diff --git a/.github/workflows/nuget_slack_notifications.yml b/.github/workflows/nuget_slack_notifications.yml index 15e812c8fa..3603fa1dde 100644 --- a/.github/workflows/nuget_slack_notifications.yml +++ b/.github/workflows/nuget_slack_notifications.yml @@ -69,6 +69,7 @@ jobs: NEW_RELIC_HOST: staging-collector.newrelic.com NEW_RELIC_LICENSE_KEY: ${{ secrets.STAGING_LICENSE_KEY }} DOTTY_LAST_RUN_TIMESTAMP: ${{ env.LAST_RUN_TIMESTAMP }} + DOTTY_SEARCH_ROOT_PATH: ${{ github.workspace }} run: | if [ ${{ inputs.daysToSearch }} != "" ]; then diff --git a/.github/workflows/scripts/nugetSlackNotifications/CsprojHandler.cs b/.github/workflows/scripts/nugetSlackNotifications/CsprojHandler.cs new file mode 100644 index 0000000000..cb907621ab --- /dev/null +++ b/.github/workflows/scripts/nugetSlackNotifications/CsprojHandler.cs @@ -0,0 +1,94 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Xml.Serialization; +using Serilog; + +namespace nugetSlackNotifications +{ + public class CsprojHandler + { + public static async Task> UpdatePackageReferences(string csprojPath, List versionDatas) + { + var updateLog = new List(); + var csprojLines = await File.ReadAllLinesAsync(csprojPath); + + var packages = Parse(csprojLines); + if (packages.Count == 0) + { + Log.Warning("No packages found in csproj file " + csprojPath); + return updateLog; + } + + foreach (var versionData in versionDatas) + { + var matchingPackages = packages.Where(p => p.Include == versionData.PackageName).ToList(); + if (matchingPackages.Count == 0) + { + Log.Warning($"No matching packages found in csproj file for {versionData.PackageName}"); + continue; + } + + foreach (var package in matchingPackages) + { + if(package.VersionAsVersion < versionData.NewVersionAsVersion && package.Pin) + { + Log.Warning($"Not updating {package.Include} for {package.TargetFramework}, it is pinned to {package.Version}. Manual verification recommended."); + continue; + } + + if (package.VersionAsVersion < versionData.NewVersionAsVersion) + { + Log.Information($"Updating {package.Include} from {package.Version} to {versionData.NewVersion}"); + var pattern = @"\d+(\.\d+){2,3}"; + var result = Regex.Replace(csprojLines[package.LineNumber], pattern, versionData.NewVersion); + csprojLines[package.LineNumber] = result; + + updateLog.Add($"- Package [{versionData.PackageName}]({versionData.Url}) " + + $"for {package.TargetFramework} " + + $"was updated from {versionData.OldVersion} to {versionData.NewVersion} " + + $"on {versionData.PublishDate.ToShortDateString()}."); + } + } + } + + await File.WriteAllLinesAsync(csprojPath, csprojLines); + updateLog.Add(""); + return updateLog; + } + + private static List Parse(string[] csprojLines) + { + var packages = new List(); + try + { + for (int i = 0; i < csprojLines.Length; i++) + { + var line = csprojLines[i]; + if (!line.Contains("PackageReference")) + { + continue; + } + + var serializer = new XmlSerializer(typeof(PackageReference)); + using (var reader = new StringReader(line)) + { + var packageReference = (PackageReference)serializer.Deserialize(reader); + packageReference.LineNumber = i; + packages.Add(packageReference); + } + } + + return packages; + } + catch (Exception e) + { + Log.Error(e, "XML issue"); + return packages; + } + } + } +} diff --git a/.github/workflows/scripts/nugetSlackNotifications/NugetVersionData.cs b/.github/workflows/scripts/nugetSlackNotifications/NugetVersionData.cs new file mode 100644 index 0000000000..1ac0928723 --- /dev/null +++ b/.github/workflows/scripts/nugetSlackNotifications/NugetVersionData.cs @@ -0,0 +1,24 @@ +using System; + +namespace nugetSlackNotifications +{ + public class NugetVersionData + { + public string PackageName { get; set; } + public string OldVersion { get; set; } + public string NewVersion { get; set; } + public Version NewVersionAsVersion { get; set; } + public string Url { get; set; } + public DateTime PublishDate { get; set; } + + public NugetVersionData(string packageName, string oldVersion, string newVersion, string url, DateTime publishDate) + { + PackageName = packageName; + OldVersion = oldVersion; + NewVersion = newVersion; + NewVersionAsVersion = new Version(newVersion); + Url = url; + PublishDate = publishDate; + } + } +} diff --git a/.github/workflows/scripts/nugetSlackNotifications/PackageInfo.cs b/.github/workflows/scripts/nugetSlackNotifications/PackageInfo.cs new file mode 100644 index 0000000000..56f2509b89 --- /dev/null +++ b/.github/workflows/scripts/nugetSlackNotifications/PackageInfo.cs @@ -0,0 +1,16 @@ +using System.Text.Json.Serialization; + +namespace nugetSlackNotifications +{ + public class PackageInfo + { + [JsonPropertyName("packageName")] + public string PackageName { get; set; } + [JsonPropertyName("ignorePatch")] + public bool IgnorePatch { get; set; } + [JsonPropertyName("ignoreMinor")] + public bool IgnoreMinor { get; set; } + [JsonPropertyName("ignoreReason")] + public string IgnoreReason {get; set;} + } +} diff --git a/.github/workflows/scripts/nugetSlackNotifications/PackageReference.cs b/.github/workflows/scripts/nugetSlackNotifications/PackageReference.cs new file mode 100644 index 0000000000..06235055f8 --- /dev/null +++ b/.github/workflows/scripts/nugetSlackNotifications/PackageReference.cs @@ -0,0 +1,40 @@ +using System; +using System.Text.RegularExpressions; +using System.Xml.Serialization; + +namespace nugetSlackNotifications +{ + public class PackageReference + { + [XmlAttribute] + public string Include { get; set; } + + [XmlAttribute] + public string Version { get; set; } + + [XmlIgnore] + public Version VersionAsVersion => new Version(Version); + + [XmlIgnore] + public int LineNumber { get; set; } + + [XmlAttribute] + public string Condition { get; set; } + + public string TargetFramework + { + get + { + if (Condition == null) + { + return null; + } + var match = Regex.Match(Condition, @"net\d+\.*\d+"); + return match.Success ? match.Value : null; + } + } + + [XmlAttribute] + public bool Pin { get; set; } + } +} diff --git a/.github/workflows/scripts/nugetSlackNotifications/Program.cs b/.github/workflows/scripts/nugetSlackNotifications/Program.cs index 88243a5bc0..f11272d1ea 100644 --- a/.github/workflows/scripts/nugetSlackNotifications/Program.cs +++ b/.github/workflows/scripts/nugetSlackNotifications/Program.cs @@ -8,13 +8,13 @@ using System.Net.Http; using System.Text; using System.Text.Json; -using System.Text.Json.Serialization; using System.Threading.Tasks; using NuGet.Common; using NuGet.Configuration; using NuGet.Protocol; using NuGet.Protocol.Core.Types; using Repository = NuGet.Protocol.Core.Types.Repository; +using System.IO; namespace nugetSlackNotifications { @@ -28,8 +28,11 @@ public class Program private static readonly string _webhook = Environment.GetEnvironmentVariable("DOTTY_WEBHOOK"); private static readonly string _githubToken = Environment.GetEnvironmentVariable("DOTTY_TOKEN"); private static readonly DateTimeOffset _lastRunTimestamp = DateTimeOffset.TryParse(Environment.GetEnvironmentVariable("DOTTY_LAST_RUN_TIMESTAMP"), out var timestamp) ? timestamp : DateTimeOffset.MinValue; + private static readonly string _searchRootPath = Environment.GetEnvironmentVariable("DOTTY_SEARCH_ROOT_PATH") ?? "."; private const string PackageInfoFilename = "packageInfo.json"; - + private const string ProjectsJsonFilename = "projectInfo.json"; + private const string Owner = "newrelic"; + private const string Repo = "newrelic-dotnet-agent"; static async Task Main() { @@ -48,15 +51,14 @@ static async Task Main() var metadataResource = await sourceRepository.GetResourceAsync(); var sourceCacheContext = new SourceCacheContext(); - if (!System.IO.File.Exists(PackageInfoFilename)) + if (!File.Exists(PackageInfoFilename)) { Log.Error($"{PackageInfoFilename} not found in the current directory. Exiting."); return; } - var packageInfoJson = await System.IO.File.ReadAllTextAsync(PackageInfoFilename); + var packageInfoJson = await File.ReadAllTextAsync(PackageInfoFilename); var packageInfos = JsonSerializer.Deserialize(packageInfoJson); - foreach (var package in packageInfos) { try @@ -70,12 +72,44 @@ static async Task Main() } } - await AlertOnNewVersions(); - await CreateGithubIssuesForNewVersions(); + if (!File.Exists(ProjectsJsonFilename)) + { + Log.Error($"{ProjectsJsonFilename} not found in the current directory. Exiting."); + return; + } + + var updateLog = new List(); + var projectInfoJson = await File.ReadAllTextAsync(ProjectsJsonFilename); + var projectInfos = JsonSerializer.Deserialize(projectInfoJson); + foreach (var projectInfo in projectInfos) + { + var projectFile = Path.Combine(_searchRootPath, projectInfo.ProjectFile); + if (!File.Exists(projectFile)) + { + Log.Warning($"Could not find {projectFile}, make sure projectFile path is relative."); + continue; + } + + var projectLog = await CsprojHandler.UpdatePackageReferences(projectFile, _newVersions); + if (projectLog.Count > 0) + { + updateLog.Add($"**{projectInfo.ProjectFile}**"); + updateLog.AddRange(projectLog); + } + + } + + var prUrl = await CreateGithubPullRequestForNewVersions(projectInfos, string.Join('\n', updateLog)); + await AlertOnNewVersions(prUrl); + + // Currently don'y want to create issues, but may in the future + // If/When we do, this shuold be moved above the PR creation so we can link issues to the PR + //await CreateGithubIssuesForNewVersions(); } [Transaction] - static async Task CheckPackage(PackageInfo package, PackageMetadataResource metadataResource, SourceCacheContext sourceCacheContext, DateTimeOffset searchTime) + static async Task CheckPackage(PackageInfo package, PackageMetadataResource metadataResource, + SourceCacheContext sourceCacheContext, DateTimeOffset searchTime) { var packageName = package.PackageName; @@ -106,7 +140,7 @@ static async Task CheckPackage(PackageInfo package, PackageMetadataResource meta { if (previousVersion.Major == latestVersion.Major && previousVersion.Minor == latestVersion.Minor) { - Log.Information($"Package {packageName} ignores Patch version updates; the Minor version ({latestVersion.Major}.{latestVersion.Minor:2}) has not been updated."); + Log.Information($"Package {packageName} ignores Patch version updates; the Minor version ({latestVersion.Major}.{latestVersion.Minor}) has not been updated."); return; } } @@ -134,7 +168,7 @@ static async Task CheckPackage(PackageInfo package, PackageMetadataResource meta } [Transaction] - static async Task AlertOnNewVersions() + static async Task AlertOnNewVersions(string prUrl) { if (_newVersions.Count > 0 && _webhook != null && !_testMode) // only message channel if there's package updates to report AND we have a webhook from the environment AND we're not in test mode @@ -144,6 +178,10 @@ static async Task AlertOnNewVersions() { msg += $"\n\t:package: {versionData.PackageName} {versionData.OldVersion} :point_right: <{versionData.Url}|{versionData.NewVersion}>"; } + + msg += $"\n\nI did the work so you won't have to!"; + msg += $"\n" + prUrl + "\n"; + msg += $"\nThanks and have a wonderful {DateTime.Now.DayOfWeek}."; await SendSlackNotification(msg); @@ -171,7 +209,7 @@ static async Task CreateGithubIssuesForNewVersions() }; newIssue.Labels.Add("testing"); newIssue.Labels.Add("Core Technologies"); - var issue = await ghClient.Issue.Create("newrelic", "newrelic-dotnet-agent", newIssue); + var issue = await ghClient.Issue.Create(Owner, Repo, newIssue); Log.Information($"Created issue #{issue.Id} for {versionData.PackageName} update to {versionData.NewVersion} in newrelic/newrelic-dotnet-agent."); } } @@ -181,6 +219,55 @@ static async Task CreateGithubIssuesForNewVersions() } } + [Transaction] + static async Task CreateGithubPullRequestForNewVersions(IEnumerable projectInfos, string updateLog) + { + + if (_newVersions.Count > 0 && _githubToken != null && !_testMode) // only message channel if there's package updates to report AND we have a GH token from the environment AND we're not in test mode + { + var ghClient = new GitHubClient(new ProductHeaderValue("Dotty-Robot")); + var tokenAuth = new Credentials(_githubToken); + ghClient.Credentials = tokenAuth; + + var masterReference = await ghClient.Git.Reference.Get(Owner, Repo, "heads/main"); + var branchName = $"dotty/test-updates-{DateTime.Now.ToString("yyyy-MMM-dd")}"; + var newBranch = new NewReference($"refs/heads/{branchName}", masterReference.Object.Sha); + await ghClient.Git.Reference.Create(Owner, Repo, newBranch); + var latestCommit = await ghClient.Git.Commit.Get(Owner, Repo, masterReference.Object.Sha); + var nt = new NewTree { BaseTree = latestCommit.Tree.Sha }; + foreach (var projectInfo in projectInfos) + { + // string.Join with \n seems to allow github to see the changed lines and not the entire file as "changed" + nt.Tree.Add(new NewTreeItem + { + Path = projectInfo.ProjectFile, + Mode = "100644", + Type = TreeType.Blob, + Content = string.Join('\n', await File.ReadAllLinesAsync(Path.Combine(_searchRootPath, projectInfo.ProjectFile))) + }); + } + + var newTree = await ghClient.Git.Tree.Create(Owner, Repo, nt); + var commitMessage = "test:Dotty instrumentation library updates for " + DateTime.Now.ToString("yyyy-MMM-dd"); + var newCommit = new NewCommit(commitMessage, newTree.Sha, masterReference.Object.Sha); + var commit = await ghClient.Git.Commit.Create(Owner, Repo, newCommit); + var branchref = await ghClient.Git.Reference.Update(Owner, Repo, $"heads/{branchName}", new ReferenceUpdate(commit.Sha)); + Log.Information($"Successfully created {branchName} branch."); + + var newPr = new NewPullRequest(commitMessage, branchName, "main"); + newPr.Body = "Dotty updated the following for your convenience.\n\n" + updateLog; + var pullRequest = await ghClient.PullRequest.Create(Owner, Repo, newPr); + Log.Information($"Successfully created PR for {branchName} at {pullRequest.HtmlUrl}"); + + return pullRequest.HtmlUrl; + } + else + { + Log.Information($"Pull request will not be created: # of new versions={_newVersions.Count}, token available={_webhook != null}, test mode={_testMode}"); + return ""; + } + } + [Trace] static async Task SendSlackNotification(string msg) { @@ -212,34 +299,4 @@ static async Task SendSlackNotification(string msg) } } } - - public class NugetVersionData - { - public string PackageName { get; set; } - public string OldVersion { get; set; } - public string NewVersion { get; set; } - public string Url { get; set; } - public DateTime PublishDate { get; set; } - - public NugetVersionData(string packageName, string oldVersion, string newVersion, string url, DateTime publishDate) - { - PackageName = packageName; - OldVersion = oldVersion; - NewVersion = newVersion; - Url = url; - PublishDate = publishDate; - } - } - - public class PackageInfo - { - [JsonPropertyName("packageName")] - public string PackageName { get; set; } - [JsonPropertyName("ignorePatch")] - public bool IgnorePatch { get; set; } - [JsonPropertyName("ignoreMinor")] - public bool IgnoreMinor { get; set; } - [JsonPropertyName("ignoreReason")] - public string IgnoreReason {get; set;} - } } diff --git a/.github/workflows/scripts/nugetSlackNotifications/ProjectInfo.cs b/.github/workflows/scripts/nugetSlackNotifications/ProjectInfo.cs new file mode 100644 index 0000000000..ffbc7ea8ff --- /dev/null +++ b/.github/workflows/scripts/nugetSlackNotifications/ProjectInfo.cs @@ -0,0 +1,10 @@ +using System.Text.Json.Serialization; + +namespace nugetSlackNotifications +{ + public class ProjectInfo + { + [JsonPropertyName("projectFile")] + public string ProjectFile { get; set; } + } +} diff --git a/.github/workflows/scripts/nugetSlackNotifications/nugetSlackNotifications.csproj b/.github/workflows/scripts/nugetSlackNotifications/nugetSlackNotifications.csproj index ba3a9c3ed1..4411b0d649 100644 --- a/.github/workflows/scripts/nugetSlackNotifications/nugetSlackNotifications.csproj +++ b/.github/workflows/scripts/nugetSlackNotifications/nugetSlackNotifications.csproj @@ -1,4 +1,4 @@ - + Exe @@ -20,6 +20,9 @@ PreserveNewest + + PreserveNewest + diff --git a/.github/workflows/scripts/nugetSlackNotifications/projectInfo.json b/.github/workflows/scripts/nugetSlackNotifications/projectInfo.json new file mode 100644 index 0000000000..3cfb1def2c --- /dev/null +++ b/.github/workflows/scripts/nugetSlackNotifications/projectInfo.json @@ -0,0 +1,5 @@ +[ + { + "projectFile": "tests/Agent/IntegrationTests/SharedApplications/Common/MFALatestPackages/MFALatestPackages.csproj" + } +] diff --git a/src/Agent/NewRelic/Agent/Core/AgentHealth/AgentHealthReporter.cs b/src/Agent/NewRelic/Agent/Core/AgentHealth/AgentHealthReporter.cs index 97b6653d4b..2d06016dff 100644 --- a/src/Agent/NewRelic/Agent/Core/AgentHealth/AgentHealthReporter.cs +++ b/src/Agent/NewRelic/Agent/Core/AgentHealth/AgentHealthReporter.cs @@ -57,8 +57,8 @@ public AgentHealthReporter(IMetricBuilder metricBuilder, IScheduler scheduler) public override void Dispose() { - base.Dispose(); _scheduler.StopExecuting(LogPeriodicReport); + base.Dispose(); } private void LogPeriodicReport() @@ -78,7 +78,7 @@ private void LogPeriodicReport() } } var message = events.Count > 0 ? string.Join(", ", events) : "No events"; - Log.Info($"In the last {_timeBetweenExecutions.TotalMinutes} minutes: {message}"); + Log.Info($"AgentHealthReporter: In the last {_timeBetweenExecutions.TotalMinutes} minutes: {message}"); } public void ReportSupportabilityCountMetric(string metricName, long count = 1) diff --git a/src/Agent/NewRelic/Agent/Core/AgentManager.cs b/src/Agent/NewRelic/Agent/Core/AgentManager.cs index 94e513fde0..e355ec5a3a 100644 --- a/src/Agent/NewRelic/Agent/Core/AgentManager.cs +++ b/src/Agent/NewRelic/Agent/Core/AgentManager.cs @@ -395,7 +395,7 @@ private void Shutdown(bool cleanShutdown) try { - Log.Debug("Starting the shutdown process for the .NET Agent."); + Log.Info("Starting the shutdown process for the .NET Agent."); AgentInitializer.OnExit -= ProcessExit; @@ -408,15 +408,17 @@ private void Shutdown(bool cleanShutdown) Log.Debug("Shutting down public agent services..."); StopServices(); - Log.Info("The New Relic .NET Agent v{0} has shutdown (pid {1}) on app domain '{2}'", AgentInstallConfiguration.AgentVersion, AgentInstallConfiguration.ProcessId, AgentInstallConfiguration.AppDomainAppVirtualPath ?? AgentInstallConfiguration.AppDomainName); } catch (Exception e) { - Log.Debug(e, "Shutdown error"); + Log.Info(e, "Unexpected exception during agent shutdown"); } finally { + Log.Debug("Shutting down internal agent services..."); Dispose(); + + Log.Info("The New Relic .NET Agent v{Version} has shutdown (pid {pid}) on app domain '{appDomain}'", AgentInstallConfiguration.AgentVersion, AgentInstallConfiguration.ProcessId, AgentInstallConfiguration.AppDomainAppVirtualPath ?? AgentInstallConfiguration.AppDomainName); Serilog.Log.CloseAndFlush(); } } diff --git a/src/Agent/NewRelic/Agent/Core/Aggregators/AbstractAggregator.cs b/src/Agent/NewRelic/Agent/Core/Aggregators/AbstractAggregator.cs index e3fdb71ff0..a750fb2be5 100644 --- a/src/Agent/NewRelic/Agent/Core/Aggregators/AbstractAggregator.cs +++ b/src/Agent/NewRelic/Agent/Core/Aggregators/AbstractAggregator.cs @@ -82,8 +82,8 @@ private void OnPreCleanShutdown(PreCleanShutdownEvent obj) public override void Dispose() { - base.Dispose(); _scheduler.StopExecuting(Harvest); + base.Dispose(); } } diff --git a/src/Agent/NewRelic/Agent/Core/Aggregators/CustomEventAggregator.cs b/src/Agent/NewRelic/Agent/Core/Aggregators/CustomEventAggregator.cs index 3a11e9051c..b974b6a017 100644 --- a/src/Agent/NewRelic/Agent/Core/Aggregators/CustomEventAggregator.cs +++ b/src/Agent/NewRelic/Agent/Core/Aggregators/CustomEventAggregator.cs @@ -43,8 +43,9 @@ public CustomEventAggregator(IDataTransportService dataTransportService, ISchedu public override void Dispose() { - base.Dispose(); _readerWriterLockSlim.Dispose(); + + base.Dispose(); } protected override TimeSpan HarvestCycle => _configuration.CustomEventsHarvestCycle; diff --git a/src/Agent/NewRelic/Agent/Core/Aggregators/ErrorEventAggregator.cs b/src/Agent/NewRelic/Agent/Core/Aggregators/ErrorEventAggregator.cs index a3e82f8099..3a5d6de467 100644 --- a/src/Agent/NewRelic/Agent/Core/Aggregators/ErrorEventAggregator.cs +++ b/src/Agent/NewRelic/Agent/Core/Aggregators/ErrorEventAggregator.cs @@ -51,8 +51,8 @@ public ErrorEventAggregator(IDataTransportService dataTransportService, ISchedul public override void Dispose() { - base.Dispose(); _readerWriterLock.Dispose(); + base.Dispose(); } public override void Collect(ErrorEventWireModel errorEventWireModel) diff --git a/src/Agent/NewRelic/Agent/Core/Aggregators/ErrorTraceAggregator.cs b/src/Agent/NewRelic/Agent/Core/Aggregators/ErrorTraceAggregator.cs index 612a984bca..ef7c49ae9b 100644 --- a/src/Agent/NewRelic/Agent/Core/Aggregators/ErrorTraceAggregator.cs +++ b/src/Agent/NewRelic/Agent/Core/Aggregators/ErrorTraceAggregator.cs @@ -39,8 +39,8 @@ public ErrorTraceAggregator(IDataTransportService dataTransportService, ISchedul public override void Dispose() { - base.Dispose(); _readerWriterLock.Dispose(); + base.Dispose(); } protected override TimeSpan HarvestCycle => _configuration.ErrorTracesHarvestCycle; diff --git a/src/Agent/NewRelic/Agent/Core/Aggregators/LogEventAggregator.cs b/src/Agent/NewRelic/Agent/Core/Aggregators/LogEventAggregator.cs index 825e8fc4c2..fbfd391441 100644 --- a/src/Agent/NewRelic/Agent/Core/Aggregators/LogEventAggregator.cs +++ b/src/Agent/NewRelic/Agent/Core/Aggregators/LogEventAggregator.cs @@ -45,11 +45,6 @@ public LogEventAggregator(IDataTransportService dataTransportService, IScheduler protected override TimeSpan HarvestCycle => _configuration.LogEventsHarvestCycle; protected override bool IsEnabled => _configuration.LogEventCollectorEnabled; - public override void Dispose() - { - base.Dispose(); - } - public override void Collect(LogEventWireModel loggingEventWireModel) { _agentHealthReporter.ReportLoggingEventCollected(); diff --git a/src/Agent/NewRelic/Agent/Core/Aggregators/SpanEventAggregator.cs b/src/Agent/NewRelic/Agent/Core/Aggregators/SpanEventAggregator.cs index 1001b4053b..45813b29bc 100644 --- a/src/Agent/NewRelic/Agent/Core/Aggregators/SpanEventAggregator.cs +++ b/src/Agent/NewRelic/Agent/Core/Aggregators/SpanEventAggregator.cs @@ -67,8 +67,8 @@ public SpanEventAggregator(IDataTransportService dataTransportService, ISchedule public override void Dispose() { - base.Dispose(); _readerWriterLockSlim.Dispose(); + base.Dispose(); } public override void Collect(ISpanEventWireModel wireModel) diff --git a/src/Agent/NewRelic/Agent/Core/Aggregators/TransactionEventAggregator.cs b/src/Agent/NewRelic/Agent/Core/Aggregators/TransactionEventAggregator.cs index 2f8aa1c8fd..b6af92a475 100644 --- a/src/Agent/NewRelic/Agent/Core/Aggregators/TransactionEventAggregator.cs +++ b/src/Agent/NewRelic/Agent/Core/Aggregators/TransactionEventAggregator.cs @@ -49,8 +49,8 @@ public TransactionEventAggregator(IDataTransportService dataTransportService, IS public override void Dispose() { - base.Dispose(); _readerWriterLock.Dispose(); + base.Dispose(); } public override void Collect(TransactionEventWireModel transactionEventWireModel) diff --git a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/NRWebRequestClient.cs b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/NRWebRequestClient.cs index d839d25dcf..decca35808 100644 --- a/src/Agent/NewRelic/Agent/Core/DataTransport/Client/NRWebRequestClient.cs +++ b/src/Agent/NewRelic/Agent/Core/DataTransport/Client/NRWebRequestClient.cs @@ -82,11 +82,6 @@ public override IHttpResponse Send(IHttpRequest request) } } - public override void Dispose() - { - base.Dispose(); - } - // for unit testing only public void SetHttpWebRequestFunc(Func getHttpWebRequestFunc ) { diff --git a/src/Agent/NewRelic/Agent/Core/DependencyInjection/AgentContainer.cs b/src/Agent/NewRelic/Agent/Core/DependencyInjection/AgentContainer.cs index 0923797b62..9db6d19a79 100644 --- a/src/Agent/NewRelic/Agent/Core/DependencyInjection/AgentContainer.cs +++ b/src/Agent/NewRelic/Agent/Core/DependencyInjection/AgentContainer.cs @@ -16,7 +16,7 @@ public class AgentContainer : IContainer // use the scope instead of the container to resolve instances. This allows us to replace registrations in a new scope for unit testing private ILifetimeScope _scope; - private bool _disposedValue; + private bool _disposed; private readonly Dictionary _registrationsToReplace = new Dictionary(); public AgentContainer() @@ -102,7 +102,7 @@ public IEnumerable ResolveAll() protected virtual void Dispose(bool disposing) { - if (!_disposedValue) + if (!_disposed) { if (disposing) { @@ -113,7 +113,7 @@ protected virtual void Dispose(bool disposing) _container = null; } - _disposedValue = true; + _disposed = true; } } diff --git a/src/Agent/NewRelic/Agent/Core/Samplers/AbstractSampler.cs b/src/Agent/NewRelic/Agent/Core/Samplers/AbstractSampler.cs index eb2edc305c..80f9172c0e 100644 --- a/src/Agent/NewRelic/Agent/Core/Samplers/AbstractSampler.cs +++ b/src/Agent/NewRelic/Agent/Core/Samplers/AbstractSampler.cs @@ -32,8 +32,8 @@ protected AbstractSampler(IScheduler scheduler, TimeSpan frequency) public override void Dispose() { - base.Dispose(); Stop(); + base.Dispose(); } protected override void OnConfigurationUpdated(ConfigurationUpdateSource configurationUpdateSource) diff --git a/src/Agent/NewRelic/Agent/Core/Samplers/GCSamplerNetCore.cs b/src/Agent/NewRelic/Agent/Core/Samplers/GCSamplerNetCore.cs index d473180c2d..238dfe0492 100644 --- a/src/Agent/NewRelic/Agent/Core/Samplers/GCSamplerNetCore.cs +++ b/src/Agent/NewRelic/Agent/Core/Samplers/GCSamplerNetCore.cs @@ -127,10 +127,11 @@ protected override void Stop() public override void Dispose() { - base.Dispose(); _listener?.StopListening(); _listener?.Dispose(); _listener = null; + + base.Dispose(); } } diff --git a/src/Agent/NewRelic/Agent/Core/Samplers/ThreadStatsSampler.cs b/src/Agent/NewRelic/Agent/Core/Samplers/ThreadStatsSampler.cs index 37e320646b..72b3aee3a3 100644 --- a/src/Agent/NewRelic/Agent/Core/Samplers/ThreadStatsSampler.cs +++ b/src/Agent/NewRelic/Agent/Core/Samplers/ThreadStatsSampler.cs @@ -77,12 +77,13 @@ protected override void Stop() public override void Dispose() { - base.Dispose(); _listener?.StopListening(); #if NETFRAMEWORK // calling .Dispose() in .NET 7 explodes. No idea why. _listener?.Dispose(); #endif _listener = null; + + base.Dispose(); } } diff --git a/src/Agent/NewRelic/Agent/Core/SharedInterfaces/PerformanceCounterProxy.cs b/src/Agent/NewRelic/Agent/Core/SharedInterfaces/PerformanceCounterProxy.cs index 1772f933cd..a15e738885 100644 --- a/src/Agent/NewRelic/Agent/Core/SharedInterfaces/PerformanceCounterProxy.cs +++ b/src/Agent/NewRelic/Agent/Core/SharedInterfaces/PerformanceCounterProxy.cs @@ -17,8 +17,7 @@ public interface IPerformanceCounterProxy : IDisposable public class PerformanceCounterProxy : IPerformanceCounterProxy { - private readonly PerformanceCounter _counter; - private bool _counterIsDisposed = false; + private PerformanceCounter _counter; public PerformanceCounterProxy(string categoryName, string counterName, string instanceName) { @@ -32,10 +31,10 @@ public float NextValue() public void Dispose() { - if (_counter != null && !_counterIsDisposed) + if (_counter != null) { _counter.Dispose(); - _counterIsDisposed = true; + _counter = null; } } } diff --git a/src/Agent/NewRelic/Agent/Core/Time/Scheduler.cs b/src/Agent/NewRelic/Agent/Core/Time/Scheduler.cs index 89230fc359..ce03e33044 100644 --- a/src/Agent/NewRelic/Agent/Core/Time/Scheduler.cs +++ b/src/Agent/NewRelic/Agent/Core/Time/Scheduler.cs @@ -202,10 +202,7 @@ public void Dispose() foreach (var timer in _recurringTimers.Values) { - if (timer != null) - { - timer.Dispose(); - } + timer?.Dispose(); } _recurringTimers.Clear(); } @@ -219,8 +216,7 @@ private class TimerStatus : IDisposable public void Dispose() { var timer = Timer; - if (timer != null) - timer.Dispose(); + timer?.Dispose(); } } } diff --git a/tests/Agent/PlatformTests/Applications/AgentLogHelper/AgentLog.cs b/tests/Agent/PlatformTests/Applications/AgentLogHelper/AgentLog.cs deleted file mode 100644 index e75163d9b6..0000000000 --- a/tests/Agent/PlatformTests/Applications/AgentLogHelper/AgentLog.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace AgentLogHelper -{ - public class AgentLog - { - private const string ProfilerLogNamePrefix = "NewRelic.Profiler."; - private const string ConnectString = @"Invoking ""connect"" with : ["; - - private readonly int _processId; - private readonly string _agentLogPath; - private readonly string _profilerLogPath; - - public AgentLog(string agentLogFolderPath) - { - var searchPattern = "newrelic_agent_*.log"; - var mostRecentlyUpdatedFile = Directory.EnumerateFiles(agentLogFolderPath, searchPattern) - .Where(file => file != null && !file.Contains("audit")) - .OrderByDescending(File.GetLastWriteTimeUtc) - .FirstOrDefault(); - - _agentLogPath = mostRecentlyUpdatedFile; - _processId = Process.GetCurrentProcess().Id; - _profilerLogPath = Path.Combine(agentLogFolderPath, ProfilerLogNamePrefix + _processId + ".log"); - } - - public string GetAgentLog(string hasString = ConnectString) - { - var logString = String.Empty; - var stopWatch = new Stopwatch(); - stopWatch.Start(); - - while (stopWatch.Elapsed < TimeSpan.FromMinutes(3)) - { - try - { - logString = Readfile(_agentLogPath); - var logLines = logString.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); - - foreach (var line in logLines) - { - if (line.Contains(hasString)) - { - return logString; - } - } - } - catch (FileNotFoundException ex) - { - - } - - Thread.Sleep(40000); - } - - stopWatch.Stop(); - return logString; - } - - public string GetProfilerLog() - { - return Readfile(_profilerLogPath); - } - - - private string Readfile(string filePath) - { - using (var filestream = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))) - { - return filestream.ReadToEnd(); - } - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/AgentLogHelper/AgentLogHelper.csproj b/tests/Agent/PlatformTests/Applications/AgentLogHelper/AgentLogHelper.csproj deleted file mode 100644 index 32473ed205..0000000000 --- a/tests/Agent/PlatformTests/Applications/AgentLogHelper/AgentLogHelper.csproj +++ /dev/null @@ -1,47 +0,0 @@ - - - - - Debug - AnyCPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B} - Library - Properties - AgentLogHelper - AgentLogHelper - v4.5 - 512 - - - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/AgentLogHelper/Properties/AssemblyInfo.cs b/tests/Agent/PlatformTests/Applications/AgentLogHelper/Properties/AssemblyInfo.cs deleted file mode 100644 index a5df719cd5..0000000000 --- a/tests/Agent/PlatformTests/Applications/AgentLogHelper/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("AgentLogHelper")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("AgentLogHelper")] -[assembly: AssemblyCopyright("Copyright © 2018")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("d811ffb5-2b9b-4d1b-b2f6-5c2557be0a6b")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication.sln b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication.sln deleted file mode 100644 index 059684fc9c..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication.sln +++ /dev/null @@ -1,31 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27428.2005 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgentLogHelper", "..\AgentLogHelper\AgentLogHelper.csproj", "{D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NetFrameworkBasicApplication", "NetFrameworkBasicApplication\NetFrameworkBasicApplication.csproj", "{2CE3DF18-F0EE-494A-94D3-5BA7BE94C249}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Release|Any CPU.Build.0 = Release|Any CPU - {2CE3DF18-F0EE-494A-94D3-5BA7BE94C249}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2CE3DF18-F0EE-494A-94D3-5BA7BE94C249}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2CE3DF18-F0EE-494A-94D3-5BA7BE94C249}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2CE3DF18-F0EE-494A-94D3-5BA7BE94C249}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {C51ED808-E127-463B-83EE-D8E3ECF2E642} - EndGlobalSection -EndGlobal diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/App_Start/FilterConfig.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/App_Start/FilterConfig.cs deleted file mode 100644 index 4768a0e5bc..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/App_Start/FilterConfig.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Web; -using System.Web.Mvc; - -namespace NetFrameworkBasicApplication -{ - public class FilterConfig - { - public static void RegisterGlobalFilters(GlobalFilterCollection filters) - { - filters.Add(new HandleErrorAttribute()); - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/App_Start/RouteConfig.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/App_Start/RouteConfig.cs deleted file mode 100644 index 3d6592912a..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/App_Start/RouteConfig.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Web; -using System.Web.Mvc; -using System.Web.Routing; - -namespace NetFrameworkBasicApplication -{ - public class RouteConfig - { - public static void RegisterRoutes(RouteCollection routes) - { - routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); - - routes.MapRoute( - name: "Default", - url: "{controller}/{action}/{id}", - defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } - ); - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/App_Start/WebApiConfig.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/App_Start/WebApiConfig.cs deleted file mode 100644 index 91cc01cb19..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/App_Start/WebApiConfig.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System.Net.Http.Headers; -using System.Web.Http; - -namespace NetFrameworkBasicApplication -{ - public static class WebApiConfig - { - public static void Register(HttpConfiguration config) - { - // Web API configuration and services - config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); - // Web API routes - config.MapHttpAttributeRoutes(); - - config.Routes.MapHttpRoute( - name: "DefaultApi", - routeTemplate: "api/{controller}/{action}/{id}", - defaults: new { id = RouteParameter.Optional } - ); - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/ApplicationInsights.config b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/ApplicationInsights.config deleted file mode 100644 index 03959d2bc7..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/ApplicationInsights.config +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ApiDescriptionExtensions.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ApiDescriptionExtensions.cs deleted file mode 100644 index 0e4ff0b24f..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ApiDescriptionExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Text; -using System.Web; -using System.Web.Http.Description; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - public static class ApiDescriptionExtensions - { - /// - /// Generates an URI-friendly ID for the . E.g. "Get-Values-id_name" instead of "GetValues/{id}?name={name}" - /// - /// The . - /// The ID as a string. - public static string GetFriendlyId(this ApiDescription description) - { - string path = description.RelativePath; - string[] urlParts = path.Split('?'); - string localPath = urlParts[0]; - string queryKeyString = null; - if (urlParts.Length > 1) - { - string query = urlParts[1]; - string[] queryKeys = HttpUtility.ParseQueryString(query).AllKeys; - queryKeyString = String.Join("_", queryKeys); - } - - StringBuilder friendlyPath = new StringBuilder(); - friendlyPath.AppendFormat("{0}-{1}", - description.HttpMethod.Method, - localPath.Replace("/", "-").Replace("{", String.Empty).Replace("}", String.Empty)); - if (queryKeyString != null) - { - friendlyPath.AppendFormat("_{0}", queryKeyString.Replace('.', '-')); - } - return friendlyPath.ToString(); - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/App_Start/HelpPageConfig.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/App_Start/HelpPageConfig.cs deleted file mode 100644 index 5c539fa3bc..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/App_Start/HelpPageConfig.cs +++ /dev/null @@ -1,113 +0,0 @@ -// Uncomment the following to provide samples for PageResult. Must also add the Microsoft.AspNet.WebApi.OData -// package to your project. -////#define Handle_PageResultOfT - -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Net.Http.Headers; -using System.Reflection; -using System.Web; -using System.Web.Http; -#if Handle_PageResultOfT -using System.Web.Http.OData; -#endif - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - /// - /// Use this class to customize the Help Page. - /// For example you can set a custom to supply the documentation - /// or you can provide the samples for the requests/responses. - /// - public static class HelpPageConfig - { - [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", - MessageId = "NetFrameworkBasicApplication.Areas.HelpPage.TextSample.#ctor(System.String)", - Justification = "End users may choose to merge this string with existing localized resources.")] - [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", - MessageId = "bsonspec", - Justification = "Part of a URI.")] - public static void Register(HttpConfiguration config) - { - //// Uncomment the following to use the documentation from XML documentation file. - //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); - - //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. - //// Also, the string arrays will be used for IEnumerable. The sample objects will be serialized into different media type - //// formats by the available formatters. - //config.SetSampleObjects(new Dictionary - //{ - // {typeof(string), "sample string"}, - // {typeof(IEnumerable), new string[]{"sample 1", "sample 2"}} - //}); - - // Extend the following to provide factories for types not handled automatically (those lacking parameterless - // constructors) or for which you prefer to use non-default property values. Line below provides a fallback - // since automatic handling will fail and GeneratePageResult handles only a single type. -#if Handle_PageResultOfT - config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); -#endif - - // Extend the following to use a preset object directly as the sample for all actions that support a media - // type, regardless of the body parameter or return type. The lines below avoid display of binary content. - // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. - config.SetSampleForMediaType( - new TextSample("Binary JSON content. See http://bsonspec.org for details."), - new MediaTypeHeaderValue("application/bson")); - - //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format - //// and have IEnumerable as the body parameter or return type. - //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable)); - - //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" - //// and action named "Put". - //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); - - //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" - //// on the controller named "Values" and action named "Get" with parameter "id". - //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); - - //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent. - //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. - //config.SetActualRequestType(typeof(string), "Values", "Get"); - - //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent. - //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. - //config.SetActualResponseType(typeof(string), "Values", "Post"); - } - -#if Handle_PageResultOfT - private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) - { - if (type.IsGenericType) - { - Type openGenericType = type.GetGenericTypeDefinition(); - if (openGenericType == typeof(PageResult<>)) - { - // Get the T in PageResult - Type[] typeParameters = type.GetGenericArguments(); - Debug.Assert(typeParameters.Length == 1); - - // Create an enumeration to pass as the first parameter to the PageResult constuctor - Type itemsType = typeof(List<>).MakeGenericType(typeParameters); - object items = sampleGenerator.GetSampleObject(itemsType); - - // Fill in the other information needed to invoke the PageResult constuctor - Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; - object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; - - // Call PageResult(IEnumerable items, Uri nextPageLink, long? count) constructor - ConstructorInfo constructor = type.GetConstructor(parameterTypes); - return constructor.Invoke(parameters); - } - } - - return null; - } -#endif - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Controllers/HelpController.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Controllers/HelpController.cs deleted file mode 100644 index 1f950ebca7..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Controllers/HelpController.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Web.Http; -using System.Web.Mvc; -using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions; -using NetFrameworkBasicApplication.Areas.HelpPage.Models; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.Controllers -{ - /// - /// The controller that will handle requests for the help page. - /// - public class HelpController : Controller - { - private const string ErrorViewName = "Error"; - - public HelpController() - : this(GlobalConfiguration.Configuration) - { - } - - public HelpController(HttpConfiguration config) - { - Configuration = config; - } - - public HttpConfiguration Configuration { get; private set; } - - public ActionResult Index() - { - ViewBag.DocumentationProvider = Configuration.Services.GetDocumentationProvider(); - return View(Configuration.Services.GetApiExplorer().ApiDescriptions); - } - - public ActionResult Api(string apiId) - { - if (!String.IsNullOrEmpty(apiId)) - { - HelpPageApiModel apiModel = Configuration.GetHelpPageApiModel(apiId); - if (apiModel != null) - { - return View(apiModel); - } - } - - return View(ErrorViewName); - } - - public ActionResult ResourceModel(string modelName) - { - if (!String.IsNullOrEmpty(modelName)) - { - ModelDescriptionGenerator modelDescriptionGenerator = Configuration.GetModelDescriptionGenerator(); - ModelDescription modelDescription; - if (modelDescriptionGenerator.GeneratedModels.TryGetValue(modelName, out modelDescription)) - { - return View(modelDescription); - } - } - - return View(ErrorViewName); - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/HelpPage.css b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/HelpPage.css deleted file mode 100644 index aff223033d..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/HelpPage.css +++ /dev/null @@ -1,134 +0,0 @@ -.help-page h1, -.help-page .h1, -.help-page h2, -.help-page .h2, -.help-page h3, -.help-page .h3, -#body.help-page, -.help-page-table th, -.help-page-table pre, -.help-page-table p { - font-family: "Segoe UI Light", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif; -} - -.help-page pre.wrapped { - white-space: -moz-pre-wrap; - white-space: -pre-wrap; - white-space: -o-pre-wrap; - white-space: pre-wrap; -} - -.help-page .warning-message-container { - margin-top: 20px; - padding: 0 10px; - color: #525252; - background: #EFDCA9; - border: 1px solid #CCCCCC; -} - -.help-page-table { - width: 100%; - border-collapse: collapse; - text-align: left; - margin: 0px 0px 20px 0px; - border-top: 1px solid #D4D4D4; -} - -.help-page-table th { - text-align: left; - font-weight: bold; - border-bottom: 1px solid #D4D4D4; - padding: 5px 6px 5px 6px; -} - -.help-page-table td { - border-bottom: 1px solid #D4D4D4; - padding: 10px 8px 10px 8px; - vertical-align: top; -} - -.help-page-table pre, -.help-page-table p { - margin: 0px; - padding: 0px; - font-family: inherit; - font-size: 100%; -} - -.help-page-table tbody tr:hover td { - background-color: #F3F3F3; -} - -.help-page a:hover { - background-color: transparent; -} - -.help-page .sample-header { - border: 2px solid #D4D4D4; - background: #00497E; - color: #FFFFFF; - padding: 8px 15px; - border-bottom: none; - display: inline-block; - margin: 10px 0px 0px 0px; -} - -.help-page .sample-content { - display: block; - border-width: 0; - padding: 15px 20px; - background: #FFFFFF; - border: 2px solid #D4D4D4; - margin: 0px 0px 10px 0px; -} - -.help-page .api-name { - width: 40%; -} - -.help-page .api-documentation { - width: 60%; -} - -.help-page .parameter-name { - width: 20%; -} - -.help-page .parameter-documentation { - width: 40%; -} - -.help-page .parameter-type { - width: 20%; -} - -.help-page .parameter-annotations { - width: 20%; -} - -.help-page h1, -.help-page .h1 { - font-size: 36px; - line-height: normal; -} - -.help-page h2, -.help-page .h2 { - font-size: 24px; -} - -.help-page h3, -.help-page .h3 { - font-size: 20px; -} - -#body.help-page { - font-size: 14px; - line-height: 143%; - color: #333; -} - -.help-page a { - color: #0000EE; - text-decoration: none; -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/HelpPageAreaRegistration.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/HelpPageAreaRegistration.cs deleted file mode 100644 index 5e842c0f73..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/HelpPageAreaRegistration.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Web.Http; -using System.Web.Mvc; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - public class HelpPageAreaRegistration : AreaRegistration - { - public override string AreaName - { - get - { - return "HelpPage"; - } - } - - public override void RegisterArea(AreaRegistrationContext context) - { - context.MapRoute( - "HelpPage_Default", - "Help/{action}/{apiId}", - new { controller = "Help", action = "Index", apiId = UrlParameter.Optional }); - - HelpPageConfig.Register(GlobalConfiguration.Configuration); - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/HelpPageConfigurationExtensions.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/HelpPageConfigurationExtensions.cs deleted file mode 100644 index 2032fc4a25..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/HelpPageConfigurationExtensions.cs +++ /dev/null @@ -1,467 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Linq; -using System.Net.Http; -using System.Net.Http.Headers; -using System.Web.Http; -using System.Web.Http.Controllers; -using System.Web.Http.Description; -using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions; -using NetFrameworkBasicApplication.Areas.HelpPage.Models; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - public static class HelpPageConfigurationExtensions - { - private const string ApiModelPrefix = "MS_HelpPageApiModel_"; - - /// - /// Sets the documentation provider for help page. - /// - /// The . - /// The documentation provider. - public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) - { - config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); - } - - /// - /// Sets the objects that will be used by the formatters to produce sample requests/responses. - /// - /// The . - /// The sample objects. - public static void SetSampleObjects(this HttpConfiguration config, IDictionary sampleObjects) - { - config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; - } - - /// - /// Sets the sample request directly for the specified media type and action. - /// - /// The . - /// The sample request. - /// The media type. - /// Name of the controller. - /// Name of the action. - public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) - { - config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); - } - - /// - /// Sets the sample request directly for the specified media type and action with parameters. - /// - /// The . - /// The sample request. - /// The media type. - /// Name of the controller. - /// Name of the action. - /// The parameter names. - public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) - { - config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); - } - - /// - /// Sets the sample request directly for the specified media type of the action. - /// - /// The . - /// The sample response. - /// The media type. - /// Name of the controller. - /// Name of the action. - public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) - { - config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); - } - - /// - /// Sets the sample response directly for the specified media type of the action with specific parameters. - /// - /// The . - /// The sample response. - /// The media type. - /// Name of the controller. - /// Name of the action. - /// The parameter names. - public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) - { - config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); - } - - /// - /// Sets the sample directly for all actions with the specified media type. - /// - /// The . - /// The sample. - /// The media type. - public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) - { - config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); - } - - /// - /// Sets the sample directly for all actions with the specified type and media type. - /// - /// The . - /// The sample. - /// The media type. - /// The parameter type or return type of an action. - public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) - { - config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); - } - - /// - /// Specifies the actual type of passed to the in an action. - /// The help page will use this information to produce more accurate request samples. - /// - /// The . - /// The type. - /// Name of the controller. - /// Name of the action. - public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) - { - config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); - } - - /// - /// Specifies the actual type of passed to the in an action. - /// The help page will use this information to produce more accurate request samples. - /// - /// The . - /// The type. - /// Name of the controller. - /// Name of the action. - /// The parameter names. - public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) - { - config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); - } - - /// - /// Specifies the actual type of returned as part of the in an action. - /// The help page will use this information to produce more accurate response samples. - /// - /// The . - /// The type. - /// Name of the controller. - /// Name of the action. - public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) - { - config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); - } - - /// - /// Specifies the actual type of returned as part of the in an action. - /// The help page will use this information to produce more accurate response samples. - /// - /// The . - /// The type. - /// Name of the controller. - /// Name of the action. - /// The parameter names. - public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) - { - config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); - } - - /// - /// Gets the help page sample generator. - /// - /// The . - /// The help page sample generator. - public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) - { - return (HelpPageSampleGenerator)config.Properties.GetOrAdd( - typeof(HelpPageSampleGenerator), - k => new HelpPageSampleGenerator()); - } - - /// - /// Sets the help page sample generator. - /// - /// The . - /// The help page sample generator. - public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) - { - config.Properties.AddOrUpdate( - typeof(HelpPageSampleGenerator), - k => sampleGenerator, - (k, o) => sampleGenerator); - } - - /// - /// Gets the model description generator. - /// - /// The configuration. - /// The - public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) - { - return (ModelDescriptionGenerator)config.Properties.GetOrAdd( - typeof(ModelDescriptionGenerator), - k => InitializeModelDescriptionGenerator(config)); - } - - /// - /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. - /// - /// The . - /// The ID. - /// - /// An - /// - public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) - { - object model; - string modelId = ApiModelPrefix + apiDescriptionId; - if (!config.Properties.TryGetValue(modelId, out model)) - { - Collection apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; - ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); - if (apiDescription != null) - { - model = GenerateApiModel(apiDescription, config); - config.Properties.TryAdd(modelId, model); - } - } - - return (HelpPageApiModel)model; - } - - private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) - { - HelpPageApiModel apiModel = new HelpPageApiModel() - { - ApiDescription = apiDescription, - }; - - ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); - HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); - GenerateUriParameters(apiModel, modelGenerator); - GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); - GenerateResourceDescription(apiModel, modelGenerator); - GenerateSamples(apiModel, sampleGenerator); - - return apiModel; - } - - private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) - { - ApiDescription apiDescription = apiModel.ApiDescription; - foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) - { - if (apiParameter.Source == ApiParameterSource.FromUri) - { - HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; - Type parameterType = null; - ModelDescription typeDescription = null; - ComplexTypeModelDescription complexTypeDescription = null; - if (parameterDescriptor != null) - { - parameterType = parameterDescriptor.ParameterType; - typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); - complexTypeDescription = typeDescription as ComplexTypeModelDescription; - } - - // Example: - // [TypeConverter(typeof(PointConverter))] - // public class Point - // { - // public Point(int x, int y) - // { - // X = x; - // Y = y; - // } - // public int X { get; set; } - // public int Y { get; set; } - // } - // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. - // - // public class Point - // { - // public int X { get; set; } - // public int Y { get; set; } - // } - // Regular complex class Point will have properties X and Y added to UriParameters collection. - if (complexTypeDescription != null - && !IsBindableWithTypeConverter(parameterType)) - { - foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) - { - apiModel.UriParameters.Add(uriParameter); - } - } - else if (parameterDescriptor != null) - { - ParameterDescription uriParameter = - AddParameterDescription(apiModel, apiParameter, typeDescription); - - if (!parameterDescriptor.IsOptional) - { - uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); - } - - object defaultValue = parameterDescriptor.DefaultValue; - if (defaultValue != null) - { - uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); - } - } - else - { - Debug.Assert(parameterDescriptor == null); - - // If parameterDescriptor is null, this is an undeclared route parameter which only occurs - // when source is FromUri. Ignored in request model and among resource parameters but listed - // as a simple string here. - ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); - AddParameterDescription(apiModel, apiParameter, modelDescription); - } - } - } - } - - private static bool IsBindableWithTypeConverter(Type parameterType) - { - if (parameterType == null) - { - return false; - } - - return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); - } - - private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, - ApiParameterDescription apiParameter, ModelDescription typeDescription) - { - ParameterDescription parameterDescription = new ParameterDescription - { - Name = apiParameter.Name, - Documentation = apiParameter.Documentation, - TypeDescription = typeDescription, - }; - - apiModel.UriParameters.Add(parameterDescription); - return parameterDescription; - } - - private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) - { - ApiDescription apiDescription = apiModel.ApiDescription; - foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) - { - if (apiParameter.Source == ApiParameterSource.FromBody) - { - Type parameterType = apiParameter.ParameterDescriptor.ParameterType; - apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); - apiModel.RequestDocumentation = apiParameter.Documentation; - } - else if (apiParameter.ParameterDescriptor != null && - apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) - { - Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); - - if (parameterType != null) - { - apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); - } - } - } - } - - private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) - { - ResponseDescription response = apiModel.ApiDescription.ResponseDescription; - Type responseType = response.ResponseType ?? response.DeclaredType; - if (responseType != null && responseType != typeof(void)) - { - apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); - } - } - - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] - private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) - { - try - { - foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) - { - apiModel.SampleRequests.Add(item.Key, item.Value); - LogInvalidSampleAsError(apiModel, item.Value); - } - - foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) - { - apiModel.SampleResponses.Add(item.Key, item.Value); - LogInvalidSampleAsError(apiModel, item.Value); - } - } - catch (Exception e) - { - apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, - "An exception has occurred while generating the sample. Exception message: {0}", - HelpPageSampleGenerator.UnwrapException(e).Message)); - } - } - - private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) - { - parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( - p => p.Source == ApiParameterSource.FromBody || - (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); - - if (parameterDescription == null) - { - resourceType = null; - return false; - } - - resourceType = parameterDescription.ParameterDescriptor.ParameterType; - - if (resourceType == typeof(HttpRequestMessage)) - { - HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); - resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); - } - - if (resourceType == null) - { - parameterDescription = null; - return false; - } - - return true; - } - - private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) - { - ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); - Collection apis = config.Services.GetApiExplorer().ApiDescriptions; - foreach (ApiDescription api in apis) - { - ApiParameterDescription parameterDescription; - Type parameterType; - if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) - { - modelGenerator.GetOrCreateModelDescription(parameterType); - } - } - return modelGenerator; - } - - private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) - { - InvalidSample invalidSample = sample as InvalidSample; - if (invalidSample != null) - { - apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); - } - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs deleted file mode 100644 index 76aace1c9d..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public class CollectionModelDescription : ModelDescription - { - public ModelDescription ElementDescription { get; set; } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs deleted file mode 100644 index 4ad0dc4f85..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.ObjectModel; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public class ComplexTypeModelDescription : ModelDescription - { - public ComplexTypeModelDescription() - { - Properties = new Collection(); - } - - public Collection Properties { get; private set; } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs deleted file mode 100644 index d3526fd53b..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public class DictionaryModelDescription : KeyValuePairModelDescription - { - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs deleted file mode 100644 index 0f83877e91..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/EnumTypeModelDescription.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Collections.Generic; -using System.Collections.ObjectModel; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public class EnumTypeModelDescription : ModelDescription - { - public EnumTypeModelDescription() - { - Values = new Collection(); - } - - public Collection Values { get; private set; } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs deleted file mode 100644 index 1554e15ddc..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public class EnumValueDescription - { - public string Documentation { get; set; } - - public string Name { get; set; } - - public string Value { get; set; } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs deleted file mode 100644 index 12d2d66f0a..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/IModelDocumentationProvider.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; -using System.Reflection; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public interface IModelDocumentationProvider - { - string GetDocumentation(MemberInfo member); - - string GetDocumentation(Type type); - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs deleted file mode 100644 index cac7d0f91c..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/KeyValuePairModelDescription.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public class KeyValuePairModelDescription : ModelDescription - { - public ModelDescription KeyModelDescription { get; set; } - - public ModelDescription ValueModelDescription { get; set; } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelDescription.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelDescription.cs deleted file mode 100644 index 5ca70961a1..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelDescription.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - /// - /// Describes a type model. - /// - public abstract class ModelDescription - { - public string Documentation { get; set; } - - public Type ModelType { get; set; } - - public string Name { get; set; } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs deleted file mode 100644 index 164ea8b015..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelDescriptionGenerator.cs +++ /dev/null @@ -1,451 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.Specialized; -using System.ComponentModel.DataAnnotations; -using System.Globalization; -using System.Reflection; -using System.Runtime.Serialization; -using System.Web.Http; -using System.Web.Http.Description; -using System.Xml.Serialization; -using Newtonsoft.Json; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - /// - /// Generates model descriptions for given types. - /// - public class ModelDescriptionGenerator - { - // Modify this to support more data annotation attributes. - private readonly IDictionary> AnnotationTextGenerator = new Dictionary> - { - { typeof(RequiredAttribute), a => "Required" }, - { typeof(RangeAttribute), a => - { - RangeAttribute range = (RangeAttribute)a; - return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); - } - }, - { typeof(MaxLengthAttribute), a => - { - MaxLengthAttribute maxLength = (MaxLengthAttribute)a; - return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); - } - }, - { typeof(MinLengthAttribute), a => - { - MinLengthAttribute minLength = (MinLengthAttribute)a; - return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); - } - }, - { typeof(StringLengthAttribute), a => - { - StringLengthAttribute strLength = (StringLengthAttribute)a; - return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); - } - }, - { typeof(DataTypeAttribute), a => - { - DataTypeAttribute dataType = (DataTypeAttribute)a; - return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); - } - }, - { typeof(RegularExpressionAttribute), a => - { - RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; - return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); - } - }, - }; - - // Modify this to add more default documentations. - private readonly IDictionary DefaultTypeDocumentation = new Dictionary - { - { typeof(Int16), "integer" }, - { typeof(Int32), "integer" }, - { typeof(Int64), "integer" }, - { typeof(UInt16), "unsigned integer" }, - { typeof(UInt32), "unsigned integer" }, - { typeof(UInt64), "unsigned integer" }, - { typeof(Byte), "byte" }, - { typeof(Char), "character" }, - { typeof(SByte), "signed byte" }, - { typeof(Uri), "URI" }, - { typeof(Single), "decimal number" }, - { typeof(Double), "decimal number" }, - { typeof(Decimal), "decimal number" }, - { typeof(String), "string" }, - { typeof(Guid), "globally unique identifier" }, - { typeof(TimeSpan), "time interval" }, - { typeof(DateTime), "date" }, - { typeof(DateTimeOffset), "date" }, - { typeof(Boolean), "boolean" }, - }; - - private Lazy _documentationProvider; - - public ModelDescriptionGenerator(HttpConfiguration config) - { - if (config == null) - { - throw new ArgumentNullException("config"); - } - - _documentationProvider = new Lazy(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); - GeneratedModels = new Dictionary(StringComparer.OrdinalIgnoreCase); - } - - public Dictionary GeneratedModels { get; private set; } - - private IModelDocumentationProvider DocumentationProvider - { - get - { - return _documentationProvider.Value; - } - } - - public ModelDescription GetOrCreateModelDescription(Type modelType) - { - if (modelType == null) - { - throw new ArgumentNullException("modelType"); - } - - Type underlyingType = Nullable.GetUnderlyingType(modelType); - if (underlyingType != null) - { - modelType = underlyingType; - } - - ModelDescription modelDescription; - string modelName = ModelNameHelper.GetModelName(modelType); - if (GeneratedModels.TryGetValue(modelName, out modelDescription)) - { - if (modelType != modelDescription.ModelType) - { - throw new InvalidOperationException( - String.Format( - CultureInfo.CurrentCulture, - "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + - "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", - modelName, - modelDescription.ModelType.FullName, - modelType.FullName)); - } - - return modelDescription; - } - - if (DefaultTypeDocumentation.ContainsKey(modelType)) - { - return GenerateSimpleTypeModelDescription(modelType); - } - - if (modelType.IsEnum) - { - return GenerateEnumTypeModelDescription(modelType); - } - - if (modelType.IsGenericType) - { - Type[] genericArguments = modelType.GetGenericArguments(); - - if (genericArguments.Length == 1) - { - Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); - if (enumerableType.IsAssignableFrom(modelType)) - { - return GenerateCollectionModelDescription(modelType, genericArguments[0]); - } - } - if (genericArguments.Length == 2) - { - Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); - if (dictionaryType.IsAssignableFrom(modelType)) - { - return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); - } - - Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); - if (keyValuePairType.IsAssignableFrom(modelType)) - { - return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); - } - } - } - - if (modelType.IsArray) - { - Type elementType = modelType.GetElementType(); - return GenerateCollectionModelDescription(modelType, elementType); - } - - if (modelType == typeof(NameValueCollection)) - { - return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); - } - - if (typeof(IDictionary).IsAssignableFrom(modelType)) - { - return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); - } - - if (typeof(IEnumerable).IsAssignableFrom(modelType)) - { - return GenerateCollectionModelDescription(modelType, typeof(object)); - } - - return GenerateComplexTypeModelDescription(modelType); - } - - // Change this to provide different name for the member. - private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) - { - JsonPropertyAttribute jsonProperty = member.GetCustomAttribute(); - if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) - { - return jsonProperty.PropertyName; - } - - if (hasDataContractAttribute) - { - DataMemberAttribute dataMember = member.GetCustomAttribute(); - if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) - { - return dataMember.Name; - } - } - - return member.Name; - } - - private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) - { - JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute(); - XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute(); - IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute(); - NonSerializedAttribute nonSerialized = member.GetCustomAttribute(); - ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute(); - - bool hasMemberAttribute = member.DeclaringType.IsEnum ? - member.GetCustomAttribute() != null : - member.GetCustomAttribute() != null; - - // Display member only if all the followings are true: - // no JsonIgnoreAttribute - // no XmlIgnoreAttribute - // no IgnoreDataMemberAttribute - // no NonSerializedAttribute - // no ApiExplorerSettingsAttribute with IgnoreApi set to true - // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute - return jsonIgnore == null && - xmlIgnore == null && - ignoreDataMember == null && - nonSerialized == null && - (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && - (!hasDataContractAttribute || hasMemberAttribute); - } - - private string CreateDefaultDocumentation(Type type) - { - string documentation; - if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) - { - return documentation; - } - if (DocumentationProvider != null) - { - documentation = DocumentationProvider.GetDocumentation(type); - } - - return documentation; - } - - private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) - { - List annotations = new List(); - - IEnumerable attributes = property.GetCustomAttributes(); - foreach (Attribute attribute in attributes) - { - Func textGenerator; - if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) - { - annotations.Add( - new ParameterAnnotation - { - AnnotationAttribute = attribute, - Documentation = textGenerator(attribute) - }); - } - } - - // Rearrange the annotations - annotations.Sort((x, y) => - { - // Special-case RequiredAttribute so that it shows up on top - if (x.AnnotationAttribute is RequiredAttribute) - { - return -1; - } - if (y.AnnotationAttribute is RequiredAttribute) - { - return 1; - } - - // Sort the rest based on alphabetic order of the documentation - return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); - }); - - foreach (ParameterAnnotation annotation in annotations) - { - propertyModel.Annotations.Add(annotation); - } - } - - private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) - { - ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); - if (collectionModelDescription != null) - { - return new CollectionModelDescription - { - Name = ModelNameHelper.GetModelName(modelType), - ModelType = modelType, - ElementDescription = collectionModelDescription - }; - } - - return null; - } - - private ModelDescription GenerateComplexTypeModelDescription(Type modelType) - { - ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription - { - Name = ModelNameHelper.GetModelName(modelType), - ModelType = modelType, - Documentation = CreateDefaultDocumentation(modelType) - }; - - GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); - bool hasDataContractAttribute = modelType.GetCustomAttribute() != null; - PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); - foreach (PropertyInfo property in properties) - { - if (ShouldDisplayMember(property, hasDataContractAttribute)) - { - ParameterDescription propertyModel = new ParameterDescription - { - Name = GetMemberName(property, hasDataContractAttribute) - }; - - if (DocumentationProvider != null) - { - propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); - } - - GenerateAnnotations(property, propertyModel); - complexModelDescription.Properties.Add(propertyModel); - propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); - } - } - - FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); - foreach (FieldInfo field in fields) - { - if (ShouldDisplayMember(field, hasDataContractAttribute)) - { - ParameterDescription propertyModel = new ParameterDescription - { - Name = GetMemberName(field, hasDataContractAttribute) - }; - - if (DocumentationProvider != null) - { - propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); - } - - complexModelDescription.Properties.Add(propertyModel); - propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); - } - } - - return complexModelDescription; - } - - private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) - { - ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); - ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); - - return new DictionaryModelDescription - { - Name = ModelNameHelper.GetModelName(modelType), - ModelType = modelType, - KeyModelDescription = keyModelDescription, - ValueModelDescription = valueModelDescription - }; - } - - private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) - { - EnumTypeModelDescription enumDescription = new EnumTypeModelDescription - { - Name = ModelNameHelper.GetModelName(modelType), - ModelType = modelType, - Documentation = CreateDefaultDocumentation(modelType) - }; - bool hasDataContractAttribute = modelType.GetCustomAttribute() != null; - foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) - { - if (ShouldDisplayMember(field, hasDataContractAttribute)) - { - EnumValueDescription enumValue = new EnumValueDescription - { - Name = field.Name, - Value = field.GetRawConstantValue().ToString() - }; - if (DocumentationProvider != null) - { - enumValue.Documentation = DocumentationProvider.GetDocumentation(field); - } - enumDescription.Values.Add(enumValue); - } - } - GeneratedModels.Add(enumDescription.Name, enumDescription); - - return enumDescription; - } - - private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) - { - ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); - ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); - - return new KeyValuePairModelDescription - { - Name = ModelNameHelper.GetModelName(modelType), - ModelType = modelType, - KeyModelDescription = keyModelDescription, - ValueModelDescription = valueModelDescription - }; - } - - private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) - { - SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription - { - Name = ModelNameHelper.GetModelName(modelType), - ModelType = modelType, - Documentation = CreateDefaultDocumentation(modelType) - }; - GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); - - return simpleModelDescription; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs deleted file mode 100644 index 4934775c8e..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - /// - /// Use this attribute to change the name of the generated for a type. - /// - [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] - public sealed class ModelNameAttribute : Attribute - { - public ModelNameAttribute(string name) - { - Name = name; - } - - public string Name { get; private set; } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs deleted file mode 100644 index b6a282e7cf..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ModelNameHelper.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using System.Reflection; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - internal static class ModelNameHelper - { - // Modify this to provide custom model name mapping. - public static string GetModelName(Type type) - { - ModelNameAttribute modelNameAttribute = type.GetCustomAttribute(); - if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name)) - { - return modelNameAttribute.Name; - } - - string modelName = type.Name; - if (type.IsGenericType) - { - // Format the generic type name to something like: GenericOfAgurment1AndArgument2 - Type genericType = type.GetGenericTypeDefinition(); - Type[] genericArguments = type.GetGenericArguments(); - string genericTypeName = genericType.Name; - - // Trim the generic parameter counts from the name - genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); - string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray(); - modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames)); - } - - return modelName; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs deleted file mode 100644 index 5aff9c659d..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ParameterAnnotation.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public class ParameterAnnotation - { - public Attribute AnnotationAttribute { get; set; } - - public string Documentation { get; set; } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs deleted file mode 100644 index 8eced1a95f..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/ParameterDescription.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Collections.Generic; -using System.Collections.ObjectModel; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public class ParameterDescription - { - public ParameterDescription() - { - Annotations = new Collection(); - } - - public Collection Annotations { get; private set; } - - public string Documentation { get; set; } - - public string Name { get; set; } - - public ModelDescription TypeDescription { get; set; } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs deleted file mode 100644 index d6db5c4616..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -{ - public class SimpleTypeModelDescription : ModelDescription - { - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Models/HelpPageApiModel.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Models/HelpPageApiModel.cs deleted file mode 100644 index 3aecf589b9..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Models/HelpPageApiModel.cs +++ /dev/null @@ -1,108 +0,0 @@ -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Net.Http.Headers; -using System.Web.Http.Description; -using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions; - -namespace NetFrameworkBasicApplication.Areas.HelpPage.Models -{ - /// - /// The model that represents an API displayed on the help page. - /// - public class HelpPageApiModel - { - /// - /// Initializes a new instance of the class. - /// - public HelpPageApiModel() - { - UriParameters = new Collection(); - SampleRequests = new Dictionary(); - SampleResponses = new Dictionary(); - ErrorMessages = new Collection(); - } - - /// - /// Gets or sets the that describes the API. - /// - public ApiDescription ApiDescription { get; set; } - - /// - /// Gets or sets the collection that describes the URI parameters for the API. - /// - public Collection UriParameters { get; private set; } - - /// - /// Gets or sets the documentation for the request. - /// - public string RequestDocumentation { get; set; } - - /// - /// Gets or sets the that describes the request body. - /// - public ModelDescription RequestModelDescription { get; set; } - - /// - /// Gets the request body parameter descriptions. - /// - public IList RequestBodyParameters - { - get - { - return GetParameterDescriptions(RequestModelDescription); - } - } - - /// - /// Gets or sets the that describes the resource. - /// - public ModelDescription ResourceDescription { get; set; } - - /// - /// Gets the resource property descriptions. - /// - public IList ResourceProperties - { - get - { - return GetParameterDescriptions(ResourceDescription); - } - } - - /// - /// Gets the sample requests associated with the API. - /// - public IDictionary SampleRequests { get; private set; } - - /// - /// Gets the sample responses associated with the API. - /// - public IDictionary SampleResponses { get; private set; } - - /// - /// Gets the error messages associated with this model. - /// - public Collection ErrorMessages { get; private set; } - - private static IList GetParameterDescriptions(ModelDescription modelDescription) - { - ComplexTypeModelDescription complexTypeModelDescription = modelDescription as ComplexTypeModelDescription; - if (complexTypeModelDescription != null) - { - return complexTypeModelDescription.Properties; - } - - CollectionModelDescription collectionModelDescription = modelDescription as CollectionModelDescription; - if (collectionModelDescription != null) - { - complexTypeModelDescription = collectionModelDescription.ElementDescription as ComplexTypeModelDescription; - if (complexTypeModelDescription != null) - { - return complexTypeModelDescription.Properties; - } - } - - return null; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs deleted file mode 100644 index d26d201e28..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/HelpPageSampleGenerator.cs +++ /dev/null @@ -1,444 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Net.Http; -using System.Net.Http.Formatting; -using System.Net.Http.Headers; -using System.Web.Http.Description; -using System.Xml.Linq; -using Newtonsoft.Json; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - /// - /// This class will generate the samples for the help page. - /// - public class HelpPageSampleGenerator - { - /// - /// Initializes a new instance of the class. - /// - public HelpPageSampleGenerator() - { - ActualHttpMessageTypes = new Dictionary(); - ActionSamples = new Dictionary(); - SampleObjects = new Dictionary(); - SampleObjectFactories = new List> - { - DefaultSampleObjectFactory, - }; - } - - /// - /// Gets CLR types that are used as the content of or . - /// - public IDictionary ActualHttpMessageTypes { get; internal set; } - - /// - /// Gets the objects that are used directly as samples for certain actions. - /// - public IDictionary ActionSamples { get; internal set; } - - /// - /// Gets the objects that are serialized as samples by the supported formatters. - /// - public IDictionary SampleObjects { get; internal set; } - - /// - /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, - /// stopping when the factory successfully returns a non- object. - /// - /// - /// Collection includes just initially. Use - /// SampleObjectFactories.Insert(0, func) to provide an override and - /// SampleObjectFactories.Add(func) to provide a fallback. - [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", - Justification = "This is an appropriate nesting of generic types")] - public IList> SampleObjectFactories { get; private set; } - - /// - /// Gets the request body samples for a given . - /// - /// The . - /// The samples keyed by media type. - public IDictionary GetSampleRequests(ApiDescription api) - { - return GetSample(api, SampleDirection.Request); - } - - /// - /// Gets the response body samples for a given . - /// - /// The . - /// The samples keyed by media type. - public IDictionary GetSampleResponses(ApiDescription api) - { - return GetSample(api, SampleDirection.Response); - } - - /// - /// Gets the request or response body samples. - /// - /// The . - /// The value indicating whether the sample is for a request or for a response. - /// The samples keyed by media type. - public virtual IDictionary GetSample(ApiDescription api, SampleDirection sampleDirection) - { - if (api == null) - { - throw new ArgumentNullException("api"); - } - string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; - string actionName = api.ActionDescriptor.ActionName; - IEnumerable parameterNames = api.ParameterDescriptions.Select(p => p.Name); - Collection formatters; - Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); - var samples = new Dictionary(); - - // Use the samples provided directly for actions - var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); - foreach (var actionSample in actionSamples) - { - samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); - } - - // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. - // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. - if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) - { - object sampleObject = GetSampleObject(type); - foreach (var formatter in formatters) - { - foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) - { - if (!samples.ContainsKey(mediaType)) - { - object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); - - // If no sample found, try generate sample using formatter and sample object - if (sample == null && sampleObject != null) - { - sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); - } - - samples.Add(mediaType, WrapSampleIfString(sample)); - } - } - } - } - - return samples; - } - - /// - /// Search for samples that are provided directly through . - /// - /// Name of the controller. - /// Name of the action. - /// The parameter names. - /// The CLR type. - /// The formatter. - /// The media type. - /// The value indicating whether the sample is for a request or for a response. - /// The sample that matches the parameters. - public virtual object GetActionSample(string controllerName, string actionName, IEnumerable parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) - { - object sample; - - // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. - // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. - // If still not found, try to get the sample provided for the specified mediaType and type. - // Finally, try to get the sample provided for the specified mediaType. - if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || - ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || - ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || - ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) - { - return sample; - } - - return null; - } - - /// - /// Gets the sample object that will be serialized by the formatters. - /// First, it will look at the . If no sample object is found, it will try to create - /// one using (which wraps an ) and other - /// factories in . - /// - /// The type. - /// The sample object. - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", - Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] - public virtual object GetSampleObject(Type type) - { - object sampleObject; - - if (!SampleObjects.TryGetValue(type, out sampleObject)) - { - // No specific object available, try our factories. - foreach (Func factory in SampleObjectFactories) - { - if (factory == null) - { - continue; - } - - try - { - sampleObject = factory(this, type); - if (sampleObject != null) - { - break; - } - } - catch - { - // Ignore any problems encountered in the factory; go on to the next one (if any). - } - } - } - - return sampleObject; - } - - /// - /// Resolves the actual type of passed to the in an action. - /// - /// The . - /// The type. - public virtual Type ResolveHttpRequestMessageType(ApiDescription api) - { - string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; - string actionName = api.ActionDescriptor.ActionName; - IEnumerable parameterNames = api.ParameterDescriptions.Select(p => p.Name); - Collection formatters; - return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); - } - - /// - /// Resolves the type of the action parameter or return value when or is used. - /// - /// The . - /// Name of the controller. - /// Name of the action. - /// The parameter names. - /// The value indicating whether the sample is for a request or a response. - /// The formatters. - [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] - public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable parameterNames, SampleDirection sampleDirection, out Collection formatters) - { - if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) - { - throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); - } - if (api == null) - { - throw new ArgumentNullException("api"); - } - Type type; - if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || - ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) - { - // Re-compute the supported formatters based on type - Collection newFormatters = new Collection(); - foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) - { - if (IsFormatSupported(sampleDirection, formatter, type)) - { - newFormatters.Add(formatter); - } - } - formatters = newFormatters; - } - else - { - switch (sampleDirection) - { - case SampleDirection.Request: - ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); - type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; - formatters = api.SupportedRequestBodyFormatters; - break; - case SampleDirection.Response: - default: - type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; - formatters = api.SupportedResponseFormatters; - break; - } - } - - return type; - } - - /// - /// Writes the sample object using formatter. - /// - /// The formatter. - /// The value. - /// The type. - /// Type of the media. - /// - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] - public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) - { - if (formatter == null) - { - throw new ArgumentNullException("formatter"); - } - if (mediaType == null) - { - throw new ArgumentNullException("mediaType"); - } - - object sample = String.Empty; - MemoryStream ms = null; - HttpContent content = null; - try - { - if (formatter.CanWriteType(type)) - { - ms = new MemoryStream(); - content = new ObjectContent(type, value, formatter, mediaType); - formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); - ms.Position = 0; - StreamReader reader = new StreamReader(ms); - string serializedSampleString = reader.ReadToEnd(); - if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) - { - serializedSampleString = TryFormatXml(serializedSampleString); - } - else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) - { - serializedSampleString = TryFormatJson(serializedSampleString); - } - - sample = new TextSample(serializedSampleString); - } - else - { - sample = new InvalidSample(String.Format( - CultureInfo.CurrentCulture, - "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", - mediaType, - formatter.GetType().Name, - type.Name)); - } - } - catch (Exception e) - { - sample = new InvalidSample(String.Format( - CultureInfo.CurrentCulture, - "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", - formatter.GetType().Name, - mediaType.MediaType, - UnwrapException(e).Message)); - } - finally - { - if (ms != null) - { - ms.Dispose(); - } - if (content != null) - { - content.Dispose(); - } - } - - return sample; - } - - internal static Exception UnwrapException(Exception exception) - { - AggregateException aggregateException = exception as AggregateException; - if (aggregateException != null) - { - return aggregateException.Flatten().InnerException; - } - return exception; - } - - // Default factory for sample objects - private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) - { - // Try to create a default sample object - ObjectGenerator objectGenerator = new ObjectGenerator(); - return objectGenerator.GenerateObject(type); - } - - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] - private static string TryFormatJson(string str) - { - try - { - object parsedJson = JsonConvert.DeserializeObject(str); - return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); - } - catch - { - // can't parse JSON, return the original string - return str; - } - } - - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] - private static string TryFormatXml(string str) - { - try - { - XDocument xml = XDocument.Parse(str); - return xml.ToString(); - } - catch - { - // can't parse XML, return the original string - return str; - } - } - - private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) - { - switch (sampleDirection) - { - case SampleDirection.Request: - return formatter.CanReadType(type); - case SampleDirection.Response: - return formatter.CanWriteType(type); - } - return false; - } - - private IEnumerable> GetAllActionSamples(string controllerName, string actionName, IEnumerable parameterNames, SampleDirection sampleDirection) - { - HashSet parameterNamesSet = new HashSet(parameterNames, StringComparer.OrdinalIgnoreCase); - foreach (var sample in ActionSamples) - { - HelpPageSampleKey sampleKey = sample.Key; - if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && - String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && - (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && - sampleDirection == sampleKey.SampleDirection) - { - yield return sample; - } - } - } - - private static object WrapSampleIfString(object sample) - { - string stringSample = sample as string; - if (stringSample != null) - { - return new TextSample(stringSample); - } - - return sample; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs deleted file mode 100644 index 4a9a7d3151..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Net.Http.Headers; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - /// - /// This is used to identify the place where the sample should be applied. - /// - public class HelpPageSampleKey - { - /// - /// Creates a new based on media type. - /// - /// The media type. - public HelpPageSampleKey(MediaTypeHeaderValue mediaType) - { - if (mediaType == null) - { - throw new ArgumentNullException("mediaType"); - } - - ActionName = String.Empty; - ControllerName = String.Empty; - MediaType = mediaType; - ParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); - } - - /// - /// Creates a new based on media type and CLR type. - /// - /// The media type. - /// The CLR type. - public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) - : this(mediaType) - { - if (type == null) - { - throw new ArgumentNullException("type"); - } - - ParameterType = type; - } - - /// - /// Creates a new based on , controller name, action name and parameter names. - /// - /// The . - /// Name of the controller. - /// Name of the action. - /// The parameter names. - public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) - { - if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) - { - throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); - } - if (controllerName == null) - { - throw new ArgumentNullException("controllerName"); - } - if (actionName == null) - { - throw new ArgumentNullException("actionName"); - } - if (parameterNames == null) - { - throw new ArgumentNullException("parameterNames"); - } - - ControllerName = controllerName; - ActionName = actionName; - ParameterNames = new HashSet(parameterNames, StringComparer.OrdinalIgnoreCase); - SampleDirection = sampleDirection; - } - - /// - /// Creates a new based on media type, , controller name, action name and parameter names. - /// - /// The media type. - /// The . - /// Name of the controller. - /// Name of the action. - /// The parameter names. - public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable parameterNames) - : this(sampleDirection, controllerName, actionName, parameterNames) - { - if (mediaType == null) - { - throw new ArgumentNullException("mediaType"); - } - - MediaType = mediaType; - } - - /// - /// Gets the name of the controller. - /// - /// - /// The name of the controller. - /// - public string ControllerName { get; private set; } - - /// - /// Gets the name of the action. - /// - /// - /// The name of the action. - /// - public string ActionName { get; private set; } - - /// - /// Gets the media type. - /// - /// - /// The media type. - /// - public MediaTypeHeaderValue MediaType { get; private set; } - - /// - /// Gets the parameter names. - /// - public HashSet ParameterNames { get; private set; } - - public Type ParameterType { get; private set; } - - /// - /// Gets the . - /// - public SampleDirection? SampleDirection { get; private set; } - - public override bool Equals(object obj) - { - HelpPageSampleKey otherKey = obj as HelpPageSampleKey; - if (otherKey == null) - { - return false; - } - - return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && - String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && - (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && - ParameterType == otherKey.ParameterType && - SampleDirection == otherKey.SampleDirection && - ParameterNames.SetEquals(otherKey.ParameterNames); - } - - public override int GetHashCode() - { - int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); - if (MediaType != null) - { - hashCode ^= MediaType.GetHashCode(); - } - if (SampleDirection != null) - { - hashCode ^= SampleDirection.GetHashCode(); - } - if (ParameterType != null) - { - hashCode ^= ParameterType.GetHashCode(); - } - foreach (string parameterName in ParameterNames) - { - hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); - } - - return hashCode; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/ImageSample.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/ImageSample.cs deleted file mode 100644 index e0958d8164..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/ImageSample.cs +++ /dev/null @@ -1,41 +0,0 @@ -using System; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - /// - /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. - /// - public class ImageSample - { - /// - /// Initializes a new instance of the class. - /// - /// The URL of an image. - public ImageSample(string src) - { - if (src == null) - { - throw new ArgumentNullException("src"); - } - Src = src; - } - - public string Src { get; private set; } - - public override bool Equals(object obj) - { - ImageSample other = obj as ImageSample; - return other != null && Src == other.Src; - } - - public override int GetHashCode() - { - return Src.GetHashCode(); - } - - public override string ToString() - { - return Src; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/InvalidSample.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/InvalidSample.cs deleted file mode 100644 index ccb9fa4ac5..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/InvalidSample.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - /// - /// This represents an invalid sample on the help page. There's a display template named InvalidSample associated with this class. - /// - public class InvalidSample - { - public InvalidSample(string errorMessage) - { - if (errorMessage == null) - { - throw new ArgumentNullException("errorMessage"); - } - ErrorMessage = errorMessage; - } - - public string ErrorMessage { get; private set; } - - public override bool Equals(object obj) - { - InvalidSample other = obj as InvalidSample; - return other != null && ErrorMessage == other.ErrorMessage; - } - - public override int GetHashCode() - { - return ErrorMessage.GetHashCode(); - } - - public override string ToString() - { - return ErrorMessage; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs deleted file mode 100644 index 6b790dc662..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs +++ /dev/null @@ -1,456 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; -using System.Linq; -using System.Reflection; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - /// - /// This class will create an object of a given type and populate it with sample data. - /// - public class ObjectGenerator - { - internal const int DefaultCollectionSize = 2; - private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); - - /// - /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: - /// Simple types: , , , , , etc. - /// Complex types: POCO types. - /// Nullables: . - /// Arrays: arrays of simple types or complex types. - /// Key value pairs: - /// Tuples: , , etc - /// Dictionaries: or anything deriving from . - /// Collections: , , , , , or anything deriving from or . - /// Queryables: , . - /// - /// The type. - /// An object of the given type. - public object GenerateObject(Type type) - { - return GenerateObject(type, new Dictionary()); - } - - [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] - private object GenerateObject(Type type, Dictionary createdObjectReferences) - { - try - { - if (SimpleTypeObjectGenerator.CanGenerateObject(type)) - { - return SimpleObjectGenerator.GenerateObject(type); - } - - if (type.IsArray) - { - return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); - } - - if (type.IsGenericType) - { - return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); - } - - if (type == typeof(IDictionary)) - { - return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); - } - - if (typeof(IDictionary).IsAssignableFrom(type)) - { - return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); - } - - if (type == typeof(IList) || - type == typeof(IEnumerable) || - type == typeof(ICollection)) - { - return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); - } - - if (typeof(IList).IsAssignableFrom(type)) - { - return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); - } - - if (type == typeof(IQueryable)) - { - return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); - } - - if (type.IsEnum) - { - return GenerateEnum(type); - } - - if (type.IsPublic || type.IsNestedPublic) - { - return GenerateComplexObject(type, createdObjectReferences); - } - } - catch - { - // Returns null if anything fails - return null; - } - - return null; - } - - private static object GenerateGenericType(Type type, int collectionSize, Dictionary createdObjectReferences) - { - Type genericTypeDefinition = type.GetGenericTypeDefinition(); - if (genericTypeDefinition == typeof(Nullable<>)) - { - return GenerateNullable(type, createdObjectReferences); - } - - if (genericTypeDefinition == typeof(KeyValuePair<,>)) - { - return GenerateKeyValuePair(type, createdObjectReferences); - } - - if (IsTuple(genericTypeDefinition)) - { - return GenerateTuple(type, createdObjectReferences); - } - - Type[] genericArguments = type.GetGenericArguments(); - if (genericArguments.Length == 1) - { - if (genericTypeDefinition == typeof(IList<>) || - genericTypeDefinition == typeof(IEnumerable<>) || - genericTypeDefinition == typeof(ICollection<>)) - { - Type collectionType = typeof(List<>).MakeGenericType(genericArguments); - return GenerateCollection(collectionType, collectionSize, createdObjectReferences); - } - - if (genericTypeDefinition == typeof(IQueryable<>)) - { - return GenerateQueryable(type, collectionSize, createdObjectReferences); - } - - Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); - if (closedCollectionType.IsAssignableFrom(type)) - { - return GenerateCollection(type, collectionSize, createdObjectReferences); - } - } - - if (genericArguments.Length == 2) - { - if (genericTypeDefinition == typeof(IDictionary<,>)) - { - Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); - return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); - } - - Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); - if (closedDictionaryType.IsAssignableFrom(type)) - { - return GenerateDictionary(type, collectionSize, createdObjectReferences); - } - } - - if (type.IsPublic || type.IsNestedPublic) - { - return GenerateComplexObject(type, createdObjectReferences); - } - - return null; - } - - private static object GenerateTuple(Type type, Dictionary createdObjectReferences) - { - Type[] genericArgs = type.GetGenericArguments(); - object[] parameterValues = new object[genericArgs.Length]; - bool failedToCreateTuple = true; - ObjectGenerator objectGenerator = new ObjectGenerator(); - for (int i = 0; i < genericArgs.Length; i++) - { - parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); - failedToCreateTuple &= parameterValues[i] == null; - } - if (failedToCreateTuple) - { - return null; - } - object result = Activator.CreateInstance(type, parameterValues); - return result; - } - - private static bool IsTuple(Type genericTypeDefinition) - { - return genericTypeDefinition == typeof(Tuple<>) || - genericTypeDefinition == typeof(Tuple<,>) || - genericTypeDefinition == typeof(Tuple<,,>) || - genericTypeDefinition == typeof(Tuple<,,,>) || - genericTypeDefinition == typeof(Tuple<,,,,>) || - genericTypeDefinition == typeof(Tuple<,,,,,>) || - genericTypeDefinition == typeof(Tuple<,,,,,,>) || - genericTypeDefinition == typeof(Tuple<,,,,,,,>); - } - - private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary createdObjectReferences) - { - Type[] genericArgs = keyValuePairType.GetGenericArguments(); - Type typeK = genericArgs[0]; - Type typeV = genericArgs[1]; - ObjectGenerator objectGenerator = new ObjectGenerator(); - object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); - object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); - if (keyObject == null && valueObject == null) - { - // Failed to create key and values - return null; - } - object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); - return result; - } - - private static object GenerateArray(Type arrayType, int size, Dictionary createdObjectReferences) - { - Type type = arrayType.GetElementType(); - Array result = Array.CreateInstance(type, size); - bool areAllElementsNull = true; - ObjectGenerator objectGenerator = new ObjectGenerator(); - for (int i = 0; i < size; i++) - { - object element = objectGenerator.GenerateObject(type, createdObjectReferences); - result.SetValue(element, i); - areAllElementsNull &= element == null; - } - - if (areAllElementsNull) - { - return null; - } - - return result; - } - - private static object GenerateDictionary(Type dictionaryType, int size, Dictionary createdObjectReferences) - { - Type typeK = typeof(object); - Type typeV = typeof(object); - if (dictionaryType.IsGenericType) - { - Type[] genericArgs = dictionaryType.GetGenericArguments(); - typeK = genericArgs[0]; - typeV = genericArgs[1]; - } - - object result = Activator.CreateInstance(dictionaryType); - MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); - MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); - ObjectGenerator objectGenerator = new ObjectGenerator(); - for (int i = 0; i < size; i++) - { - object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); - if (newKey == null) - { - // Cannot generate a valid key - return null; - } - - bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); - if (!containsKey) - { - object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); - addMethod.Invoke(result, new object[] { newKey, newValue }); - } - } - - return result; - } - - private static object GenerateEnum(Type enumType) - { - Array possibleValues = Enum.GetValues(enumType); - if (possibleValues.Length > 0) - { - return possibleValues.GetValue(0); - } - return null; - } - - private static object GenerateQueryable(Type queryableType, int size, Dictionary createdObjectReferences) - { - bool isGeneric = queryableType.IsGenericType; - object list; - if (isGeneric) - { - Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); - list = GenerateCollection(listType, size, createdObjectReferences); - } - else - { - list = GenerateArray(typeof(object[]), size, createdObjectReferences); - } - if (list == null) - { - return null; - } - if (isGeneric) - { - Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); - MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); - return asQueryableMethod.Invoke(null, new[] { list }); - } - - return Queryable.AsQueryable((IEnumerable)list); - } - - private static object GenerateCollection(Type collectionType, int size, Dictionary createdObjectReferences) - { - Type type = collectionType.IsGenericType ? - collectionType.GetGenericArguments()[0] : - typeof(object); - object result = Activator.CreateInstance(collectionType); - MethodInfo addMethod = collectionType.GetMethod("Add"); - bool areAllElementsNull = true; - ObjectGenerator objectGenerator = new ObjectGenerator(); - for (int i = 0; i < size; i++) - { - object element = objectGenerator.GenerateObject(type, createdObjectReferences); - addMethod.Invoke(result, new object[] { element }); - areAllElementsNull &= element == null; - } - - if (areAllElementsNull) - { - return null; - } - - return result; - } - - private static object GenerateNullable(Type nullableType, Dictionary createdObjectReferences) - { - Type type = nullableType.GetGenericArguments()[0]; - ObjectGenerator objectGenerator = new ObjectGenerator(); - return objectGenerator.GenerateObject(type, createdObjectReferences); - } - - private static object GenerateComplexObject(Type type, Dictionary createdObjectReferences) - { - object result = null; - - if (createdObjectReferences.TryGetValue(type, out result)) - { - // The object has been created already, just return it. This will handle the circular reference case. - return result; - } - - if (type.IsValueType) - { - result = Activator.CreateInstance(type); - } - else - { - ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); - if (defaultCtor == null) - { - // Cannot instantiate the type because it doesn't have a default constructor - return null; - } - - result = defaultCtor.Invoke(new object[0]); - } - createdObjectReferences.Add(type, result); - SetPublicProperties(type, result, createdObjectReferences); - SetPublicFields(type, result, createdObjectReferences); - return result; - } - - private static void SetPublicProperties(Type type, object obj, Dictionary createdObjectReferences) - { - PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); - ObjectGenerator objectGenerator = new ObjectGenerator(); - foreach (PropertyInfo property in properties) - { - if (property.CanWrite) - { - object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); - property.SetValue(obj, propertyValue, null); - } - } - } - - private static void SetPublicFields(Type type, object obj, Dictionary createdObjectReferences) - { - FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); - ObjectGenerator objectGenerator = new ObjectGenerator(); - foreach (FieldInfo field in fields) - { - object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); - field.SetValue(obj, fieldValue); - } - } - - private class SimpleTypeObjectGenerator - { - private long _index = 0; - private static readonly Dictionary> DefaultGenerators = InitializeGenerators(); - - [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] - private static Dictionary> InitializeGenerators() - { - return new Dictionary> - { - { typeof(Boolean), index => true }, - { typeof(Byte), index => (Byte)64 }, - { typeof(Char), index => (Char)65 }, - { typeof(DateTime), index => DateTime.Now }, - { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, - { typeof(DBNull), index => DBNull.Value }, - { typeof(Decimal), index => (Decimal)index }, - { typeof(Double), index => (Double)(index + 0.1) }, - { typeof(Guid), index => Guid.NewGuid() }, - { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, - { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, - { typeof(Int64), index => (Int64)index }, - { typeof(Object), index => new object() }, - { typeof(SByte), index => (SByte)64 }, - { typeof(Single), index => (Single)(index + 0.1) }, - { - typeof(String), index => - { - return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); - } - }, - { - typeof(TimeSpan), index => - { - return TimeSpan.FromTicks(1234567); - } - }, - { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, - { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, - { typeof(UInt64), index => (UInt64)index }, - { - typeof(Uri), index => - { - return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); - } - }, - }; - } - - public static bool CanGenerateObject(Type type) - { - return DefaultGenerators.ContainsKey(type); - } - - public object GenerateObject(Type type) - { - return DefaultGenerators[type](++_index); - } - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/SampleDirection.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/SampleDirection.cs deleted file mode 100644 index 077f9ad5ce..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/SampleDirection.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - /// - /// Indicates whether the sample is used for request or response - /// - public enum SampleDirection - { - Request = 0, - Response - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/TextSample.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/TextSample.cs deleted file mode 100644 index 9a123bbf31..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/SampleGeneration/TextSample.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - /// - /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. - /// - public class TextSample - { - public TextSample(string text) - { - if (text == null) - { - throw new ArgumentNullException("text"); - } - Text = text; - } - - public string Text { get; private set; } - - public override bool Equals(object obj) - { - TextSample other = obj as TextSample; - return other != null && Text == other.Text; - } - - public override int GetHashCode() - { - return Text.GetHashCode(); - } - - public override string ToString() - { - return Text; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/Api.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/Api.cshtml deleted file mode 100644 index c23918f569..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/Api.cshtml +++ /dev/null @@ -1,22 +0,0 @@ -@using System.Web.Http -@using NetFrameworkBasicApplication.Areas.HelpPage.Models -@model HelpPageApiModel - -@{ - var description = Model.ApiDescription; - ViewBag.Title = description.HttpMethod.Method + " " + description.RelativePath; -} - - -
- -
- @Html.DisplayForModel() -
-
diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml deleted file mode 100644 index 267a763dd3..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ApiGroup.cshtml +++ /dev/null @@ -1,41 +0,0 @@ -@using System.Web.Http -@using System.Web.Http.Controllers -@using System.Web.Http.Description -@using NetFrameworkBasicApplication.Areas.HelpPage -@using NetFrameworkBasicApplication.Areas.HelpPage.Models -@model IGrouping - -@{ - var controllerDocumentation = ViewBag.DocumentationProvider != null ? - ViewBag.DocumentationProvider.GetDocumentation(Model.Key) : - null; -} - -

@Model.Key.ControllerName

-@if (!String.IsNullOrEmpty(controllerDocumentation)) -{ -

@controllerDocumentation

-} - - - - - - @foreach (var api in Model) - { - - - - - } - -
APIDescription
@api.HttpMethod.Method @api.RelativePath - @if (api.Documentation != null) - { -

@api.Documentation

- } - else - { -

No documentation available.

- } -
\ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml deleted file mode 100644 index 2b27baf714..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/CollectionModelDescription.cshtml +++ /dev/null @@ -1,6 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model CollectionModelDescription -@if (Model.ElementDescription is ComplexTypeModelDescription) -{ - @Html.DisplayFor(m => m.ElementDescription) -} \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml deleted file mode 100644 index 9f77c49f7b..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ComplexTypeModelDescription.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model ComplexTypeModelDescription -@Html.DisplayFor(m => m.Properties, "Parameters") \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml deleted file mode 100644 index 7b39497b25..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/DictionaryModelDescription.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model DictionaryModelDescription -Dictionary of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] -and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml deleted file mode 100644 index 190f280fe3..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/EnumTypeModelDescription.cshtml +++ /dev/null @@ -1,24 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model EnumTypeModelDescription - -

