Skip to content

Commit

Permalink
Added ApplicationInfoHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasArdal committed Nov 6, 2024
1 parent 23dcbb8 commit fcbca06
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/Elmah.Io.Client/ApplicationInfoHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Elmah.Io.Client
{
/// <summary>
/// A class that can provide a guess of the current application type. The class requires either >= .NET 4.5 or >= NETSTANDARD 2.0.
/// </summary>
public static class ApplicationInfoHelper
{
/// <summary>
/// Get the best guess of the current application type.
/// </summary>
/// <returns>Null or one of these values: aspnet, aspnetcore, console, azurefunction, service, windowsapp</returns>
public static string GetApplicationType()
{
#if NETSTANDARD2_0_OR_GREATER || NET45_OR_GREATER || NETCOREAPP2_0_OR_GREATER
var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToList();
var processName = Process.GetCurrentProcess().ProcessName;
if (assemblies.Exists(a => a.FullName.StartsWith("System.Web")) && (processName == "w3wp" || processName == "iisexpress"))
return "aspnet";
else if (assemblies.Exists(a => a.FullName.StartsWith("Microsoft.Azure.Functions") || a.FullName.StartsWith("Microsoft.Azure.WebJobs")))
return "azurefunction";
else if (assemblies.Exists(a => a.FullName.StartsWith("Microsoft.AspNetCore")))
return "aspnetcore";
else if (assemblies.Exists(a => a.FullName.StartsWith("System.Windows.Forms") || a.FullName.StartsWith("PresentationCore") || a.FullName.StartsWith("WindowsBase")))
return "windowsapp";
else if (!Environment.UserInteractive)
return "service";
else if (Console.OpenStandardInput() != Stream.Null)
return "console";
#endif

return null;
}
}
}
10 changes: 10 additions & 0 deletions test/Elmah.Io.Client.Test/ApplicationInfoHelperTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using NUnit.Framework;

namespace Elmah.Io.Client.Test
{
public class ApplicationInfoHelperTest
{
[Test]
public void CanGetApplicationType() => Assert.That(ApplicationInfoHelper.GetApplicationType(), Is.EqualTo("console"));
}
}

0 comments on commit fcbca06

Please sign in to comment.