Possible enumeration values:

- - - - - - - @foreach (EnumValueDescription value in Model.Values) - { - - - - - - } - -
NameValueDescription
@value.Name -

@value.Value

-
-

@value.Documentation

-
\ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml deleted file mode 100644 index cb117132e2..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/HelpPageApiModel.cshtml +++ /dev/null @@ -1,67 +0,0 @@ -@using System.Web.Http -@using System.Web.Http.Description -@using NetFrameworkBasicApplication.Areas.HelpPage.Models -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model HelpPageApiModel - -@{ - ApiDescription description = Model.ApiDescription; -} -

@description.HttpMethod.Method @description.RelativePath

-
-

@description.Documentation

- -

Request Information

- -

URI Parameters

- @Html.DisplayFor(m => m.UriParameters, "Parameters") - -

Body Parameters

- -

@Model.RequestDocumentation

- - @if (Model.RequestModelDescription != null) - { - @Html.DisplayFor(m => m.RequestModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.RequestModelDescription }) - if (Model.RequestBodyParameters != null) - { - @Html.DisplayFor(m => m.RequestBodyParameters, "Parameters") - } - } - else - { -

None.

- } - - @if (Model.SampleRequests.Count > 0) - { -

Request Formats

- @Html.DisplayFor(m => m.SampleRequests, "Samples") - } - -

Response Information

- -

Resource Description

- -

@description.ResponseDescription.Documentation

- - @if (Model.ResourceDescription != null) - { - @Html.DisplayFor(m => m.ResourceDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ResourceDescription }) - if (Model.ResourceProperties != null) - { - @Html.DisplayFor(m => m.ResourceProperties, "Parameters") - } - } - else - { -

None.

- } - - @if (Model.SampleResponses.Count > 0) - { -

Response Formats

- @Html.DisplayFor(m => m.SampleResponses, "Samples") - } - -
\ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml deleted file mode 100644 index c52154cb9e..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ImageSample.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage -@model ImageSample - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml deleted file mode 100644 index 091e628456..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/InvalidSample.cshtml +++ /dev/null @@ -1,13 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage -@model InvalidSample - -@if (HttpContext.Current.IsDebuggingEnabled) -{ -
-

@Model.ErrorMessage

-
-} -else -{ -

Sample not available.

-} \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml deleted file mode 100644 index f562e2863d..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/KeyValuePairModelDescription.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model KeyValuePairModelDescription -Pair of @Html.DisplayFor(m => Model.KeyModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.KeyModelDescription }) [key] -and @Html.DisplayFor(m => Model.ValueModelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = Model.ValueModelDescription }) [value] \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml deleted file mode 100644 index f6aaf1c9f2..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/ModelDescriptionLink.cshtml +++ /dev/null @@ -1,26 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model Type -@{ - ModelDescription modelDescription = ViewBag.modelDescription; - if (modelDescription is ComplexTypeModelDescription || modelDescription is EnumTypeModelDescription) - { - if (Model == typeof(Object)) - { - @:Object - } - else - { - @Html.ActionLink(modelDescription.Name, "ResourceModel", "Help", new { modelName = modelDescription.Name }, null) - } - } - else if (modelDescription is CollectionModelDescription) - { - var collectionDescription = modelDescription as CollectionModelDescription; - var elementDescription = collectionDescription.ElementDescription; - @:Collection of @Html.DisplayFor(m => elementDescription.ModelType, "ModelDescriptionLink", new { modelDescription = elementDescription }) - } - else - { - @Html.DisplayFor(m => modelDescription) - } -} \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml deleted file mode 100644 index ee36a21255..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/Parameters.cshtml +++ /dev/null @@ -1,48 +0,0 @@ -@using System.Collections.Generic -@using System.Collections.ObjectModel -@using System.Web.Http.Description -@using System.Threading -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model IList - -@if (Model.Count > 0) -{ - - - - - - @foreach (ParameterDescription parameter in Model) - { - ModelDescription modelDescription = parameter.TypeDescription; - - - - - - - } - -
NameDescriptionTypeAdditional information
@parameter.Name -

@parameter.Documentation

-
- @Html.DisplayFor(m => modelDescription.ModelType, "ModelDescriptionLink", new { modelDescription = modelDescription }) - - @if (parameter.Annotations.Count > 0) - { - foreach (var annotation in parameter.Annotations) - { -

@annotation.Documentation

- } - } - else - { -

None.

- } -
-} -else -{ -

None.

-} - diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml deleted file mode 100644 index c19596fb12..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/Samples.cshtml +++ /dev/null @@ -1,30 +0,0 @@ -@using System.Net.Http.Headers -@model Dictionary - -@{ - // Group the samples into a single tab if they are the same. - Dictionary samples = Model.GroupBy(pair => pair.Value).ToDictionary( - pair => String.Join(", ", pair.Select(m => m.Key.ToString()).ToArray()), - pair => pair.Key); - var mediaTypes = samples.Keys; -} -
- @foreach (var mediaType in mediaTypes) - { -

@mediaType

-
- Sample: - @{ - var sample = samples[mediaType]; - if (sample == null) - { -

Sample not available.

- } - else - { - @Html.DisplayFor(s => sample); - } - } -
- } -
\ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml deleted file mode 100644 index e5e60815be..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/SimpleTypeModelDescription.cshtml +++ /dev/null @@ -1,3 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model SimpleTypeModelDescription -@Model.Documentation \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml deleted file mode 100644 index 1dea06c943..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/DisplayTemplates/TextSample.cshtml +++ /dev/null @@ -1,6 +0,0 @@ -@using NetFrameworkBasicApplication.Areas.HelpPage -@model TextSample - -
-@Model.Text
-
\ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/Index.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/Index.cshtml deleted file mode 100644 index 22c7e8a3bd..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/Index.cshtml +++ /dev/null @@ -1,38 +0,0 @@ -@using System.Web.Http -@using System.Web.Http.Controllers -@using System.Web.Http.Description -@using System.Collections.ObjectModel -@using NetFrameworkBasicApplication.Areas.HelpPage.Models -@model Collection - -@{ - ViewBag.Title = "ASP.NET Web API Help Page"; - - // Group APIs by controller - ILookup apiGroups = Model.ToLookup(api => api.ActionDescriptor.ControllerDescriptor); -} - - -
-
-
-

@ViewBag.Title

-
-
-
-
- -
- @foreach (var group in apiGroups) - { - @Html.DisplayFor(m => group, "ApiGroup") - } -
-
diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/ResourceModel.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/ResourceModel.cshtml deleted file mode 100644 index 9437f58325..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Help/ResourceModel.cshtml +++ /dev/null @@ -1,19 +0,0 @@ -@using System.Web.Http -@using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions -@model ModelDescription - - -
- -

@Model.Name

-

@Model.Documentation

-
- @Html.DisplayFor(m => Model) -
-
diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Shared/_Layout.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Shared/_Layout.cshtml deleted file mode 100644 index 896c833a03..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Shared/_Layout.cshtml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - @ViewBag.Title - @RenderSection("scripts", required: false) - - - @RenderBody() - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Web.config b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Web.config deleted file mode 100644 index 0971732240..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/Web.config +++ /dev/null @@ -1,41 +0,0 @@ - - - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/_ViewStart.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/_ViewStart.cshtml deleted file mode 100644 index d735b1cb0b..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/Views/_ViewStart.cshtml +++ /dev/null @@ -1,4 +0,0 @@ -@{ - // Change the Layout path below to blend the look and feel of the help page with your existing web pages - Layout = "~/Views/Shared/_Layout.cshtml"; -} \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/XmlDocumentationProvider.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/XmlDocumentationProvider.cs deleted file mode 100644 index 80074c9dae..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Areas/HelpPage/XmlDocumentationProvider.cs +++ /dev/null @@ -1,161 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using System.Reflection; -using System.Web.Http.Controllers; -using System.Web.Http.Description; -using System.Xml.XPath; -using NetFrameworkBasicApplication.Areas.HelpPage.ModelDescriptions; - -namespace NetFrameworkBasicApplication.Areas.HelpPage -{ - /// - /// A custom that reads the API documentation from an XML documentation file. - /// - public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider - { - private XPathNavigator _documentNavigator; - private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; - private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; - private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; - private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; - private const string ParameterExpression = "param[@name='{0}']"; - - /// - /// Initializes a new instance of the class. - /// - /// The physical path to XML document. - public XmlDocumentationProvider(string documentPath) - { - if (documentPath == null) - { - throw new ArgumentNullException("documentPath"); - } - XPathDocument xpath = new XPathDocument(documentPath); - _documentNavigator = xpath.CreateNavigator(); - } - - public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) - { - XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); - return GetTagValue(typeNode, "summary"); - } - - public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) - { - XPathNavigator methodNode = GetMethodNode(actionDescriptor); - return GetTagValue(methodNode, "summary"); - } - - public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) - { - ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; - if (reflectedParameterDescriptor != null) - { - XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); - if (methodNode != null) - { - string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; - XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); - if (parameterNode != null) - { - return parameterNode.Value.Trim(); - } - } - } - - return null; - } - - public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) - { - XPathNavigator methodNode = GetMethodNode(actionDescriptor); - return GetTagValue(methodNode, "returns"); - } - - public string GetDocumentation(MemberInfo member) - { - string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); - string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; - string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); - XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); - return GetTagValue(propertyNode, "summary"); - } - - public string GetDocumentation(Type type) - { - XPathNavigator typeNode = GetTypeNode(type); - return GetTagValue(typeNode, "summary"); - } - - private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) - { - ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; - if (reflectedActionDescriptor != null) - { - string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); - return _documentNavigator.SelectSingleNode(selectExpression); - } - - return null; - } - - private static string GetMemberName(MethodInfo method) - { - string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); - ParameterInfo[] parameters = method.GetParameters(); - if (parameters.Length != 0) - { - string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); - name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); - } - - return name; - } - - private static string GetTagValue(XPathNavigator parentNode, string tagName) - { - if (parentNode != null) - { - XPathNavigator node = parentNode.SelectSingleNode(tagName); - if (node != null) - { - return node.Value.Trim(); - } - } - - return null; - } - - private XPathNavigator GetTypeNode(Type type) - { - string controllerTypeName = GetTypeName(type); - string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); - return _documentNavigator.SelectSingleNode(selectExpression); - } - - private static string GetTypeName(Type type) - { - string name = type.FullName; - if (type.IsGenericType) - { - // Format the generic type name to something like: Generic{System.Int32,System.String} - Type genericType = type.GetGenericTypeDefinition(); - Type[] genericArguments = type.GetGenericArguments(); - string genericTypeName = genericType.FullName; - - // Trim the generic parameter counts from the name - genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); - string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); - name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); - } - if (type.IsNested) - { - // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. - name = name.Replace("+", "."); - } - - return name; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Controllers/HomeController.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Controllers/HomeController.cs deleted file mode 100644 index 426c1929ea..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Controllers/HomeController.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Web.Mvc; - -namespace NetFrameworkBasicApplication.Controllers -{ - public class HomeController : Controller - { - public ActionResult Index() - { - ViewBag.Title = "Home Page"; - - return View(); - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Controllers/LogsController.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Controllers/LogsController.cs deleted file mode 100644 index 48ceb71e66..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Controllers/LogsController.cs +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ - -using AgentLogHelper; -using System; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Http; -using System.Reflection; -using System.Web.Http; - -namespace NetFrameworkBasicApplication.Controllers -{ - public class LogsController : ApiController - { - private AgentLog _agentLog; - private const string TransactionSampleLogLineRegex = @"Invoking ""transaction_sample_data"" with : "; - - - public LogsController() - { - var logPath = @"c:\Home\LogFiles\NewRelic"; - _agentLog = new AgentLog(logPath); - } - - [HttpGet] - //Get api/Logs/AgentLog - public string AgentLog() - { - var logString = _agentLog.GetAgentLog(); - return logString; - } - - [HttpGet] - //Get api/Logs/AgentLogWithTransactionSample - public string AgentLogWithTransactionSample() - { - var logString = _agentLog.GetAgentLog(TransactionSampleLogLineRegex); - return logString; - } - - [HttpGet] - //Get api/Logs/ProfilerLog - public string ProfilerLog() - { - var logString = _agentLog.GetProfilerLog(); - return logString; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/DeployUtils/StartAppService.ps1 b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/DeployUtils/StartAppService.ps1 deleted file mode 100644 index ffa547af7c..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/DeployUtils/StartAppService.ps1 +++ /dev/null @@ -1,13 +0,0 @@ -############################################################ -# Copyright 2020 New Relic Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 -############################################################ - -Param( - [string] $appName, - [string] $publishSettings -) - -Import-AzurePublishSettingsFile -PublishSettingsFile $publishSettings -Select-AzureSubscription -SubscriptionName '.Net Team Sandbox' -Start-AzureWebsite -Name $appName diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/DeployUtils/StopAppService.ps1 b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/DeployUtils/StopAppService.ps1 deleted file mode 100644 index f6ee85545e..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/DeployUtils/StopAppService.ps1 +++ /dev/null @@ -1,13 +0,0 @@ -############################################################ -# Copyright 2020 New Relic Corporation. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 -############################################################ - -Param( - [string] $appName, - [string] $publishSettings -) - -Import-AzurePublishSettingsFile -PublishSettingsFile $publishSettings -Select-AzureSubscription -SubscriptionName '.Net Team Sandbox' -Stop-AzureWebsite -Name $appName diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Global.asax b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Global.asax deleted file mode 100644 index e16568cc64..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Global.asax +++ /dev/null @@ -1 +0,0 @@ -<%@ Application Codebehind="Global.asax.cs" Inherits="NetFrameworkBasicApplication.WebApiApplication" Language="C#" %> diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Global.asax.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Global.asax.cs deleted file mode 100644 index aeca5d0870..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Global.asax.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System.Web.Http; -using System.Web.Mvc; -using System.Web.Routing; - -namespace NetFrameworkBasicApplication -{ - public class WebApiApplication : System.Web.HttpApplication - { - protected void Application_Start() - { - AreaRegistration.RegisterAllAreas(); - GlobalConfiguration.Configure(WebApiConfig.Register); - FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); - RouteConfig.RegisterRoutes(RouteTable.Routes); - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/NetFrameworkBasicApplication.csproj b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/NetFrameworkBasicApplication.csproj deleted file mode 100644 index e0c6409477..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/NetFrameworkBasicApplication.csproj +++ /dev/null @@ -1,222 +0,0 @@ - - - - - Debug - AnyCPU - - - 2.0 - {2CE3DF18-F0EE-494A-94D3-5BA7BE94C249} - {349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc} - Library - Properties - NetFrameworkBasicApplication - NetFrameworkBasicApplication - v4.5 - false - true - - - - - - - - - true - full - false - bin\ - DEBUG;TRACE - prompt - 4 - - - true - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - - - - - ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll - - - ..\packages\NewRelic.Azure.WebSites.x64.6.0.0.0\lib\NewRelic.Api.Agent.dll - - - ..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll - True - - - - - - - ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll - - - - - - - - ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.Helpers.dll - - - ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll - - - ..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll - - - ..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll - - - ..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll - - - ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll - - - ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Deployment.dll - - - ..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Global.asax - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - - Web.config - - - Web.config - - - - - - - - {d811ffb5-2b9b-4d1b-b2f6-5c2557be0a6b} - AgentLogHelper - - - - 10.0 - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - - - - - - - - - - - - False - True - 64561 - / - http://localhost:57521/ - False - False - - - False - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Properties/AssemblyInfo.cs b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Properties/AssemblyInfo.cs deleted file mode 100644 index 2aac793d71..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("NetFrameworkBasicApplication")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("NetFrameworkBasicApplication")] -[assembly: AssemblyCopyright("Copyright © 2018")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("ce55c9d0-29d5-4b61-9f23-e0a29ce5e920")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Properties/PublishProfiles/DeployProfile.pubxml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Properties/PublishProfiles/DeployProfile.pubxml deleted file mode 100644 index 08f54c32b9..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Properties/PublishProfiles/DeployProfile.pubxml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - MSDeploy - /subscriptions/b808887b-cb91-49e0-b922-c9188372bdba/resourceGroups/dotnet-azure-test-rg/providers/Microsoft.Web/sites/NetFrameworkBasicApplication - dotnet-azure-test-rg - AzureWebSite - Release - Any CPU - http://netframeworkbasicapplication.azurewebsites.net - True - False - netframeworkbasicapplication.scm.azurewebsites.net:443 - NetFrameworkBasicApplication - - False - WMSVC - True - dotnet-agent - <_SavePWD>True - <_DestinationType>AzureWebSite - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Views/Home/Index.cshtml b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Views/Home/Index.cshtml deleted file mode 100644 index e3223e287e..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Views/Home/Index.cshtml +++ /dev/null @@ -1,18 +0,0 @@ -@inherits System.Web.Mvc.WebViewPage -@{ - Layout = null; -} - - - - - - - - - -
- Homepage -
- - diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Web.Debug.config b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Web.Debug.config deleted file mode 100644 index d7712aaf17..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Web.Debug.config +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Web.Release.config b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Web.Release.config deleted file mode 100644 index 28a4d5fcc3..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Web.Release.config +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Web.config b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Web.config deleted file mode 100644 index bc9d5f872b..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/Web.config +++ /dev/null @@ -1,53 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/favicon.ico b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/favicon.ico deleted file mode 100644 index a3a799985c..0000000000 Binary files a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/favicon.ico and /dev/null differ diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/newrelic.config b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/newrelic.config deleted file mode 100644 index dbe6b5354c..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/newrelic.config +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - NetFrameworkBasicApplication - - - - - - - System.IO.FileNotFoundException - System.Threading.ThreadAbortException - - - 401 - 404 - - - - - System.Threading.WaitHandle:InternalWaitOne - System.Threading.WaitHandle:WaitAny - - diff --git a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/packages.config b/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/packages.config deleted file mode 100644 index 0cb9798a93..0000000000 --- a/tests/Agent/PlatformTests/Applications/NetFrameworkBasicApplication/NetFrameworkBasicApplication/packages.config +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/App.config b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/App.config deleted file mode 100644 index 86272c6ae0..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/App.config +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Controllers/DefaultController.cs b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Controllers/DefaultController.cs deleted file mode 100644 index f8dd5b53bf..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Controllers/DefaultController.cs +++ /dev/null @@ -1,18 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System.Web.Http; - -namespace OwinService.Controllers -{ - public class DefaultController : ApiController - { - [HttpGet] - [Route("")] - public string Index() - { - return "Hello World!"; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Controllers/LogsController.cs b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Controllers/LogsController.cs deleted file mode 100644 index e7109b3895..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Controllers/LogsController.cs +++ /dev/null @@ -1,43 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System; -using System.Diagnostics; -using System.IO; -using System.Net.Http; -using System.Reflection; -using System.Threading; -using System.Web; -using System.Web.Http; -using AgentLogHelper; - -namespace OwinService.Controllers -{ - public class LogsController : ApiController - { - private AgentLog _agentLog; - - public LogsController() - { - var logPath = Path.Combine(Environment.GetEnvironmentVariable("NEWRELIC_HOME"), "logs"); - _agentLog = new AgentLog(logPath); - } - - [HttpGet] - [Route("Logs/AgentLog")] - public string AgentLog() - { - var logString = _agentLog.GetAgentLog(); - return logString; - } - - [HttpGet] - [Route("Logs/ProfilerLog")] - public string ProfilerLog() - { - var logString = _agentLog.GetProfilerLog(); - return logString; - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/IOwinAppBuilder.cs b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/IOwinAppBuilder.cs deleted file mode 100644 index a118a61432..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/IOwinAppBuilder.cs +++ /dev/null @@ -1,13 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using Owin; - -namespace OwinService -{ - public interface IOwinAppBuilder - { - void Configuration(IAppBuilder appBuilder); - } -} diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/OwinCommunicationListener.cs b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/OwinCommunicationListener.cs deleted file mode 100644 index b7810236ee..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/OwinCommunicationListener.cs +++ /dev/null @@ -1,88 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System; -using System.Fabric; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.Owin.Hosting; -using Microsoft.ServiceFabric.Services.Communication.Runtime; - -namespace OwinService -{ - public class OwinCommunicationListener : ICommunicationListener - { - private readonly IOwinAppBuilder _startup; - private readonly string _appRoot; - private readonly StatelessServiceContext _parameters; - - private string _listeningAddress; - - private IDisposable _serverHandle; - - public OwinCommunicationListener(string appRoot, IOwinAppBuilder startup, StatelessServiceContext serviceInitializationParameters) - { - _startup = startup; - _appRoot = appRoot; - _parameters = serviceInitializationParameters; - } - - public Task OpenAsync(CancellationToken cancellationToken) - { - var serviceEndpoint = - _parameters - .CodePackageActivationContext - .GetEndpoint("ServiceEndpoint"); - - var port = serviceEndpoint.Port; - var root = - String.IsNullOrWhiteSpace(_appRoot) - ? String.Empty - : _appRoot.TrimEnd('/') + '/'; - - _listeningAddress = String.Format( - CultureInfo.InvariantCulture, - "http://+:{0}/{1}", - port, - root - ); - _serverHandle = WebApp.Start( - _listeningAddress, - appBuilder => _startup.Configuration(appBuilder) - ); - - var publishAddress = _listeningAddress.Replace( - "+", - FabricRuntime.GetNodeContext().IPAddressOrFQDN - ); - - ServiceEventSource.Current.Message("Listening on {0}", publishAddress); - return Task.FromResult(publishAddress); - } - - public void Abort() - { - StopWebServer(); - } - - public Task CloseAsync(CancellationToken cancellationToken) - { - StopWebServer(); - return Task.FromResult(true); - } - - private void StopWebServer() - { - if (_serverHandle == null) - return; - - try - { - _serverHandle.Dispose(); - } - catch (ObjectDisposedException) { } - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/OwinService.cs b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/OwinService.cs deleted file mode 100644 index 13dec93986..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/OwinService.cs +++ /dev/null @@ -1,38 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System; -using System.Collections.Generic; -using System.Fabric; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.ServiceFabric.Services.Communication.Runtime; -using Microsoft.ServiceFabric.Services.Runtime; -using OwinService; - -namespace OwinService -{ - /// - /// An instance of this class is created for each service instance by the Service Fabric runtime. - /// - internal sealed class OwinService : StatelessService - { - public OwinService(StatelessServiceContext context) - : base(context) - { } - - /// - /// Optional override to create listeners (e.g., TCP, HTTP) for this service replica to handle client or user requests. - /// - /// A collection of listeners. - protected override IEnumerable CreateServiceInstanceListeners() - { - return new[] { - new ServiceInstanceListener(initParams => new OwinCommunicationListener("api", new Startup(), initParams)) - }; - } - - } -} diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/OwinService.csproj b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/OwinService.csproj deleted file mode 100644 index 74f69a3c26..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/OwinService.csproj +++ /dev/null @@ -1,117 +0,0 @@ - - - - - Debug - x64 - {27FA83D8-F7A9-4EDF-ACA2-59474CDB4576} - Exe - Properties - OwinService - OwinService - v4.5 - 512 - true - false - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 1 - 1.0.0.%2a - false - true - true - - - true - full - false - bin\x64\Debug\ - DEBUG;TRACE - prompt - x64 - MinimumRecommendedRules.ruleset - - - pdbonly - true - bin\x64\Release\ - TRACE - prompt - x64 - MinimumRecommendedRules.ruleset - - - $(AdditionalFileItemNames);None - - - true - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Designer - - - - - - False - .NET Framework 3.5 SP1 - false - - - - - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B} - AgentLogHelper - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/PackageRoot/Config/Settings.xml b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/PackageRoot/Config/Settings.xml deleted file mode 100644 index ad84ffd8aa..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/PackageRoot/Config/Settings.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/PackageRoot/ServiceManifest.xml b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/PackageRoot/ServiceManifest.xml deleted file mode 100644 index d8674ef96a..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/PackageRoot/ServiceManifest.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - OwinService.exe - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Program.cs b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Program.cs deleted file mode 100644 index 6ccd726121..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Program.cs +++ /dev/null @@ -1,43 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System; -using System.Diagnostics; -using System.Fabric; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.ServiceFabric.Services.Runtime; - -namespace OwinService -{ - internal static class Program - { - /// - /// This is the entry point of the service host process. - /// - private static void Main() - { - try - { - // The ServiceManifest.XML file defines one or more service type names. - // Registering a service maps a service type name to a .NET type. - // When Service Fabric creates an instance of this service type, - // an instance of the class is created in this host process. - - ServiceRuntime.RegisterServiceAsync("OwinServiceType", - context => new OwinService(context)).GetAwaiter().GetResult(); - - ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(OwinService).Name); - - // Prevents this host process from terminating so services keep running. - Thread.Sleep(Timeout.Infinite); - } - catch (Exception e) - { - ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString()); - throw; - } - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Properties/AssemblyInfo.cs b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Properties/AssemblyInfo.cs deleted file mode 100644 index 039bb06485..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("OwinService")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("OwinService")] -[assembly: AssemblyCopyright("Copyright © 2018")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("27fa83d8-f7a9-4edf-aca2-59474cdb4576")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/ServiceEventSource.cs b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/ServiceEventSource.cs deleted file mode 100644 index 926acac48f..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/ServiceEventSource.cs +++ /dev/null @@ -1,177 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System; -using System.Collections.Generic; -using System.Diagnostics.Tracing; -using System.Fabric; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Microsoft.ServiceFabric.Services.Runtime; - -namespace OwinService -{ - [EventSource(Name = "MyCompany-OwinService")] - internal sealed class ServiceEventSource : EventSource - { - public static readonly ServiceEventSource Current = new ServiceEventSource(); - - static ServiceEventSource() - { - // A workaround for the problem where ETW activities do not get tracked until Tasks infrastructure is initialized. - // This problem will be fixed in .NET Framework 4.6.2. - Task.Run(() => { }); - } - - // Instance constructor is private to enforce singleton semantics - private ServiceEventSource() : base() { } - - #region Keywords - // Event keywords can be used to categorize events. - // Each keyword is a bit flag. A single event can be associated with multiple keywords (via EventAttribute.Keywords property). - // Keywords must be defined as a public class named 'Keywords' inside EventSource that uses them. - public static class Keywords - { - public const EventKeywords Requests = (EventKeywords)0x1L; - public const EventKeywords ServiceInitialization = (EventKeywords)0x2L; - } - #endregion - - #region Events - // Define an instance method for each event you want to record and apply an [Event] attribute to it. - // The method name is the name of the event. - // Pass any parameters you want to record with the event (only primitive integer types, DateTime, Guid & string are allowed). - // Each event method implementation should check whether the event source is enabled, and if it is, call WriteEvent() method to raise the event. - // The number and types of arguments passed to every event method must exactly match what is passed to WriteEvent(). - // Put [NonEvent] attribute on all methods that do not define an event. - // For more information see https://msdn.microsoft.com/en-us/library/system.diagnostics.tracing.eventsource.aspx - - [NonEvent] - public void Message(string message, params object[] args) - { - if (this.IsEnabled()) - { - string finalMessage = string.Format(message, args); - Message(finalMessage); - } - } - - private const int MessageEventId = 1; - [Event(MessageEventId, Level = EventLevel.Informational, Message = "{0}")] - public void Message(string message) - { - if (this.IsEnabled()) - { - WriteEvent(MessageEventId, message); - } - } - - [NonEvent] - public void ServiceMessage(StatelessServiceContext serviceContext, string message, params object[] args) - { - if (this.IsEnabled()) - { - string finalMessage = string.Format(message, args); - ServiceMessage( - serviceContext.ServiceName.ToString(), - serviceContext.ServiceTypeName, - serviceContext.InstanceId, - serviceContext.PartitionId, - serviceContext.CodePackageActivationContext.ApplicationName, - serviceContext.CodePackageActivationContext.ApplicationTypeName, - serviceContext.NodeContext.NodeName, - finalMessage); - } - } - - // For very high-frequency events it might be advantageous to raise events using WriteEventCore API. - // This results in more efficient parameter handling, but requires explicit allocation of EventData structure and unsafe code. - // To enable this code path, define UNSAFE conditional compilation symbol and turn on unsafe code support in project properties. - private const int ServiceMessageEventId = 2; - [Event(ServiceMessageEventId, Level = EventLevel.Informational, Message = "{7}")] - private -#if UNSAFE - unsafe -#endif - void ServiceMessage( - string serviceName, - string serviceTypeName, - long replicaOrInstanceId, - Guid partitionId, - string applicationName, - string applicationTypeName, - string nodeName, - string message) - { -#if !UNSAFE - WriteEvent(ServiceMessageEventId, serviceName, serviceTypeName, replicaOrInstanceId, partitionId, applicationName, applicationTypeName, nodeName, message); -#else - const int numArgs = 8; - fixed (char* pServiceName = serviceName, pServiceTypeName = serviceTypeName, pApplicationName = applicationName, pApplicationTypeName = applicationTypeName, pNodeName = nodeName, pMessage = message) - { - EventData* eventData = stackalloc EventData[numArgs]; - eventData[0] = new EventData { DataPointer = (IntPtr) pServiceName, Size = SizeInBytes(serviceName) }; - eventData[1] = new EventData { DataPointer = (IntPtr) pServiceTypeName, Size = SizeInBytes(serviceTypeName) }; - eventData[2] = new EventData { DataPointer = (IntPtr) (&replicaOrInstanceId), Size = sizeof(long) }; - eventData[3] = new EventData { DataPointer = (IntPtr) (&partitionId), Size = sizeof(Guid) }; - eventData[4] = new EventData { DataPointer = (IntPtr) pApplicationName, Size = SizeInBytes(applicationName) }; - eventData[5] = new EventData { DataPointer = (IntPtr) pApplicationTypeName, Size = SizeInBytes(applicationTypeName) }; - eventData[6] = new EventData { DataPointer = (IntPtr) pNodeName, Size = SizeInBytes(nodeName) }; - eventData[7] = new EventData { DataPointer = (IntPtr) pMessage, Size = SizeInBytes(message) }; - - WriteEventCore(ServiceMessageEventId, numArgs, eventData); - } -#endif - } - - private const int ServiceTypeRegisteredEventId = 3; - [Event(ServiceTypeRegisteredEventId, Level = EventLevel.Informational, Message = "Service host process {0} registered service type {1}", Keywords = Keywords.ServiceInitialization)] - public void ServiceTypeRegistered(int hostProcessId, string serviceType) - { - WriteEvent(ServiceTypeRegisteredEventId, hostProcessId, serviceType); - } - - private const int ServiceHostInitializationFailedEventId = 4; - [Event(ServiceHostInitializationFailedEventId, Level = EventLevel.Error, Message = "Service host initialization failed", Keywords = Keywords.ServiceInitialization)] - public void ServiceHostInitializationFailed(string exception) - { - WriteEvent(ServiceHostInitializationFailedEventId, exception); - } - - // A pair of events sharing the same name prefix with a "Start"/"Stop" suffix implicitly marks boundaries of an event tracing activity. - // These activities can be automatically picked up by debugging and profiling tools, which can compute their execution time, child activities, - // and other statistics. - private const int ServiceRequestStartEventId = 5; - [Event(ServiceRequestStartEventId, Level = EventLevel.Informational, Message = "Service request '{0}' started", Keywords = Keywords.Requests)] - public void ServiceRequestStart(string requestTypeName) - { - WriteEvent(ServiceRequestStartEventId, requestTypeName); - } - - private const int ServiceRequestStopEventId = 6; - [Event(ServiceRequestStopEventId, Level = EventLevel.Informational, Message = "Service request '{0}' finished", Keywords = Keywords.Requests)] - public void ServiceRequestStop(string requestTypeName, string exception = "") - { - WriteEvent(ServiceRequestStopEventId, requestTypeName, exception); - } - #endregion - - #region Private methods -#if UNSAFE - private int SizeInBytes(string s) - { - if (s == null) - { - return 0; - } - else - { - return (s.Length + 1) * sizeof(char); - } - } -#endif - #endregion - } -} diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Startup.cs b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Startup.cs deleted file mode 100644 index 47d71f2a9a..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/OwinService/Startup.cs +++ /dev/null @@ -1,30 +0,0 @@ -/* -* Copyright 2020 New Relic Corporation. All rights reserved. -* SPDX-License-Identifier: Apache-2.0 -*/ -using System.Net.Http.Formatting; -using System.Net.Http.Headers; -using System.Web.Http; -using Owin; -using OwinService; - -namespace OwinService -{ - public class Startup : IOwinAppBuilder - { - public static void ConfigureFormatters(MediaTypeFormatterCollection formatters) - { - formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); - } - - public void Configuration(IAppBuilder appBuilder) - { - var config = new HttpConfiguration(); - - config.MapHttpAttributeRoutes(); - ConfigureFormatters(config.Formatters); - - appBuilder.UseWebApi(config); - } - } -} diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication.sln b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication.sln deleted file mode 100644 index b9b03fd4e0..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication.sln +++ /dev/null @@ -1,54 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.27428.2005 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{A07B5EB6-E848-4116-A8D0-A826331D98C6}") = "ServiceFabricApplication", "ServiceFabricApplication\ServiceFabricApplication.sfproj", "{11553D91-149B-441F-87ED-B5F929DD14F7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OwinService", "OwinService\OwinService.csproj", "{27FA83D8-F7A9-4EDF-ACA2-59474CDB4576}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AgentLogHelper", "..\AgentLogHelper\AgentLogHelper.csproj", "{D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {11553D91-149B-441F-87ED-B5F929DD14F7}.Debug|Any CPU.ActiveCfg = Debug|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Debug|Any CPU.Build.0 = Debug|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Debug|Any CPU.Deploy.0 = Debug|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Debug|x64.ActiveCfg = Debug|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Debug|x64.Build.0 = Debug|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Debug|x64.Deploy.0 = Debug|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Release|Any CPU.ActiveCfg = Release|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Release|Any CPU.Build.0 = Release|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Release|Any CPU.Deploy.0 = Release|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Release|x64.ActiveCfg = Release|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Release|x64.Build.0 = Release|x64 - {11553D91-149B-441F-87ED-B5F929DD14F7}.Release|x64.Deploy.0 = Release|x64 - {27FA83D8-F7A9-4EDF-ACA2-59474CDB4576}.Debug|Any CPU.ActiveCfg = Debug|x64 - {27FA83D8-F7A9-4EDF-ACA2-59474CDB4576}.Debug|Any CPU.Build.0 = Debug|x64 - {27FA83D8-F7A9-4EDF-ACA2-59474CDB4576}.Debug|x64.ActiveCfg = Debug|x64 - {27FA83D8-F7A9-4EDF-ACA2-59474CDB4576}.Debug|x64.Build.0 = Debug|x64 - {27FA83D8-F7A9-4EDF-ACA2-59474CDB4576}.Release|Any CPU.ActiveCfg = Release|x64 - {27FA83D8-F7A9-4EDF-ACA2-59474CDB4576}.Release|x64.ActiveCfg = Release|x64 - {27FA83D8-F7A9-4EDF-ACA2-59474CDB4576}.Release|x64.Build.0 = Release|x64 - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Debug|x64.ActiveCfg = Debug|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Debug|x64.Build.0 = Debug|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Release|Any CPU.Build.0 = Release|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Release|x64.ActiveCfg = Release|Any CPU - {D811FFB5-2B9B-4D1B-B2F6-5C2557BE0A6B}.Release|x64.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {DB330363-7EF7-4522-A9BE-8D2B3DF7107F} - EndGlobalSection -EndGlobal diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationPackageRoot/ApplicationManifest.xml b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationPackageRoot/ApplicationManifest.xml deleted file mode 100644 index 42766ca863..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationPackageRoot/ApplicationManifest.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationParameters/Cloud.xml b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationParameters/Cloud.xml deleted file mode 100644 index a0441cda97..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationParameters/Cloud.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationParameters/Local.1Node.xml b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationParameters/Local.1Node.xml deleted file mode 100644 index 89317fe0ac..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationParameters/Local.1Node.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationParameters/Local.5Node.xml b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationParameters/Local.5Node.xml deleted file mode 100644 index 89317fe0ac..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ApplicationParameters/Local.5Node.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/PublishProfiles/Cloud.xml b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/PublishProfiles/Cloud.xml deleted file mode 100644 index f3e58aaf45..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/PublishProfiles/Cloud.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/PublishProfiles/Local.1Node.xml b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/PublishProfiles/Local.1Node.xml deleted file mode 100644 index 6e1403e962..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/PublishProfiles/Local.1Node.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/PublishProfiles/Local.5Node.xml b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/PublishProfiles/Local.5Node.xml deleted file mode 100644 index f42d759c3d..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/PublishProfiles/Local.5Node.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/Scripts/Deploy-FabricApplication.ps1 b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/Scripts/Deploy-FabricApplication.ps1 deleted file mode 100644 index 563bd9e938..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/Scripts/Deploy-FabricApplication.ps1 +++ /dev/null @@ -1,259 +0,0 @@ -<# -.SYNOPSIS -Deploys a Service Fabric application type to a cluster. - -.DESCRIPTION -This script deploys a Service Fabric application type to a cluster. It is invoked by Visual Studio when deploying a Service Fabric Application project. - -.NOTES -WARNING: This script file is invoked by Visual Studio. Its parameters must not be altered but its logic can be customized as necessary. - -.PARAMETER PublishProfileFile -Path to the file containing the publish profile. - -.PARAMETER ApplicationPackagePath -Path to the folder of the packaged Service Fabric application. - -.PARAMETER DeployOnly -Indicates that the Service Fabric application should not be created or upgraded after registering the application type. - -.PARAMETER ApplicationParameter -Hashtable of the Service Fabric application parameters to be used for the application. - -.PARAMETER UnregisterUnusedApplicationVersionsAfterUpgrade -Indicates whether to unregister any unused application versions that exist after an upgrade is finished. - -.PARAMETER OverrideUpgradeBehavior -Indicates the behavior used to override the upgrade settings specified by the publish profile. -'None' indicates that the upgrade settings will not be overridden. -'ForceUpgrade' indicates that an upgrade will occur with default settings, regardless of what is specified in the publish profile. -'VetoUpgrade' indicates that an upgrade will not occur, regardless of what is specified in the publish profile. - -.PARAMETER UseExistingClusterConnection -Indicates that the script should make use of an existing cluster connection that has already been established in the PowerShell session. The cluster connection parameters configured in the publish profile are ignored. - -.PARAMETER OverwriteBehavior -Overwrite Behavior if an application exists in the cluster with the same name. Available Options are Never, Always, SameAppTypeAndVersion. This setting is not applicable when upgrading an application. -'Never' will not remove the existing application. This is the default behavior. -'Always' will remove the existing application even if its Application type and Version is different from the application being created. -'SameAppTypeAndVersion' will remove the existing application only if its Application type and Version is same as the application being created. - -.PARAMETER SkipPackageValidation -Switch signaling whether the package should be validated or not before deployment. - -.PARAMETER SecurityToken -A security token for authentication to cluster management endpoints. Used for silent authentication to clusters that are protected by Azure Active Directory. - -.PARAMETER CopyPackageTimeoutSec -Timeout in seconds for copying application package to image store. - -.EXAMPLE -. Scripts\Deploy-FabricApplication.ps1 -ApplicationPackagePath 'pkg\Debug' - -Deploy the application using the default package location for a Debug build. - -.EXAMPLE -. Scripts\Deploy-FabricApplication.ps1 -ApplicationPackagePath 'pkg\Debug' -DoNotCreateApplication - -Deploy the application but do not create the application instance. - -.EXAMPLE -. Scripts\Deploy-FabricApplication.ps1 -ApplicationPackagePath 'pkg\Debug' -ApplicationParameter @{CustomParameter1='MyValue'; CustomParameter2='MyValue'} - -Deploy the application by providing values for parameters that are defined in the application manifest. -#> - -Param -( - [String] - $PublishProfileFile, - - [String] - $ApplicationPackagePath, - - [Switch] - $DeployOnly, - - [Hashtable] - $ApplicationParameter, - - [Boolean] - $UnregisterUnusedApplicationVersionsAfterUpgrade, - - [String] - [ValidateSet('None', 'ForceUpgrade', 'VetoUpgrade')] - $OverrideUpgradeBehavior = 'None', - - [Switch] - $UseExistingClusterConnection, - - [String] - [ValidateSet('Never','Always','SameAppTypeAndVersion')] - $OverwriteBehavior = 'Never', - - [Switch] - $SkipPackageValidation, - - [String] - $SecurityToken, - - [int] - $CopyPackageTimeoutSec -) - -function Read-XmlElementAsHashtable -{ - Param ( - [System.Xml.XmlElement] - $Element - ) - - $hashtable = @{} - if ($Element.Attributes) - { - $Element.Attributes | - ForEach-Object { - $boolVal = $null - if ([bool]::TryParse($_.Value, [ref]$boolVal)) { - $hashtable[$_.Name] = $boolVal - } - else { - $hashtable[$_.Name] = $_.Value - } - } - } - - return $hashtable -} - -function Read-PublishProfile -{ - Param ( - [ValidateScript({Test-Path $_ -PathType Leaf})] - [String] - $PublishProfileFile - ) - - $publishProfileXml = [Xml] (Get-Content $PublishProfileFile) - $publishProfile = @{} - - $publishProfile.ClusterConnectionParameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("ClusterConnectionParameters") - $publishProfile.UpgradeDeployment = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("UpgradeDeployment") - $publishProfile.CopyPackageParameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("CopyPackageParameters") - - if ($publishProfileXml.PublishProfile.Item("UpgradeDeployment")) - { - $publishProfile.UpgradeDeployment.Parameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("UpgradeDeployment").Item("Parameters") - if ($publishProfile.UpgradeDeployment["Mode"]) - { - $publishProfile.UpgradeDeployment.Parameters[$publishProfile.UpgradeDeployment["Mode"]] = $true - } - } - - $publishProfileFolder = (Split-Path $PublishProfileFile) - $publishProfile.ApplicationParameterFile = [System.IO.Path]::Combine($PublishProfileFolder, $publishProfileXml.PublishProfile.ApplicationParameterFile.Path) - - return $publishProfile -} - -$LocalFolder = (Split-Path $MyInvocation.MyCommand.Path) - -if (!$PublishProfileFile) -{ - $PublishProfileFile = "$LocalFolder\..\PublishProfiles\Local.xml" -} - -if (!$ApplicationPackagePath) -{ - $ApplicationPackagePath = "$LocalFolder\..\pkg\Release" -} - -$ApplicationPackagePath = Resolve-Path $ApplicationPackagePath - -$publishProfile = Read-PublishProfile $PublishProfileFile - -if (-not $UseExistingClusterConnection) -{ - $ClusterConnectionParameters = $publishProfile.ClusterConnectionParameters - if ($SecurityToken) - { - $ClusterConnectionParameters["SecurityToken"] = $SecurityToken - } - - try - { - [void](Connect-ServiceFabricCluster @ClusterConnectionParameters) - $global:clusterConnection = $clusterConnection - } - catch [System.Fabric.FabricObjectClosedException] - { - Write-Warning "Service Fabric cluster may not be connected." - throw - } -} - -$RegKey = "HKLM:\SOFTWARE\Microsoft\Service Fabric SDK" -$ModuleFolderPath = (Get-ItemProperty -Path $RegKey -Name FabricSDKPSModulePath).FabricSDKPSModulePath -Import-Module "$ModuleFolderPath\ServiceFabricSDK.psm1" - -$IsUpgrade = ($publishProfile.UpgradeDeployment -and $publishProfile.UpgradeDeployment.Enabled -and $OverrideUpgradeBehavior -ne 'VetoUpgrade') -or $OverrideUpgradeBehavior -eq 'ForceUpgrade' - -$PublishParameters = @{ - 'ApplicationPackagePath' = $ApplicationPackagePath - 'ApplicationParameterFilePath' = $publishProfile.ApplicationParameterFile - 'ApplicationParameter' = $ApplicationParameter - 'ErrorAction' = 'Stop' -} - -if ($publishProfile.CopyPackageParameters.CopyPackageTimeoutSec) -{ - $PublishParameters['CopyPackageTimeoutSec'] = $publishProfile.CopyPackageParameters.CopyPackageTimeoutSec -} - -if ($publishProfile.CopyPackageParameters.CompressPackage) -{ - $PublishParameters['CompressPackage'] = $publishProfile.CopyPackageParameters.CompressPackage -} - -# CopyPackageTimeoutSec parameter overrides the value from the publish profile -if ($CopyPackageTimeoutSec) -{ - $PublishParameters['CopyPackageTimeoutSec'] = $CopyPackageTimeoutSec -} - -if ($IsUpgrade) -{ - $Action = "RegisterAndUpgrade" - if ($DeployOnly) - { - $Action = "Register" - } - - $UpgradeParameters = $publishProfile.UpgradeDeployment.Parameters - - if ($OverrideUpgradeBehavior -eq 'ForceUpgrade') - { - # Warning: Do not alter these upgrade parameters. It will create an inconsistency with Visual Studio's behavior. - $UpgradeParameters = @{ UnmonitoredAuto = $true; Force = $true } - } - - $PublishParameters['Action'] = $Action - $PublishParameters['UpgradeParameters'] = $UpgradeParameters - $PublishParameters['UnregisterUnusedVersions'] = $UnregisterUnusedApplicationVersionsAfterUpgrade - - Publish-UpgradedServiceFabricApplication @PublishParameters -} -else -{ - $Action = "RegisterAndCreate" - if ($DeployOnly) - { - $Action = "Register" - } - - $PublishParameters['Action'] = $Action - $PublishParameters['OverwriteBehavior'] = $OverwriteBehavior - $PublishParameters['SkipPackageValidation'] = $SkipPackageValidation - - Publish-NewServiceFabricApplication @PublishParameters -} \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/Scripts/Undeploy-FabricApplication.ps1 b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/Scripts/Undeploy-FabricApplication.ps1 deleted file mode 100644 index db6414eeaf..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/Scripts/Undeploy-FabricApplication.ps1 +++ /dev/null @@ -1,103 +0,0 @@ -Param -( - [String] - $ApplicationName, - - [String] - $PublishProfileFile, - - [Switch] - $UseExistingClusterConnection - -) - -function Read-XmlElementAsHashtable -{ - Param ( - [System.Xml.XmlElement] - $Element - ) - - $hashtable = @{} - if ($Element.Attributes) - { - $Element.Attributes | - ForEach-Object { - $boolVal = $null - if ([bool]::TryParse($_.Value, [ref]$boolVal)) { - $hashtable[$_.Name] = $boolVal - } - else { - $hashtable[$_.Name] = $_.Value - } - } - } - - return $hashtable -} - -function Read-PublishProfile -{ - Param ( - [ValidateScript({Test-Path $_ -PathType Leaf})] - [String] - $PublishProfileFile - ) - - $publishProfileXml = [Xml] (Get-Content $PublishProfileFile) - $publishProfile = @{} - - $publishProfile.ClusterConnectionParameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("ClusterConnectionParameters") - $publishProfile.UpgradeDeployment = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("UpgradeDeployment") - $publishProfile.CopyPackageParameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("CopyPackageParameters") - - if ($publishProfileXml.PublishProfile.Item("UpgradeDeployment")) - { - $publishProfile.UpgradeDeployment.Parameters = Read-XmlElementAsHashtable $publishProfileXml.PublishProfile.Item("UpgradeDeployment").Item("Parameters") - if ($publishProfile.UpgradeDeployment["Mode"]) - { - $publishProfile.UpgradeDeployment.Parameters[$publishProfile.UpgradeDeployment["Mode"]] = $true - } - } - - $publishProfileFolder = (Split-Path $PublishProfileFile) - $publishProfile.ApplicationParameterFile = [System.IO.Path]::Combine($PublishProfileFolder, $publishProfileXml.PublishProfile.ApplicationParameterFile.Path) - - return $publishProfile -} - -$LocalFolder = (Split-Path $MyInvocation.MyCommand.Path) - -if (!$PublishProfileFile) -{ - $PublishProfileFile = "$LocalFolder\..\PublishProfiles\Local.xml" -} - -$publishProfile = Read-PublishProfile $PublishProfileFile - -if (-not $UseExistingClusterConnection) -{ - $ClusterConnectionParameters = $publishProfile.ClusterConnectionParameters - if ($SecurityToken) - { - $ClusterConnectionParameters["SecurityToken"] = $SecurityToken - } - - try - { - [void](Connect-ServiceFabricCluster @ClusterConnectionParameters) - $global:clusterConnection = $clusterConnection - } - catch [System.Fabric.FabricObjectClosedException] - { - Write-Warning "Service Fabric cluster may not be connected." - throw - } -} - -$RegKey = "HKLM:\SOFTWARE\Microsoft\Service Fabric SDK" -$ModuleFolderPath = (Get-ItemProperty -Path $RegKey -Name FabricSDKPSModulePath).FabricSDKPSModulePath -Import-Module "$ModuleFolderPath\ServiceFabricSDK.psm1" - -# Remove an application instance -Unpublish-ServiceFabricApplication -ApplicationName $ApplicationName diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ServiceFabricApplication.sfproj b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ServiceFabricApplication.sfproj deleted file mode 100644 index 5ca1348e55..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/ServiceFabricApplication.sfproj +++ /dev/null @@ -1,56 +0,0 @@ - - - - - 11553d91-149b-441f-87ed-b5f929dd14f7 - 2.0 - 1.5 - 1.6.5 - v4.5 - - - - Debug - AnyCPU - - - Debug - x64 - - - Release - AnyCPU - - - Release - x64 - - - - - - - - - - - - - - - - - - - - - - $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Service Fabric Tools\Microsoft.VisualStudio.Azure.Fabric.ApplicationProject.targets - - - - - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/packages.config b/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/packages.config deleted file mode 100644 index 37bc6f0645..0000000000 --- a/tests/Agent/PlatformTests/Applications/ServiceFabricApplication/ServiceFabricApplication/packages.config +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/tests/Agent/PlatformTests/PlatformTests.sln b/tests/Agent/PlatformTests/PlatformTests.sln deleted file mode 100644 index bbe8215498..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests.sln +++ /dev/null @@ -1,79 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26730.8 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PlatformTests", "PlatformTests\PlatformTests.csproj", "{2E3DF5C2-8A38-4A03-86D7-8D463C917E47}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegrationTestHelpers", "..\IntegrationTests\IntegrationTestHelpers\IntegrationTestHelpers.csproj", "{9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Shared", "..\IntegrationTests\Shared\Shared.csproj", "{8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|ARM = Debug|ARM - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|ARM = Release|ARM - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Debug|ARM.ActiveCfg = Debug|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Debug|ARM.Build.0 = Debug|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Debug|x64.ActiveCfg = Debug|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Debug|x64.Build.0 = Debug|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Debug|x86.ActiveCfg = Debug|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Debug|x86.Build.0 = Debug|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Release|Any CPU.Build.0 = Release|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Release|ARM.ActiveCfg = Release|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Release|ARM.Build.0 = Release|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Release|x64.ActiveCfg = Release|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Release|x64.Build.0 = Release|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Release|x86.ActiveCfg = Release|Any CPU - {2E3DF5C2-8A38-4A03-86D7-8D463C917E47}.Release|x86.Build.0 = Release|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Debug|ARM.ActiveCfg = Debug|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Debug|ARM.Build.0 = Debug|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Debug|x64.ActiveCfg = Debug|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Debug|x64.Build.0 = Debug|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Debug|x86.ActiveCfg = Debug|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Debug|x86.Build.0 = Debug|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Release|Any CPU.Build.0 = Release|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Release|ARM.ActiveCfg = Release|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Release|ARM.Build.0 = Release|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Release|x64.ActiveCfg = Release|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Release|x64.Build.0 = Release|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Release|x86.ActiveCfg = Release|Any CPU - {9AABBBB0-32FC-4DA3-A38C-96A50A7ABAC1}.Release|x86.Build.0 = Release|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Debug|ARM.ActiveCfg = Debug|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Debug|ARM.Build.0 = Debug|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Debug|x64.ActiveCfg = Debug|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Debug|x64.Build.0 = Debug|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Debug|x86.ActiveCfg = Debug|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Debug|x86.Build.0 = Debug|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Release|Any CPU.ActiveCfg = Release|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Release|Any CPU.Build.0 = Release|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Release|ARM.ActiveCfg = Release|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Release|ARM.Build.0 = Release|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Release|x64.ActiveCfg = Release|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Release|x64.Build.0 = Release|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Release|x86.ActiveCfg = Release|Any CPU - {8CFEBED7-4137-4D82-AC1E-D12F47EA43EF}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {20BFF902-E76E-4746-BD98-9BBC5CD15694} - EndGlobalSection -EndGlobal diff --git a/tests/Agent/PlatformTests/PlatformTests/Applications/AzureWebApplication.cs b/tests/Agent/PlatformTests/PlatformTests/Applications/AzureWebApplication.cs deleted file mode 100644 index 8cc5ecf71a..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Applications/AzureWebApplication.cs +++ /dev/null @@ -1,184 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System; -using System.Collections; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Threading; - -namespace PlatformTests.Applications -{ - public class AzureWebApplication : BaseApplication - { - private const string TestPackageName = "NewRelic.Azure.WebSites.x64"; - - private static string TestPackageLocalPath { get; } = Path.GetFullPath(Path.Combine(RootRepositoryPath, @"build\BuildArtifacts\NugetAzureWebSites-x64\")); - - public String ApplicationRootDirectory { get; } - - public String ApplicationOutputPath { get; } - - public String SolutionConfiguration { get; } - - public AzureWebApplication(string applicationName, string testSettingCategory) : base(applicationName, null, testSettingCategory) - { - ApplicationRootDirectory = Path.GetFullPath(Path.Combine(RootRepositoryPath, $@"tests\Agent\PlatformTests\Applications\{ApplicationName}")); - - SolutionConfiguration = "Release"; -#if DEBUG - SolutionConfiguration = "Debug"; -#endif - - ApplicationOutputPath = Path.Combine(ApplicationRootDirectory, $@"{ApplicationName}\bin\{SolutionConfiguration}"); - } - - public override string[] NugetSources { get; } = - { - TestPackageLocalPath, - "https://api.nuget.org/v3/index.json" - }; - - public override void InstallAgent() - { - var version = GetNugetPackageVersion(TestPackageLocalPath); - - TestLogger?.WriteLine($@"[{DateTime.Now}] Installing {TestPackageName} version {version} ."); - - RestoreNuGetPackage(NugetSources); - - UpdateNewRelicAgentNuGetPackage(TestPackageName, version, NugetSources); - - TestLogger?.WriteLine($@"[{DateTime.Now}] {TestPackageName} version {version} installed."); - } - - private string GetNugetPackageVersion(string nugetSource) - { - var package = Directory.GetFiles(nugetSource).FirstOrDefault(); - if (package != null) - { - var parts = package.Split('.'); - - return $@"{parts[parts.Length - 5]}.{parts[parts.Length - 4]}.{parts[parts.Length - 3]}.{parts[parts.Length - 2]}"; - } - - return String.Empty; - } - - private void RestoreNuGetPackage(string[] sources) - { - TestLogger?.WriteLine($@"[{DateTime.Now}] Restoring NuGet packages."); - - var solutionFile = Path.Combine(ApplicationRootDirectory, $@"{ApplicationName}.sln"); - var sourceArgument = String.Join(";", sources); - - var arguments = $@"restore {solutionFile} -Source ""{sourceArgument}"" -NoCache -NonInteractive"; - - try - { - InvokeAnExecutable(NugetPath, arguments, ApplicationRootDirectory); - } - catch - { - throw new Exception($@"There were errors while restoring nuget packages for {solutionFile}"); - } - - TestLogger?.WriteLine($@"[{DateTime.Now}] Nuget packages restored."); - } - - private void UpdateNewRelicAgentNuGetPackage(string packageName, string version, string[] sources) - { - TestLogger?.WriteLine($@"[{DateTime.Now}] Restoring NuGet packages."); - - var solutionFile = Path.Combine(ApplicationRootDirectory, $@"{ApplicationName}.sln"); - var sourceArgument = String.Join(";", sources); - - var arguments = $@"update {solutionFile} -Id {packageName} -Version {version} -Source ""{sourceArgument}"" -FileConflictAction overwrite -NonInteractive"; - - try - { - InvokeAnExecutable(NugetPath, arguments, ApplicationRootDirectory); - } - catch - { - throw new Exception($@"There were errors while updating nuget packages for {solutionFile}"); - } - - TestLogger?.WriteLine($@"[{DateTime.Now}] Nuget packages updated."); - } - - public override void BuildAndDeploy() - { - DeleteNewRelicLogFiles(); - - //Building and deploying app service - TestLogger?.WriteLine($@"[{DateTime.Now}] Building and deploying the test application."); - var userName = TestConfiguration["UserName"]; - var password = TestConfiguration["Password"]; - var workingDirectory = Path.Combine(ApplicationRootDirectory, ApplicationName); - var arguments = $@"{ApplicationName}.csproj /p:DeployOnBuild=true /p:PublishProfile=DeployProfile /p:Configuration={SolutionConfiguration} /p:username={userName} /p:Password={password} "; - try - { - InvokeAnExecutable(MsbuildPath, arguments, workingDirectory); - } - catch (Exception ex) - { - throw new Exception($"There were errors while packaging the test application: {ex.Message}"); - } - - TestLogger?.WriteLine($@"[{DateTime.Now}] Finished."); - } - - public override void StopTestApplicationService() - { - } - - private void DeleteNewRelicLogFiles() - { - var userName = TestConfiguration["UserName"]; - var password = TestConfiguration["Password"]; - var credentials = new NetworkCredential($@"{ApplicationName}\{userName}", password); - var newRelicLogFilesUri = TestConfiguration["NewRelicLogFilesUri"]; - var filesToDelete = GetFiles(newRelicLogFilesUri, credentials); - - foreach (var fileName in filesToDelete) - { - var reqFtp = WebRequest.Create(newRelicLogFilesUri + $@"/{fileName}"); - reqFtp.Method = WebRequestMethods.Ftp.DeleteFile; - reqFtp.Credentials = credentials; - - using (reqFtp.GetResponse()) - { - - } - } - } - - private IEnumerable GetFiles(string uri, ICredentials credentials) - { - var reqFtp = WebRequest.Create(uri); - reqFtp.Method = WebRequestMethods.Ftp.ListDirectory; - reqFtp.Credentials = credentials; - - var files = new List(); - - using (var response = reqFtp.GetResponse()) - { - var responseStream = response.GetResponseStream(); - using (var reader = new StreamReader(responseStream)) - { - string line; - while ((line = reader.ReadLine()) != null) - { - files.Add(line); - } - } - } - - return files; - } - } -} - diff --git a/tests/Agent/PlatformTests/PlatformTests/Applications/BaseApplication.cs b/tests/Agent/PlatformTests/PlatformTests/Applications/BaseApplication.cs deleted file mode 100644 index 31664ca17a..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Applications/BaseApplication.cs +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System; -using System.Diagnostics; -using System.IO; -using NewRelic.Agent.IntegrationTests.Shared; -using Xunit.Abstractions; - -namespace PlatformTests.Applications -{ - public abstract class BaseApplication - { - public string ApplicationName { get; } - - public string[] ServiceNames { get; } - - public ITestOutputHelper TestLogger { get; set; } - - private string _testSettingCategory; - - private IntegrationTestConfiguration _testConfiguration; - - public IntegrationTestConfiguration TestConfiguration - { - get - { - if (_testConfiguration == null) - { - _testConfiguration = IntegrationTestConfiguration.GetIntegrationTestConfiguration(_testSettingCategory); - } - - return _testConfiguration; - } - } - - - protected BaseApplication(string applicationName, string[] serviceNames, string testSettingCategory) - { - ApplicationName = applicationName; - ServiceNames = serviceNames; - _testSettingCategory = testSettingCategory; - } - - public static string RootRepositoryPath { get; } = Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\..\..\..\..\"); - - public String MsbuildPath - { - get - { - var path = Environment.GetEnvironmentVariable("MsBuildPath"); - if (path != null) - { - return path; - } - - if (File.Exists(@"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\MSBuild.exe")) - { - return @"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\MSBuild.exe"; - } - - if (File.Exists(@"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe")) - { - return @"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\MSBuild.exe"; - } - - if (File.Exists(@"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\msbuild.exe")) - { - return @"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\msbuild.exe"; - } - - if (File.Exists(@"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MsBuild.exe")) - { - return @"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MsBuild.exe"; - } - - throw new Exception("Can not locate MsBuild.exe ."); - } - } - - public virtual String[] NugetSources { get; } = - { - "https://api.nuget.org/v3/index.json" - }; - - public static string NugetPath { get; } = Path.GetFullPath(Path.Combine(RootRepositoryPath, @"build\Tools\nuget.4.4.1.exe")); - - public void InvokeAnExecutable(string executablePath, string arguments, string workingDirectory) - { - TestLogger?.WriteLine($@"[{DateTime.Now}] Executing: '{executablePath} {arguments}' in ({workingDirectory})"); - - var startInfo = new ProcessStartInfo - { - Arguments = arguments, - FileName = executablePath, - UseShellExecute = false, - WorkingDirectory = workingDirectory, - RedirectStandardOutput = true, - RedirectStandardError = true - }; - - Process process = Process.Start(startInfo); - - if (process == null) - { - throw new Exception($@"[{DateTime.Now}] {executablePath} process failed to start."); - } - - LogProcessOutput(process.StandardOutput); - LogProcessOutput(process.StandardError); - - process.WaitForExit(); - - if (process.HasExited && process.ExitCode != 0) - { - throw new Exception("App server shutdown unexpectedly."); - } - - } - - private void LogProcessOutput(TextReader reader) - { - string line; - - while ((line = reader.ReadLine()) != null) - { - TestLogger?.WriteLine($@"[{DateTime.Now}] {line}"); - } - } - - public abstract void InstallAgent(); - public abstract void BuildAndDeploy(); - public abstract void StopTestApplicationService(); - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Applications/ServiceFabricApplication.cs b/tests/Agent/PlatformTests/PlatformTests/Applications/ServiceFabricApplication.cs deleted file mode 100644 index fdfe7ce741..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Applications/ServiceFabricApplication.cs +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Security.Cryptography.X509Certificates; -using System.Xml; -using NewRelic.Agent.IntegrationTestHelpers; - -namespace PlatformTests.Applications -{ - public class ServiceFabricApplication : BaseApplication - { - public String ApplicationRootDirectory { get; } - - public String ApplicationPackagePath { get; } - - public String SolutionConfiguration { get; } - - public ServiceFabricApplication(string applicationName, string[] serviceNames, string testSettingCategory) : base(applicationName, serviceNames, testSettingCategory) - { - ApplicationRootDirectory = Path.GetFullPath(Path.Combine(RootRepositoryPath, $@"tests\Agent\PlatformTests\Applications\{ApplicationName}")); - - SolutionConfiguration = "Release"; -#if DEBUG - SolutionConfiguration = "Debug"; -#endif - - ApplicationPackagePath = Path.Combine(ApplicationRootDirectory, $@"{ApplicationName}\pkg\{SolutionConfiguration}"); - } - - public override string[] NugetSources { get; } = - { - Path.GetFullPath(Path.Combine(RootRepositoryPath, @"build\BuildArtifacts\NugetAgent\")), - "https://api.nuget.org/v3/index.json" - }; - - public override void InstallAgent() - { - var packageName = "NewRelic.Agent"; - - var version = SearchForNewestNugetVersion(Path.GetFullPath(Path.Combine(RootRepositoryPath, @"build\BuildArtifacts\NugetAgent\"))); - - TestLogger?.WriteLine($@"[{DateTime.Now}] Installing {packageName} version {version} ."); - - UpdatePackageReference(packageName, version); - - TestLogger?.WriteLine($@"[{DateTime.Now}] {packageName} version {version} installed."); - - RestoreNuGetPackage(NugetSources); - } - - private string SearchForNewestNugetVersion(string nugetSource) - { - List packages = new List(); - - foreach (var file in Directory.GetFiles(nugetSource)) - { - packages.Add(Path.GetFileNameWithoutExtension(file)); - } - - var package = packages.First(); - var parts = package.Split('.'); - - return $@"{ parts[parts.Length - 4]}.{parts[parts.Length - 3]}.{parts[parts.Length - 2]}.{parts[parts.Length - 1]}"; - } - - private void UpdatePackageReference(string packageName, string version) - { - foreach (var serviceName in ServiceNames) - { - var projectFile = Path.Combine(ApplicationRootDirectory, $@"{serviceName}\{serviceName}.csproj"); - - const string ns = "http://schemas.microsoft.com/developer/msbuild/2003"; - var xml = new XmlDocument(); - var nsmgr = new XmlNamespaceManager(xml.NameTable); - nsmgr.AddNamespace("msbld", ns); - - xml.Load(projectFile); - - var packageReferenceNode = xml.SelectSingleNode($@"//msbld:PackageReference[@Include='{packageName}']", nsmgr); - - if (packageReferenceNode?.Attributes != null) packageReferenceNode.Attributes["Version"].Value = version; - - xml.Save(projectFile); - } - } - - private void RestoreNuGetPackage(string[] sources) - { - TestLogger?.WriteLine($@"[{DateTime.Now}] Restoring NuGet packages."); - - var solutionFile = Path.Combine(ApplicationRootDirectory, $@"{ApplicationName}.sln"); - var sourceArgument = String.Join(";", sources); - - var arguments = $@"restore {solutionFile} -Source ""{sourceArgument}"" -NoCache -NonInteractive"; - - try - { - InvokeAnExecutable(NugetPath, arguments, ApplicationRootDirectory); - } - catch (Exception ex) - { - throw new Exception($@"There were errors while restoring nuget packages for {solutionFile}: {ex.Message}"); - } - - TestLogger?.WriteLine($@"[{DateTime.Now}] Nuget packages restored."); - } - - private void BuildAndPackage() - { - TestLogger?.WriteLine($@"[{DateTime.Now}] Building and packaging the test application."); - - var workingDirectory = Path.Combine(ApplicationRootDirectory, ApplicationName); - var arguments = $@"{ApplicationName}.sfproj /t:Package /p:Configuration={SolutionConfiguration}"; - try - { - InvokeAnExecutable(MsbuildPath, arguments, workingDirectory); - } - catch (Exception ex) - { - throw new Exception($"There were errors while packaging the test application. Exception: {ex.Message}"); - } - - TestLogger?.WriteLine($@"[{DateTime.Now}] Finished."); - } - - public override void BuildAndDeploy() - { - UpdatePublishProfile(); - - BuildAndPackage(); - - UpdateNewRelicConfig(); - - TestLogger?.WriteLine($@"[{DateTime.Now}] ... Deploying"); - - var arguments = $@".\Scripts\Deploy-FabricApplication.ps1 -PublishProfileFile .\PublishProfiles\Cloud.xml -ApplicationPackagePath .\pkg\{SolutionConfiguration} -OverwriteBehavior Always"; - var workingDirectory = Path.Combine(ApplicationRootDirectory, ApplicationName); - - try - { - InvokeAnExecutable("powershell.exe", arguments, workingDirectory); - } - catch - { - throw new Exception("There were errors while deploying the test application"); - } - - TestLogger?.WriteLine($@"[{DateTime.Now}] ... Deployed"); - - } - - private void UpdatePublishProfile() - { - var publishFile = Path.Combine(ApplicationRootDirectory, $@"{ApplicationName}\PublishProfiles\Cloud.xml"); - const string ns = "http://schemas.microsoft.com/2015/05/fabrictools"; - var xml = new XmlDocument(); - var nsmgr = new XmlNamespaceManager(xml.NameTable); - nsmgr.AddNamespace("msbld", ns); - - xml.Load(publishFile); - - var clusterConnectionNode = xml.SelectSingleNode($@"//msbld:ClusterConnectionParameters[@StoreLocation='CurrentUser']", nsmgr); - - if (clusterConnectionNode?.Attributes != null) - { - clusterConnectionNode.Attributes["ConnectionEndpoint"].Value = TestConfiguration["ConnectionEndpoint"]; - clusterConnectionNode.Attributes["ServerCertThumbprint"].Value = TestConfiguration["ServerCertThumbprint"]; - clusterConnectionNode.Attributes["FindValue"].Value = TestConfiguration["ServerCertThumbprint"]; - } - - xml.Save(publishFile); - } - - public override void StopTestApplicationService() - { - TestLogger?.WriteLine($@"[{DateTime.Now}] ... Undeploying"); - - var arguments = $@".\Scripts\Undeploy-FabricApplication.ps1 -ApplicationName fabric:/{ApplicationName} -PublishProfileFile .\PublishProfiles\Cloud.xml"; - var workingDirectory = Path.Combine(ApplicationRootDirectory, ApplicationName); - - try - { - InvokeAnExecutable("powershell.exe", arguments, workingDirectory); - } - catch - { - throw new Exception("There were errors while undeploying the test application"); - } - - TestLogger?.WriteLine($@"[{DateTime.Now}] ... Undeployed"); - } - - private void UpdateNewRelicConfig() - { - foreach (var serviceName in ServiceNames) - { - var newRelicConfigPath = Path.Combine(ApplicationPackagePath, $@"{serviceName}Pkg/Code/newrelic/newrelic.config"); - var newRelicConfigModifier = new NewRelicConfigModifier(newRelicConfigPath); - newRelicConfigModifier.ForceTransactionTraces(); - newRelicConfigModifier.SetLogLevel("debug"); - newRelicConfigModifier.SetLicenseKey(TestConfiguration.LicenseKey); - newRelicConfigModifier.SetHost(TestConfiguration.CollectorUrl); - } - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/AzureWebApplicationSmokeTest.cs b/tests/Agent/PlatformTests/PlatformTests/AzureWebApplicationSmokeTest.cs deleted file mode 100644 index d5272a1d99..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/AzureWebApplicationSmokeTest.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using NewRelic.Agent.IntegrationTestHelpers; -using PlatformTests.Fixtures; -using Xunit; -using Xunit.Abstractions; - -namespace PlatformTests -{ - public class AzureWebApplicationSmokeTest : IClassFixture - { - private AzureWebApplicationFixture _fixture; - - private AgentLogString _agentLog; - - public AzureWebApplicationSmokeTest(AzureWebApplicationFixture fixture, ITestOutputHelper output) - { - _fixture = fixture; - _fixture.TestLogger = output; - - _fixture.Exercise = () => - { - _fixture.WarmUp(); - var agentLogString = _fixture.GetAgentLog(); - _agentLog = new AgentLogString(agentLogString); - }; - - _fixture.Initialize(); - } - - [Fact] - public void Test() - { - var transactionSamples = _agentLog.GetTransactionSamples(); - Assert.NotEmpty(transactionSamples); - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaApplicationFixture.cs b/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaApplicationFixture.cs deleted file mode 100644 index 619e074dc2..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaApplicationFixture.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System.Net; -using System.Threading; -using PlatformTests.Applications; -using Xunit; - -namespace PlatformTests.Fixtures -{ - public class AwsLambdaApplicationFixture : BaseFixture - { - public const string TestSettingCategory = "AwsLambdaSmokeTests"; - - public string LogGroupName => ((AwsLambdaApplication)Application).LogGroupName; - - public AwsLambdaApplicationFixture() : base(new AwsLambdaApplication("AwsLambdaTestApplication", TestSettingCategory)) - { - } - - public void ExerciseFunction() - { - ((AwsLambdaApplication)Application).ExerciseFunction(); - Thread.Sleep(5000); - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaAwsSdkTestFixture .cs b/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaAwsSdkTestFixture .cs deleted file mode 100644 index 8eaaf5acae..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaAwsSdkTestFixture .cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System.Net; -using System.Threading; -using PlatformTests.Applications; -using Xunit; - -namespace PlatformTests.Fixtures -{ - public class AwsLambdaAwsSdkTestFixture : BaseFixture - { - public const string TestSettingCategory = "AwsLambdaAwsSdkTests"; - - public string LogGroupName => ((AwsLambdaApplication)Application).LogGroupName; - - public AwsLambdaAwsSdkTestFixture() : base(new AwsLambdaApplication("AwsLambdaAwsSdkTestFunction", TestSettingCategory)) - { - } - - public void ExerciseFunction() - { - var accessKeyId = Application.TestConfiguration.DefaultSetting.AwsAccessKeyId; - var secretKeyId = Application.TestConfiguration.DefaultSetting.AwsSecretAccessKey; - var accountNumber = Application.TestConfiguration.DefaultSetting.AwsAccountNumber; - var queryString = $"AwsAccessKeyId={accessKeyId}&AwsSecretAccessKey={secretKeyId}&AwsAccountNumber={accountNumber}"; - - ((AwsLambdaApplication)Application).ExerciseFunction(queryStringParameters: queryString); - Thread.Sleep(5000); - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaDTTestFixture.cs b/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaDTTestFixture.cs deleted file mode 100644 index fa058d61a9..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaDTTestFixture.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System; -using System.Net; -using System.Threading; -using PlatformTests.Applications; -using Xunit; - -namespace PlatformTests.Fixtures -{ - public class AwsLambdaDTTestFixture : BaseFixture - { - public string CalleeApplicationLogs => ((AwsLambdaApplication)base.Application).LogGroupName; - public string CallerApplicationLogs => CallerApplication.LogGroupName; - - public AwsLambdaApplication CalleeApplication => (AwsLambdaApplication)base.Application; - public AwsLambdaApplication CallerApplication; - - public AwsLambdaDTTestFixture() : base(new AwsLambdaApplication("AwsLambdaTestApplication", "AwsLambdaDTTestCallee")) //callee - { - CallerApplication = new AwsLambdaApplication("AwsLambdaChainCallingApplication", "AwsLambdaDTTestCaller"); //caller - InitializeCallingApplication(); - } - - public void WarmUpCalleeApp() - { - CalleeApplication.ExerciseFunction(); - Thread.Sleep(5000); - } - - public void ExerciseChainTest() - { - var calleeResourceId = CalleeApplication.TestConfiguration["ApplicationGatewayResourceId"]; - var calleeUrl = $"https://{calleeResourceId}.execute-api.us-west-2.amazonaws.com/test/{CalleeApplication.ApplicationName}"; - - var queryString = $"calleeUrl={calleeUrl}"; - - CallerApplication.ExerciseFunction(null, queryString); - Thread.Sleep(5000); - } - - private void InitializeCallingApplication() - { - CallerApplication.TestLogger = TestLogger; - CallerApplication.InstallAgent(); - CallerApplication.BuildAndDeploy(); - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaErrorTestFixture.cs b/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaErrorTestFixture.cs deleted file mode 100644 index 380a5f80d8..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AwsLambdaErrorTestFixture.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System.Net; -using System.Threading; -using PlatformTests.Applications; - -namespace PlatformTests.Fixtures -{ - public class AwsLambdaErrorTestFixture : BaseFixture - { - public const string TestSettingCategory = "AwsLambdaErrorTests"; - - public string LogGroupName => ((AwsLambdaApplication)Application).LogGroupName; - - public AwsLambdaErrorTestFixture() : base(new AwsLambdaApplication("AwsLambdaErrorTestFunction", TestSettingCategory)) - { - } - - public void ExerciseFunction() - { - try - { - ((AwsLambdaApplication)Application).ExerciseFunction(); - Thread.Sleep(5000); - } - catch (WebException ex) - { - if (ex.Message != "The remote server returned an error: (502) Bad Gateway.") - { - throw; - } - } - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AzureWebApplicationFixture.cs b/tests/Agent/PlatformTests/PlatformTests/Fixtures/AzureWebApplicationFixture.cs deleted file mode 100644 index f90ff374ee..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Fixtures/AzureWebApplicationFixture.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System.IO; -using System.Net; -using System.Threading; -using PlatformTests.Applications; - -namespace PlatformTests.Fixtures -{ - public class AzureWebApplicationFixture : BaseFixture - { - public const string TestSettingCategory = "AzureWebApplicationTests"; - - public AzureWebApplicationFixture() : base(new AzureWebApplication("NetFrameworkBasicApplication", TestSettingCategory)) - { - } - - public void WarmUp() - { - var maxTry = 3; - for (var i = 1; i <= maxTry; i++) - { - try - { - var address = Application.TestConfiguration["TestUrl"]; - var request = (HttpWebRequest)WebRequest.Create(address); - request.Timeout = 180000; - var response = request.GetResponse(); - break; - } - catch - { - if (i == maxTry) - throw; - - Thread.Sleep(10000); - } - } - } - - public string GetAgentLog() - { - var address = Application.TestConfiguration["TestUrl"] + "/api/Logs/AgentLogWithTransactionSample"; - var request = (HttpWebRequest)WebRequest.Create(address); - request.Timeout = 300000; - var response = request.GetResponse(); - var stream = new StreamReader(response.GetResponseStream()); - - var agentLogString = stream.ReadToEnd(); - - agentLogString = agentLogString.TrimStart('"').TrimEnd('"'); - agentLogString = System.Text.RegularExpressions.Regex.Unescape(agentLogString); - - return agentLogString; - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Fixtures/BaseFixture.cs b/tests/Agent/PlatformTests/PlatformTests/Fixtures/BaseFixture.cs deleted file mode 100644 index cf11587d7f..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Fixtures/BaseFixture.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System; -using PlatformTests.Applications; -using Xunit.Abstractions; - -namespace PlatformTests.Fixtures -{ - public class BaseFixture - { - public BaseApplication Application { get; } - public ITestOutputHelper TestLogger { get; set; } - - public BaseFixture(BaseApplication application) - { - Application = application; - } - - public Action Exercise { get; set; } - - public void Initialize() - { - Application.TestLogger = TestLogger; - - Application.InstallAgent(); - - Application.BuildAndDeploy(); - - TestLogger?.WriteLine($@"[{DateTime.Now}] ... Testing"); - - Exercise.Invoke(); - - TestLogger?.WriteLine($@"[{DateTime.Now}] ... Tesing done"); - - Application.StopTestApplicationService(); - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Fixtures/ServiceFabricFixture.cs b/tests/Agent/PlatformTests/PlatformTests/Fixtures/ServiceFabricFixture.cs deleted file mode 100644 index 359bdf6293..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Fixtures/ServiceFabricFixture.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using System.IO; -using System.Net; -using System.Threading; -using NewRelic.Agent.IntegrationTests.Shared; -using PlatformTests.Applications; - -namespace PlatformTests.Fixtures -{ - public class ServiceFabricFixture : BaseFixture - { - private const string TestSettingCategory = "ServiceFabricTests"; - - public ServiceFabricFixture() : base(new ServiceFabricApplication("ServiceFabricApplication", new[] { "OwinService" }, TestSettingCategory)) - { - } - - public void WarmUp() - { - var maxTry = 3; - for (var i = 1; i <= maxTry; i++) - { - try - { - var address = $@"{Application.TestConfiguration["TestUrl"]}/api/"; - var request = (HttpWebRequest)WebRequest.Create(address); - request.Timeout = 180000; - var response = request.GetResponse(); - break; - } - catch - { - if (i == maxTry) - throw; - - Thread.Sleep(10000); - } - } - } - - public string GetAgentLog() - { - var address = $@"{Application.TestConfiguration["TestUrl"]}/api/Logs/AgentLog"; - var request = (HttpWebRequest)WebRequest.Create(address); - request.Timeout = 300000; - var response = request.GetResponse(); - var stream = new StreamReader(response.GetResponseStream()); - - var agentLogString = stream.ReadToEnd(); - - agentLogString = agentLogString.TrimStart('"').TrimEnd('"'); - agentLogString = System.Text.RegularExpressions.Regex.Unescape(agentLogString); - - return agentLogString; - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/PlatformTests.csproj b/tests/Agent/PlatformTests/PlatformTests/PlatformTests.csproj deleted file mode 100644 index 4a07358140..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/PlatformTests.csproj +++ /dev/null @@ -1,20 +0,0 @@ - - - net461 - - - - - - - - - - - - - - - - - diff --git a/tests/Agent/PlatformTests/PlatformTests/ServiceFabricOwinSmokeTest.cs b/tests/Agent/PlatformTests/PlatformTests/ServiceFabricOwinSmokeTest.cs deleted file mode 100644 index 7a6c1dbd18..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/ServiceFabricOwinSmokeTest.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -using NewRelic.Agent.IntegrationTestHelpers; -using PlatformTests.Fixtures; -using Xunit; -using Xunit.Abstractions; - -namespace PlatformTests -{ - public class ServiceFabricOwinSmokeTest : IClassFixture - { - private ServiceFabricFixture _fixture; - - private AgentLogString _agentLog; - - public ServiceFabricOwinSmokeTest(ServiceFabricFixture fixture, ITestOutputHelper output) - { - _fixture = fixture; - _fixture.TestLogger = output; - - _fixture.Exercise = () => - { - _fixture.WarmUp(); - var agentLogString = _fixture.GetAgentLog(); - _agentLog = new AgentLogString(agentLogString); - }; - - _fixture.Initialize(); - } - - [Fact] - public void Test() - { - var connectData = _agentLog.GetConnectData(); - Assert.True(connectData.UtilizationSettings.Vendors.ContainsKey("azure")); - Assert.NotEmpty(connectData.UtilizationSettings.Vendors["azure"].Location); - Assert.NotEmpty(connectData.UtilizationSettings.Vendors["azure"].Name); - Assert.NotEmpty(connectData.UtilizationSettings.Vendors["azure"].VmId); - Assert.NotEmpty(connectData.UtilizationSettings.Vendors["azure"].VmSize); - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Util/CloudWatchLogsService.cs b/tests/Agent/PlatformTests/PlatformTests/Util/CloudWatchLogsService.cs deleted file mode 100644 index 932a8f7de1..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Util/CloudWatchLogsService.cs +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - - -using System; -using System.Collections.Generic; -using Amazon.CloudWatchLogs; -using Amazon.Runtime.CredentialManagement; -using Amazon.Runtime; -using Amazon.CloudWatchLogs.Model; -using Amazon; -using System.Threading.Tasks; -using System.Linq; -using System.Diagnostics; -using System.Threading; - -namespace NewRelic.Agent.IntegrationTests.Shared.Amazon -{ - public class CloudWatchLogsService - { - private const string NRLogIdentifier = "NR_LAMBDA_MONITORING"; - private const string ProfileName = "awsunittest"; - private readonly RegionEndpoint Region = RegionEndpoint.USWest2; - private readonly CredentialProfileStoreChain _credentialProfileStoreChain = new CredentialProfileStoreChain(); - private AWSCredentials _awsCredentials; - - private AWSCredentials AwsCredentials - { - get - { - if (_awsCredentials == null) - { - _credentialProfileStoreChain.TryGetAWSCredentials(ProfileName, out _awsCredentials); - } - - return _awsCredentials; - } - } - - public async Task> GetCloudWatchEventMessagesForLogGroup(string logGroupName, DateTime startTime) - { - var result = new List(); - var stopWatch = new Stopwatch(); - - try - { - var client = new AmazonCloudWatchLogsClient(AwsCredentials, Region); - - var logStreamRequest = new DescribeLogStreamsRequest() - { - LogGroupName = logGroupName, - OrderBy = OrderBy.LastEventTime - }; - - stopWatch.Start(); - - while (stopWatch.ElapsedMilliseconds < TimeSpan.FromMinutes(1).TotalMilliseconds) - { - var logStreamsResponse = await client.DescribeLogStreamsAsync(logStreamRequest); // rate limit is 5 per second - foreach (var stream in logStreamsResponse.LogStreams) - { - var logEventsRequest = new GetLogEventsRequest() - { - LogGroupName = logGroupName, - LogStreamName = stream.LogStreamName, - StartTime = startTime, - }; - - var logEventsResponse = await client.GetLogEventsAsync(logEventsRequest); // rate limit is 10 per second - result.AddRange(logEventsResponse.Events.Select(e => e.Message).ToList()); - Thread.Sleep(150); - } - - if (result.Count > 0) - { - var nrLog = result.Where(l => l.Contains(NRLogIdentifier)); - if (nrLog?.Count() > 0) - { - break; - } - } - - Thread.Sleep(250); - } - } - catch (Exception e) - { - throw e; - } - - stopWatch.Stop(); - return result; - } - - public async Task DeleteCloudWatchLogStreamsForLogStreams(string logGroupName) - { - try - { - var client = new AmazonCloudWatchLogsClient(AwsCredentials, Region); - var logStreamRequest = new DescribeLogStreamsRequest() - { - LogGroupName = logGroupName, - OrderBy = OrderBy.LastEventTime - }; - - var logStreamsResponse = await client.DescribeLogStreamsAsync(logStreamRequest); // rate limit is 5 per second - foreach (var stream in logStreamsResponse.LogStreams) - { - var request = new DeleteLogStreamRequest(logGroupName, stream.LogStreamName); - var deleteLogStringresponse = await client.DeleteLogStreamAsync(request); - Thread.Sleep(150); - } - } - catch (Exception ex) - { - throw ex; - } - } - } -} diff --git a/tests/Agent/PlatformTests/PlatformTests/Util/CloudWatchUtilities.cs b/tests/Agent/PlatformTests/PlatformTests/Util/CloudWatchUtilities.cs deleted file mode 100644 index eb0a5b5701..0000000000 --- a/tests/Agent/PlatformTests/PlatformTests/Util/CloudWatchUtilities.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2020 New Relic, Inc. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - - -using System; -using System.Collections.Generic; -using System.IO; -using System.IO.Compression; -using System.Text; -using System.Linq; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace NewRelic.Agent.IntegrationTests.Shared.Amazon -{ - public static class CloudWatchUtilities - { - private const string NRLogIdentifier = "NR_LAMBDA_MONITORING"; - - public static string DecodeAndDecompressNewRelicPayload(string source) - { - var byteArray = Convert.FromBase64String(source); - - using (GZipStream stream = new GZipStream(new MemoryStream(byteArray), - CompressionMode.Decompress)) - { - const int size = 4096; - byte[] buffer = new byte[size]; - using (MemoryStream memory = new MemoryStream()) - { - int count = 0; - do - { - count = stream.Read(buffer, 0, size); - if (count > 0) - { - memory.Write(buffer, 0, count); - } - } - while (count > 0); - return Encoding.UTF8.GetString(memory.ToArray()); - } - } - } - - public static string GetSpanEventDataFromLog(List logs) - { - var decoded = GetNewRelicPayloadFromLogs(logs); - var spanEventData = JsonConvert.DeserializeObject(decoded)["span_event_data"]; - return spanEventData[2].ToString(); - } - - public static string GetTransactionEventDataFromLog(List logs) - { - var decoded = GetNewRelicPayloadFromLogs(logs); - var transactionEventData = JsonConvert.DeserializeObject(decoded)["analytic_event_data"]; - return transactionEventData[2].ToString(); - } - - public static string GetErrorEventDataFromLog(List logs) - { - var decoded = GetNewRelicPayloadFromLogs(logs); - var errorEventData = JsonConvert.DeserializeObject(decoded)["error_event_data"]; - return errorEventData[2].ToString(); - } - - public static string GetErrorTraceDataFromLog(List logs) - { - var decoded = GetNewRelicPayloadFromLogs(logs); - var errorTraceData = JsonConvert.DeserializeObject(decoded)["error_data"]; - return errorTraceData[1].ToString(); - } - - private static string GetNewRelicPayloadFromLogs(List logs) - { - var nrLog = logs.Where(l => l.Contains(NRLogIdentifier)).LastOrDefault(); - var jsonPayload = JsonConvert.DeserializeObject(nrLog); - return CloudWatchUtilities.DecodeAndDecompressNewRelicPayload(jsonPayload[3].ToString()); - } - } -}