Exemple #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RuntimeInfoMiddleware"/> class
        /// </summary>
        /// <param name="next"></param>
        /// <param name="options"></param>
        public RuntimeInfoMiddleware(
            RequestDelegate next,
            RuntimeInfoPageOptions options,
            ILibraryManager libraryManager,
            IRuntimeEnvironment runtimeEnvironment)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (libraryManager == null)
            {
                throw new ArgumentNullException(nameof(libraryManager));
            }

            if (runtimeEnvironment == null)
            {
                throw new ArgumentNullException(nameof(runtimeEnvironment));
            }

            _next               = next;
            _options            = options;
            _libraryManager     = libraryManager;
            _runtimeEnvironment = runtimeEnvironment;
        }
        internal static RSA GenerateKey(IRuntimeEnvironment environment) {
            if (string.Equals(environment.OperatingSystem, "Windows", StringComparison.OrdinalIgnoreCase)) {
#if DNXCORE50
                // On CoreCLR, use RSACng.
                return new RSACng(2048);
#else
                // On desktop CLR, use RSACryptoServiceProvider.
                return new RSACryptoServiceProvider(2048);
#endif
            }

            // When the runtime is identified as Mono, use RSACryptoServiceProvider, independently of the operating system.
            if (string.Equals(environment.RuntimeType, "Mono", StringComparison.OrdinalIgnoreCase)) {
                return new RSACryptoServiceProvider(2048);
            }

#if DNXCORE50
            // On Linux and Darwin, use RSAOpenSsl when running on CoreCLR.
            if (string.Equals(environment.OperatingSystem, "Linux", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(environment.OperatingSystem, "Darwin", StringComparison.OrdinalIgnoreCase)) {
                return new RSAOpenSsl(2048);
            }
#endif

            // If no appropriate implementation can be found, throw an exception.
            throw new PlatformNotSupportedException("No RSA implementation compatible with your configuration can be found.");
        }
 private static string GetDefaultDotNetReferenceAssembliesPath(IFileSystem fileSystem, IRuntimeEnvironment runtimeEnvironment)
 {            
     var os = runtimeEnvironment.OperatingSystemPlatform;
     
     if (os == Platform.Windows)
     {
         return null;
     }
     
     if (os == Platform.Darwin && 
         fileSystem.Directory.Exists("/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/xbuild-frameworks"))
     {
         return "/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/xbuild-frameworks";
     }
     
     if (fileSystem.Directory.Exists("/usr/local/lib/mono/xbuild-frameworks"))
     {
         return "/usr/local/lib/mono/xbuild-frameworks";
     }
     
     if (fileSystem.Directory.Exists("/usr/lib/mono/xbuild-frameworks"))
     {
         return "/usr/lib/mono/xbuild-frameworks";
     }
     
     return null;
 }
        public static void Register(CommandLineApplication cmdApp, IApplicationEnvironment appEnvironment, IAssemblyLoadContextAccessor loadContextAccessor, IRuntimeEnvironment runtimeEnvironment)
        {
            cmdApp.Command("graph", (Action<CommandLineApplication>)(c => {
            c.Description = "Perform parsing, static analysis, semantic analysis, and type inference";

            c.HelpOption("-?|-h|--help");

            c.OnExecute((Func<System.Threading.Tasks.Task<int>>)(async () => {
              var jsonIn = await Console.In.ReadToEndAsync();
              var sourceUnit = JsonConvert.DeserializeObject<SourceUnit>(jsonIn);

              var root = Directory.GetCurrentDirectory();
              var dir = Path.Combine(root, sourceUnit.Dir);
              var context = new GraphContext
              {
            RootPath = root,
            SourceUnit = sourceUnit,
            ProjectDirectory = dir,
            HostEnvironment = appEnvironment,
            LoadContextAccessor = loadContextAccessor,
            RuntimeEnvironment = runtimeEnvironment
              };

              var result = await GraphRunner.Graph(context);

              Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
              return 0;
            }));
              }));
        }
 public static void Setup()
 {
     _previousEnvironment = OS.Current;
     OS.Current = new RuntimeEnvironment(null);
     _tempPath = Path.Combine(Path.GetTempPath(), "Axantum.AxCrypt.Core.Test.TestFileWatcher");
     Directory.CreateDirectory(_tempPath);
 }
 public CompilationEngineContext(IApplicationEnvironment applicationEnvironment,
                                 IRuntimeEnvironment runtimeEnvironment,
                                 IAssemblyLoadContext defaultLoadContext,
                                 CompilationCache cache)
     : this(applicationEnvironment, runtimeEnvironment, defaultLoadContext, cache, NoopWatcher.Instance)
 {
 }
Exemple #7
0
        private static string GetDefaultDotNetReferenceAssembliesPath(IRuntimeEnvironment runtimeEnvironment)
        {
            var os = runtimeEnvironment.OperatingSystemPlatform;

            if (os == Platform.Windows)
            {
                return(null);
            }

            if (os == Platform.Darwin &&
                Directory.Exists("/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/xbuild-frameworks"))
            {
                return("/Library/Frameworks/Mono.framework/Versions/Current/lib/mono/xbuild-frameworks");
            }

            if (Directory.Exists("/usr/local/lib/mono/xbuild-frameworks"))
            {
                return("/usr/local/lib/mono/xbuild-frameworks");
            }

            if (Directory.Exists("/usr/lib/mono/xbuild-frameworks"))
            {
                return("/usr/lib/mono/xbuild-frameworks");
            }

            return(null);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="RuntimeInfoMiddleware"/> class
        /// </summary>
        /// <param name="next"></param>
        /// <param name="options"></param>
        public RuntimeInfoMiddleware(
            RequestDelegate next,
            RuntimeInfoPageOptions options,
            ILibraryManager libraryManager,
            IRuntimeEnvironment runtimeEnvironment)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (libraryManager == null)
            {
                throw new ArgumentNullException(nameof(libraryManager));
            }

            if (runtimeEnvironment == null)
            {
                throw new ArgumentNullException(nameof(runtimeEnvironment));
            }

            _next = next;
            _options = options;
            _libraryManager = libraryManager;
            _runtimeEnvironment = runtimeEnvironment;
        }
 public SamplingRefreshService(IConfigAccessor configAccessor,
                               IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
     : base(runtimeEnvironment, loggerFactory)
 {
     _config = configAccessor.Get <SamplingConfig>();
     DefaultSampler.Instance.SetSamplePer3Secs(_config.SamplePer3Secs);
 }
 public TraceSegmentTransportService(ITraceDispatcher dispatcher, IRuntimeEnvironment runtimeEnvironment, IOptions <SkrTraceOptions> skrTraceOptions) : base(runtimeEnvironment)
 {
     _dispatcher      = dispatcher;
     _skrTraceOptions = skrTraceOptions.Value;
     Period           = TimeSpan.FromMilliseconds(_skrTraceOptions.Interval);
     TracingContext.ListenerManager.Add(this);
 }
Exemple #11
0
 public static PlatformServices Create(
     PlatformServices basePlatformServices,
     IApplicationEnvironment application = null,
     IRuntimeEnvironment runtime = null,
     IAssemblyLoaderContainer container = null,
     IAssemblyLoadContextAccessor accessor = null,
     ILibraryManager libraryManager = null)
 {
     if (basePlatformServices == null)
     {
         return new DefaultPlatformServices(
             application,
             runtime,
             container,
             accessor,
             libraryManager
         );
     }
     return new DefaultPlatformServices(
             application ?? basePlatformServices.Application,
             runtime ?? basePlatformServices.Runtime,
             container ?? basePlatformServices.AssemblyLoaderContainer,
             accessor ?? basePlatformServices.AssemblyLoadContextAccessor,
             libraryManager ?? basePlatformServices.LibraryManager
         );
 }
Exemple #12
0
        public static void TestEndianOptimization()
        {
            IRuntimeEnvironment currentEnvironment = OS.Current;

            OS.Current = new FakeRuntimeEnvironment(Endian.Reverse);
            try
            {
                if (BitConverter.IsLittleEndian)
                {
                    byte[] actuallyLittleEndianBytes = 0x0102030405060708L.GetBigEndianBytes();
                    Assert.That(actuallyLittleEndianBytes, Is.EqualTo(new byte[] { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 }), "Getting big endian long, thinking we are big endian but in fact are not, will get us little endian bytes.");

                    byte[] actuallyStillLittleEndianBytes = 0x0102030405060708L.GetLittleEndianBytes();
                    Assert.That(actuallyStillLittleEndianBytes, Is.EqualTo(new byte[] { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 }), "Getting little endian long, thinking we are big endian but in fact are not, will still get us little endian.");

                    byte[] actuallyIntStillLittleEndianBytes = 0x01020304.GetLittleEndianBytes();
                    Assert.That(actuallyIntStillLittleEndianBytes, Is.EqualTo(new byte[] { 0x04, 0x03, 0x02, 0x01 }), "Getting little endian int, thinking we are big endian but in fact are not, will still get us little endian.");
                }
                else
                {
                    byte[] actuallyStillBigEndianBytes = 0x0102030405060708L.GetBigEndianBytes();
                    Assert.That(actuallyStillBigEndianBytes, Is.EqualTo(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }), "Getting big endian long, thinking we are little endian but in fact are not, will still get us big endian bytes.");

                    byte[] actuallyBigEndianBytes = 0x0102030405060708L.GetLittleEndianBytes();
                    Assert.That(actuallyBigEndianBytes, Is.EqualTo(new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }), "Getting little endian long, thinking we are big endian but in fact are not, will get us big endian bytes.");

                    byte[] actuallyIntBigEndianBytes = 0x01020304.GetLittleEndianBytes();
                    Assert.That(actuallyIntBigEndianBytes, Is.EqualTo(new byte[] { 0x01, 0x02, 0x03, 0x04 }), "Getting little endian int, thinking we are big endian but in fact are not, will get us big endian bytes.");
                }
            }
            finally
            {
                OS.Current = currentEnvironment;
            }
        }
        /// <summary>
        /// Uses Reflection to verify that the specified member signatures are present in emitted metadata
        /// </summary>
        /// <param name="appDomainHost">Unit test AppDomain host</param>
        /// <param name="expectedSignatures">Baseline signatures - use the Signature() factory method to create instances of SignatureDescription</param>
        internal static void VerifyMemberSignatures(
            IRuntimeEnvironment appDomainHost, params SignatureDescription[] expectedSignatures)
        {
            Assert.NotNull(expectedSignatures);
            Assert.NotEmpty(expectedSignatures);

            var succeeded = true;
            var expected = new List<string>();
            var actual = new List<string>();

            foreach (var signature in expectedSignatures)
            {
                List<string> actualSignatures = null;
                var expectedSignature = signature.ExpectedSignature;

                if (!VerifyMemberSignatureHelper(
                    appDomainHost, signature.FullyQualifiedTypeName, signature.MemberName,
                    ref expectedSignature, out actualSignatures))
                {
                    succeeded = false;
                }

                expected.Add(expectedSignature);
                actual.AddRange(actualSignatures);
            }

            if (!succeeded)
            {
                TriggerSignatureMismatchFailure(expected, actual);
            }
        }
Exemple #14
0
        internal static string GetDefaultPackageDirectory(IRuntimeEnvironment runtimeEnvironment, IEnvironment environment)
        {
            var packageDirectory = environment.GetEnvironmentVariable("NUGET_PACKAGES");

            if (!string.IsNullOrEmpty(packageDirectory))
            {
                return(packageDirectory);
            }

            string basePath;

            if (runtimeEnvironment.OperatingSystemPlatform == Platform.Windows)
            {
                basePath = environment.GetEnvironmentVariable("USERPROFILE");
            }
            else
            {
                basePath = environment.GetEnvironmentVariable("HOME");
            }
            if (string.IsNullOrEmpty(basePath))
            {
                return(null);
            }
            return(Path.Combine(basePath, ".nuget", "packages"));
        }
 public static void Setup()
 {
     _previousEnvironment = OS.Current;
     OS.Current           = new RuntimeEnvironment(null);
     _tempPath            = Path.Combine(Path.GetTempPath(), "Axantum.AxCrypt.Core.Test.TestFileWatcher");
     Directory.CreateDirectory(_tempPath);
 }
        public static byte[] GenerateErrorHtml(bool showDetails, IRuntimeEnvironment runtimeEnvironment, Exception exception)
        {
            // Build the message for each error
            var builder = new StringBuilder();
            var rawExceptionDetails = new StringBuilder();

            if (!showDetails)
            {
                WriteMessage("An error occurred while starting the application.", builder);
            }
            else
            {
                Debug.Assert(exception != null);
                var wasSourceCodeWrittenOntoPage = false;
                var flattenedExceptions = FlattenAndReverseExceptionTree(exception);
                foreach (var innerEx in flattenedExceptions)
                {
                    WriteException(innerEx, builder, ref wasSourceCodeWrittenOntoPage);
                }

                WriteRawExceptionDetails("Show raw exception details", exception.ToString(), rawExceptionDetails);
            }

            // Generate the footer
            var footer = showDetails ? GenerateFooterEncoded(runtimeEnvironment) : null;

            // And generate the full markup
            return Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, _errorPageFormatString, builder, rawExceptionDetails, footer));
        }
        private static string GetWindowsProductVersion(IRuntimeEnvironment self)
        {
            var ver = Version.Parse(self.OperatingSystemVersion);

            if (ver.Major == 6)
            {
                if (ver.Minor == 1)
                {
                    return("7");
                }
                else if (ver.Minor == 2)
                {
                    return("8");
                }
                else if (ver.Minor == 3)
                {
                    return("81");
                }
            }
            else if (ver.Major == 10 && ver.Minor == 0)
            {
                // Not sure if there will be  10.x (where x > 0) or even 11, so let's be defensive.
                return("10");
            }
            return(string.Empty); // Unknown version
        }
 // This is intentionally NOT an extension method because it is only really here for testing
 internal static IEnumerable<string> GetAllRuntimeIdentifiersWithoutOverride(IRuntimeEnvironment env)
 {
     if (!string.Equals(env.OperatingSystem, RuntimeOperatingSystems.Windows, StringComparison.Ordinal))
     {
         yield return GetRuntimeIdentifierWithoutOverride(env);
     }
     else
     {
         var arch = env.RuntimeArchitecture.ToLowerInvariant();
         if (env.OperatingSystemVersion.Equals("6.1", StringComparison.Ordinal))
         {
             yield return "win7-" + arch;
         }
         else if (env.OperatingSystemVersion.Equals("6.2", StringComparison.Ordinal))
         {
             yield return "win8-" + arch;
             yield return "win7-" + arch;
         }
         else if (env.OperatingSystemVersion.Equals("6.3", StringComparison.Ordinal))
         {
             yield return "win81-" + arch;
             yield return "win8-" + arch;
             yield return "win7-" + arch;
         }
         else if (env.OperatingSystemVersion.Equals("10.0", StringComparison.Ordinal))
         {
             yield return "win10-" + arch;
             yield return "win81-" + arch;
             yield return "win8-" + arch;
             yield return "win7-" + arch;
         }
     }
 }
 public static string GetRuntimeIdentifier(this IRuntimeEnvironment self)
 {
     return
         (Environment.GetEnvironmentVariable(OverrideEnvironmentVariableName) ??
          Environment.GetEnvironmentVariable(LegacyOverrideEnvironmentVariableName) ??
          (GetRIDOS(self) + GetRIDVersion(self) + GetRIDArch(self)));
 }
    public static void Register(CommandLineApplication cmdApp, IApplicationEnvironment appEnv, IRuntimeEnvironment runtimeEnv)
    {
      if (runtimeEnv.OperatingSystem == "Windows")
      {
        _dnuPath = new Lazy<string>(FindDnuWindows);
      }
      else
      {
        _dnuPath = new Lazy<string>(FindDnuNix);
      }

      cmdApp.Command("depresolve", c => {
        c.Description = "Perform a combination of parsing, static analysis, semantic analysis, and type inference";

        c.HelpOption("-?|-h|--help");

        c.OnExecute(async () => {
          //System.Diagnostics.Debugger.Launch();
          var jsonIn = await Console.In.ReadToEndAsync();
          var sourceUnit = JsonConvert.DeserializeObject<SourceUnit>(jsonIn);

          var dir = Path.Combine(Directory.GetCurrentDirectory(), sourceUnit.Dir);
          var deps = await DepResolve(dir);

          var result = new List<Resolution>();
          foreach(var dep in deps)
          {
            result.Add(Resolution.FromLibrary(dep));
          }

          Console.WriteLine(JsonConvert.SerializeObject(result, Formatting.Indented));
          return 0;
        });
      });
    }
Exemple #21
0
 public static IEnumerable<string> GetAllCandidateRuntimeIdentifiers(this IRuntimeEnvironment env)
 {
     if (env.OperatingSystemPlatform != Platform.Windows)
     {
         yield return env.GetRuntimeIdentifier();
     }
     else
     {
         var arch = env.RuntimeArchitecture.ToLowerInvariant();
         if (env.OperatingSystemVersion.StartsWith("6.1", StringComparison.Ordinal))
         {
             yield return "win7-" + arch;
         }
         else if (env.OperatingSystemVersion.StartsWith("6.2", StringComparison.Ordinal))
         {
             yield return "win8-" + arch;
             yield return "win7-" + arch;
         }
         else if (env.OperatingSystemVersion.StartsWith("6.3", StringComparison.Ordinal))
         {
             yield return "win81-" + arch;
             yield return "win8-" + arch;
             yield return "win7-" + arch;
         }
         else if (env.OperatingSystemVersion.StartsWith("10.0", StringComparison.Ordinal))
         {
             yield return "win10-" + arch;
             yield return "win81-" + arch;
             yield return "win8-" + arch;
             yield return "win7-" + arch;
         }
     }
 }
Exemple #22
0
 public Startup(IHostingEnvironment hostingEnvironment, IApplicationEnvironment applicationEnvironment, IRuntimeEnvironment runtimeEnvironment)
 {
   log("Startup");
   log("Platform = " + runtimeEnvironment.OperatingSystem);
   string PrjFolder = "";
   // Set up configuration sources.
   var builder = new ConfigurationBuilder()
       .AddJsonFile("appsettings.json")
       .AddEnvironmentVariables();
   Configuration = builder.Build();
   try
   {
     PrjFolder = Directory.GetParent(hostingEnvironment.WebRootPath).FullName;
   }
   catch
   {
     // bei migrations klappts nicht mit der Ermittlung des Pfads aus env
     PrjFolder = Directory.GetCurrentDirectory();
     log("Could't get project folder from HostingEnvironment, using CurDir: " + PrjFolder);
   }
   _DataFolder = Path.Combine(PrjFolder, "data");
   log("DataFolder = " + _DataFolder);
   // Ordner überprüfen
   try
   {
     string AcessTestFileName = Path.Combine(_DataFolder, "_accestest.accestest");
     File.Create(AcessTestFileName);
   }
   catch (Exception E)
   {
     log("Could't write in DataFolder: " + E.Message);
   }
 }
        internal static RSA GenerateKey(IRuntimeEnvironment environment)
        {
            if (string.Equals(environment.OperatingSystem, "Windows", StringComparison.OrdinalIgnoreCase))
            {
#if DNXCORE50
                // On CoreCLR, use RSACng.
                return(new RSACng(2048));
#else
                // On desktop CLR, use RSACryptoServiceProvider.
                return(new RSACryptoServiceProvider(2048));
#endif
            }

            // When the runtime is identified as Mono, use RSACryptoServiceProvider, independently of the operating system.
            if (string.Equals(environment.RuntimeType, "Mono", StringComparison.OrdinalIgnoreCase))
            {
                return(new RSACryptoServiceProvider(2048));
            }

#if DNXCORE50
            // On Linux and Darwin, use RSAOpenSsl when running on CoreCLR.
            if (string.Equals(environment.OperatingSystem, "Linux", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(environment.OperatingSystem, "Darwin", StringComparison.OrdinalIgnoreCase))
            {
                return(new RSAOpenSsl(2048));
            }
#endif

            // If no appropriate implementation can be found, throw an exception.
            throw new PlatformNotSupportedException("No RSA implementation compatible with your configuration can be found.");
        }
        /// <summary>
        /// Uses Reflection to verify that the specified member signatures are present in emitted metadata
        /// </summary>
        /// <param name="appDomainHost">Unit test AppDomain host</param>
        /// <param name="expectedSignatures">Baseline signatures - use the Signature() factory method to create instances of SignatureDescription</param>
        internal static void VerifyMemberSignatures(
            IRuntimeEnvironment appDomainHost, params SignatureDescription[] expectedSignatures)
        {
            Assert.NotNull(expectedSignatures);
            Assert.NotEmpty(expectedSignatures);

            var succeeded = true;
            var expected  = new List <string>();
            var actual    = new List <string>();

            foreach (var signature in expectedSignatures)
            {
                var expectedSignature = signature.ExpectedSignature;

                if (!VerifyMemberSignatureHelper(
                        appDomainHost, signature.FullyQualifiedTypeName, signature.MemberName,
                        ref expectedSignature, out var actualSignatures))
                {
                    succeeded = false;
                }

                expected.Add(expectedSignature);
                actual.AddRange(actualSignatures);
            }

            if (!succeeded)
            {
                TriggerSignatureMismatchFailure(expected, actual);
            }
        }
Exemple #25
0
        public Program(IRuntimeEnvironment runtimeEnvironment)
        {
            _loggerFactory = new LoggerFactory();

            var commandProvider = new CommandOutputProvider(runtimeEnvironment);
            _loggerFactory.AddProvider(commandProvider);
        }
Exemple #26
0
 public Program(IRuntimeEnvironment runtimeEnv)
 {
     var loggerFactory = new LoggerFactory();
     CommandOutputProvider = new CommandOutputProvider(runtimeEnv);
     loggerFactory.AddProvider(CommandOutputProvider);
     Logger = loggerFactory.CreateLogger<Program>();
 }
Exemple #27
0
 public static PlatformServices Create(
     PlatformServices basePlatformServices,
     IApplicationEnvironment application   = null,
     IRuntimeEnvironment runtime           = null,
     IAssemblyLoaderContainer container    = null,
     IAssemblyLoadContextAccessor accessor = null,
     ILibraryManager libraryManager        = null)
 {
     if (basePlatformServices == null)
     {
         return(new DefaultPlatformServices(
                    application,
                    runtime,
                    container,
                    accessor,
                    libraryManager
                    ));
     }
     return(new DefaultPlatformServices(
                application ?? basePlatformServices.Application,
                runtime ?? basePlatformServices.Runtime,
                container ?? basePlatformServices.AssemblyLoaderContainer,
                accessor ?? basePlatformServices.AssemblyLoadContextAccessor,
                libraryManager ?? basePlatformServices.LibraryManager
                ));
 }
 public InstrumentStartup(TracingDiagnosticProcessorObserver observer, IEnumerable <IExecutionService> services, ILoggerFactory loggerFactory, IRuntimeEnvironment runtimeEnvironment)
 {
     _observer           = observer;
     _services           = services;
     _logger             = loggerFactory.CreateLogger(typeof(InstrumentStartup));
     _runtimeEnvironment = runtimeEnvironment;
 }
Exemple #29
0
 public CompilationEngineContext(IApplicationEnvironment applicationEnvironment,
                                 IRuntimeEnvironment runtimeEnvironment,
                                 IAssemblyLoadContext defaultLoadContext,
                                 CompilationCache cache) :
     this(applicationEnvironment, runtimeEnvironment, defaultLoadContext, cache, NoopWatcher.Instance)
 {
 }
Exemple #30
0
 // to enable unit testing
 internal OSSkipConditionAttribute(
     OperatingSystems operatingSystem, IRuntimeEnvironment runtimeEnvironment, params string[] versions)
 {
     _excludedOperatingSystem = operatingSystem;
     _excludedVersions        = versions ?? Enumerable.Empty <string>();
     _runtimeEnvironment      = runtimeEnvironment;
 }
Exemple #31
0
        public static string GetRuntimeOsName(this IRuntimeEnvironment env)
        {
            string os  = env.OperatingSystem ?? string.Empty;
            string ver = env.OperatingSystemVersion ?? string.Empty;

            if (string.Equals(os, RuntimeOperatingSystems.Windows, StringComparison.Ordinal))
            {
                os = "win";

                if (env.OperatingSystemVersion.Equals("6.1", StringComparison.Ordinal))
                {
                    ver = "7";
                }
                else if (env.OperatingSystemVersion.Equals("6.2", StringComparison.Ordinal))
                {
                    ver = "8";
                }
                else if (env.OperatingSystemVersion.Equals("6.3", StringComparison.Ordinal))
                {
                    ver = "81";
                }
                else if (env.OperatingSystemVersion.Equals("10.0", StringComparison.Ordinal))
                {
                    ver = "10";
                }

                return(os + ver);
            }
            else if (string.Equals(os, RuntimeOperatingSystems.Linux, StringComparison.Ordinal))
            {
                // Generate the distro-based name
                var split = ver.Split(new[] { ' ' }, 2);
                if (split.Length == 2)
                {
                    os  = split[0].ToLowerInvariant();
                    ver = split[1].ToLowerInvariant();
                }
                else
                {
                    os  = "linux";
                    ver = string.Empty;
                }
            }
            else if (string.Equals(os, RuntimeOperatingSystems.Darwin, StringComparison.Ordinal))
            {
                os = "osx";
            }
            else
            {
                // Just use the lower-case full name of the OS as the RID OS and tack on the version number
                os = os.ToLowerInvariant();
            }

            if (!string.IsNullOrEmpty(ver))
            {
                os = os + "." + ver;
            }
            return(os);
        }
        /// <summary>
        /// Uses Reflection to verify that the specified member signature is present in emitted metadata
        /// </summary>
        /// <param name="appDomainHost">Unit test AppDomain host</param>
        /// <param name="fullyQualifiedTypeName">
        /// Fully qualified type name for member
        /// Names must be in format recognized by reflection
        /// e.g. MyType&lt;T&gt;.MyNestedType&lt;T, U&gt; => MyType`1+MyNestedType`2
        /// </param>
        /// <param name="memberName">
        /// Name of member on specified type whose signature needs to be verified
        /// Names must be in format recognized by reflection
        /// e.g. For explicitly implemented member - I1&lt;string&gt;.Method => I1&lt;System.String&gt;.Method
        /// </param>
        /// <param name="expectedSignature">
        /// Baseline string for signature of specified member
        /// Skip this argument to get an error message that shows all available signatures for specified member
        /// This argument is passed by reference and it will be updated with a formatted form of the baseline signature for error reporting purposes
        /// </param>
        /// <param name="actualSignatures">List of found signatures matching member name</param>
        /// <returns>True if a matching member signature was found, false otherwise</returns>
        private static bool VerifyMemberSignatureHelper(
            IRuntimeEnvironment appDomainHost, string fullyQualifiedTypeName, string memberName,
            ref string expectedSignature, out List<string> actualSignatures)
        {
            Assert.False(string.IsNullOrWhiteSpace(fullyQualifiedTypeName), "'fullyQualifiedTypeName' can't be null or empty");
            Assert.False(string.IsNullOrWhiteSpace(memberName), "'memberName' can't be null or empty");

            var retVal = true; actualSignatures = new List<string>();
            var signatures = appDomainHost.GetMemberSignaturesFromMetadata(fullyQualifiedTypeName, memberName);
            var signatureAssertText = "Signature(\"" + fullyQualifiedTypeName + "\", \"" + memberName + "\", \"{0}\"),";

            if (!string.IsNullOrWhiteSpace(expectedSignature))
            {
                expectedSignature = expectedSignature.Replace("\"", "\\\"");
            }
            expectedSignature = string.Format(signatureAssertText, expectedSignature);

            if (signatures.Count > 1)
            {
                var found = false;
                foreach (var signature in signatures)
                {
                    var actualSignature = signature.Replace("\"", "\\\"");
                    actualSignature = string.Format(signatureAssertText, actualSignature);

                    if (actualSignature == expectedSignature)
                    {
                        actualSignatures.Clear();
                        actualSignatures.Add(actualSignature);
                        found = true; break;
                    }
                    else
                    {
                        actualSignatures.Add(actualSignature);
                    }
                }
                if (!found)
                {
                    retVal = false;
                }
            }
            else if (signatures.Count == 1)
            {
                var actualSignature = signatures.First().Replace("\"", "\\\"");
                actualSignature = string.Format(signatureAssertText, actualSignature);
                actualSignatures.Add(actualSignature);

                if (expectedSignature != actualSignature)
                {
                    retVal = false;
                }
            }
            else
            {
                retVal = false;
            }

            return retVal;
        }
        public static byte[] GenerateErrorHtml(bool showDetails, IRuntimeEnvironment runtimeEnvironment, params object[] errorDetails)
        {
            if (!showDetails)
            {
                errorDetails = new[] { "An error occurred while starting the application." };
            }

            // Build the message for each error
            var wasSourceCodeWrittenOntoPage = false;
            var builder = new StringBuilder();
            var rawExceptionDetails = new StringBuilder();

            foreach (object error in errorDetails ?? new object[0])
            {
                var ex = error as Exception;
                if (ex == null && error is ExceptionDispatchInfo)
                {
                    ex = ((ExceptionDispatchInfo)error).SourceException;
                }

                if (ex != null)
                {
                    var flattenedExceptions = FlattenAndReverseExceptionTree(ex);

                    var compilationException = flattenedExceptions.OfType<ICompilationException>()
                                                                  .FirstOrDefault();
                    if (compilationException != null)
                    {
                        WriteException(compilationException, builder, ref wasSourceCodeWrittenOntoPage);

                        var compilationErrorMessages = compilationException.CompilationFailures
                            .SelectMany(f => f.Messages.Select(m => m.FormattedMessage))
                            .Take(MaxCompilationErrorsToShow);

                        WriteRawExceptionDetails("Show raw compilation error details", compilationErrorMessages, rawExceptionDetails);
                    }
                    else
                    {
                        foreach (var innerEx in flattenedExceptions)
                        {
                            WriteException(innerEx, builder, ref wasSourceCodeWrittenOntoPage);
                        }

                        WriteRawExceptionDetails("Show raw exception details", new[] { ex.ToString() }, rawExceptionDetails);
                    }
                }
                else
                {
                    var message = Convert.ToString(error, CultureInfo.InvariantCulture);
                    WriteMessage(message, builder);
                }
            }

            // Generate the footer
            var footer = showDetails ? GenerateFooterEncoded(runtimeEnvironment) : null;

            // And generate the full markup
            return Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, _errorPageFormatString, builder, rawExceptionDetails, footer));
        }
        public static byte[] GenerateErrorHtml(bool showDetails, IRuntimeEnvironment runtimeEnvironment, params object[] errorDetails)
        {
            if (!showDetails)
            {
                errorDetails = new[] { "An error occurred while starting the application." };
            }

            // Build the message for each error
            var wasSourceCodeWrittenOntoPage = false;
            var builder             = new StringBuilder();
            var rawExceptionDetails = new StringBuilder();

            foreach (object error in errorDetails ?? new object[0])
            {
                var ex = error as Exception;
                if (ex == null && error is ExceptionDispatchInfo)
                {
                    ex = ((ExceptionDispatchInfo)error).SourceException;
                }

                if (ex != null)
                {
                    var flattenedExceptions = FlattenAndReverseExceptionTree(ex);

                    var compilationException = flattenedExceptions.OfType <ICompilationException>()
                                               .FirstOrDefault();
                    if (compilationException != null)
                    {
                        WriteException(compilationException, builder, ref wasSourceCodeWrittenOntoPage);

                        var compilationErrorMessages = compilationException.CompilationFailures
                                                       .SelectMany(f => f.Messages.Select(m => m.FormattedMessage))
                                                       .Take(MaxCompilationErrorsToShow);

                        WriteRawExceptionDetails("Show raw compilation error details", compilationErrorMessages, rawExceptionDetails);
                    }
                    else
                    {
                        foreach (var innerEx in flattenedExceptions)
                        {
                            WriteException(innerEx, builder, ref wasSourceCodeWrittenOntoPage);
                        }

                        WriteRawExceptionDetails("Show raw exception details", new[] { ex.ToString() }, rawExceptionDetails);
                    }
                }
                else
                {
                    var message = Convert.ToString(error, CultureInfo.InvariantCulture);
                    WriteMessage(message, builder);
                }
            }

            // Generate the footer
            var footer = showDetails ? GenerateFooterEncoded(runtimeEnvironment) : null;

            // And generate the full markup
            return(Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, _errorPageFormatString, builder, rawExceptionDetails, footer)));
        }
        /// <summary>
        /// Uses Reflection to verify that the specified member signature is present in emitted metadata
        /// </summary>
        /// <param name="appDomainHost">Unit test AppDomain host</param>
        /// <param name="fullyQualifiedTypeName">
        /// Fully qualified type name for member
        /// Names must be in format recognized by reflection
        /// e.g. MyType&lt;T&gt;.MyNestedType&lt;T, U&gt; => MyType`1+MyNestedType`2
        /// </param>
        /// <param name="memberName">
        /// Name of member on specified type whose signature needs to be verified
        /// Names must be in format recognized by reflection
        /// e.g. For explicitly implemented member - I1&lt;string&gt;.Method => I1&lt;System.String&gt;.Method
        /// </param>
        /// <param name="expectedSignature">
        /// Baseline string for signature of specified member
        /// Skip this argument to get an error message that shows all available signatures for specified member
        /// This argument is passed by reference and it will be updated with a formatted form of the baseline signature for error reporting purposes
        /// </param>
        /// <param name="actualSignatures">List of found signatures matching member name</param>
        /// <returns>True if a matching member signature was found, false otherwise</returns>
        private static bool VerifyMemberSignatureHelper(
            IRuntimeEnvironment appDomainHost, string fullyQualifiedTypeName, string memberName,
            ref string expectedSignature, out List <string> actualSignatures)
        {
            Assert.False(string.IsNullOrWhiteSpace(fullyQualifiedTypeName), "'fullyQualifiedTypeName' can't be null or empty");
            Assert.False(string.IsNullOrWhiteSpace(memberName), "'memberName' can't be null or empty");

            var retVal              = true; actualSignatures = new List <string>();
            var signatures          = appDomainHost.GetMemberSignaturesFromMetadata(fullyQualifiedTypeName, memberName);
            var signatureAssertText = "Signature(\"" + fullyQualifiedTypeName + "\", \"" + memberName + "\", \"{0}\"),";

            if (!string.IsNullOrWhiteSpace(expectedSignature))
            {
                expectedSignature = expectedSignature.Replace("\"", "\\\"");
            }
            expectedSignature = string.Format(signatureAssertText, expectedSignature);

            if (signatures.Count > 1)
            {
                var found = false;
                foreach (var signature in signatures)
                {
                    var actualSignature = signature.Replace("\"", "\\\"");
                    actualSignature = string.Format(signatureAssertText, actualSignature);

                    if (actualSignature == expectedSignature)
                    {
                        actualSignatures.Clear();
                        actualSignatures.Add(actualSignature);
                        found = true; break;
                    }
                    else
                    {
                        actualSignatures.Add(actualSignature);
                    }
                }
                if (!found)
                {
                    retVal = false;
                }
            }
            else if (signatures.Count == 1)
            {
                var actualSignature = signatures.First().Replace("\"", "\\\"");
                actualSignature = string.Format(signatureAssertText, actualSignature);
                actualSignatures.Add(actualSignature);

                if (expectedSignature != actualSignature)
                {
                    retVal = false;
                }
            }
            else
            {
                retVal = false;
            }

            return(retVal);
        }
Exemple #36
0
 public PingService(IConfigAccessor configAccessor, IPingCaller pingCaller,
                    IRuntimeEnvironment runtimeEnvironment,
                    ILoggerFactory loggerFactory) : base(
         runtimeEnvironment, loggerFactory)
 {
     _pingCaller      = pingCaller;
     _transportConfig = configAccessor.Get <TransportConfig>();
 }
Exemple #37
0
        public static string GetRuntimeIdentifier(this IRuntimeEnvironment env)
        {
            var overrideRid = GetOverrideRid();

            return(string.IsNullOrEmpty(overrideRid) ?
                   GetRuntimeIdentifierWithoutOverride(env) :
                   overrideRid);
        }
 private static string GetRIDArch(IRuntimeEnvironment self)
 {
     if (!string.IsNullOrEmpty(self.RuntimeArchitecture))
     {
         return($"-{self.RuntimeArchitecture.ToLowerInvariant()}");
     }
     return(string.Empty);
 }
Exemple #39
0
        public SimpleCountSamplingInterceptor(IConfigAccessor configAccessor, IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory) :
            base(runtimeEnvironment, loggerFactory)
        {
            var samplingConfig = configAccessor.Get <SamplingConfig>();

            _samplePer3Secs = samplingConfig.SamplePer3Secs;
            _sample_on      = _samplePer3Secs > -1;
        }
Exemple #40
0
 public RegisterService(IConfigAccessor configAccessor, IServiceRegister serviceRegister,
                        IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory) : base(runtimeEnvironment,
                                                                                                     loggerFactory)
 {
     _serviceRegister = serviceRegister;
     _config          = configAccessor.Get <InstrumentConfig>();
     _transportConfig = configAccessor.Get <TransportConfig>();
 }
Exemple #41
0
 public SegmentReportService(IConfigAccessor configAccessor, ISegmentDispatcher dispatcher,
                             IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
     : base(runtimeEnvironment, loggerFactory)
 {
     _dispatcher = dispatcher;
     _config     = configAccessor.Get <TransportConfig>();
     Period      = TimeSpan.FromMilliseconds(_config.Interval);
 }
 public static void Update(this RuntimeEnvironment source, IRuntimeEnvironment environment)
 {
     source.OperatingSystem = environment.OperatingSystem;
     source.OperatingSystemVersion = environment.OperatingSystemVersion;
     source.RuntimeArchitecture = environment.RuntimeArchitecture;
     source.RuntimeType = environment.RuntimeType;
     source.RuntimeVersion = environment.RuntimeVersion;
 }
Exemple #43
0
        public static IEnumerable <string> GetAllRuntimeIdentifiers(this IRuntimeEnvironment env)
        {
            var overrideRid = GetOverrideRid();

            return(string.IsNullOrEmpty(overrideRid) ?
                   GetAllRuntimeIdentifiersWithoutOverride(env) :
                   new [] { overrideRid });
        }
 public CLRStatsReporter(ConnectionManager connectionManager, ILoggerFactory loggerFactory,
                         IConfigAccessor configAccessor, IRuntimeEnvironment runtimeEnvironment)
 {
     _connectionManager  = connectionManager;
     _logger             = loggerFactory.CreateLogger(NLog.LogManager.GetCurrentClassLogger());
     _config             = configAccessor.Get <GrpcConfig>();
     _runtimeEnvironment = runtimeEnvironment;
 }
Exemple #45
0
 public SegmentReportService(IOptions <SkyApmConfig> configAccessor, ISegmentDispatcher dispatcher,
                             IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
     : base(runtimeEnvironment, loggerFactory)
 {
     _dispatcher = dispatcher;
     _config     = configAccessor.Value;
     Period      = TimeSpan.FromMilliseconds(_config.Transport.Interval);
 }
 public ServiceDiscoveryV5Service(IConfigAccessor configAccessor, ISkyApmClientV5 skyApmClient,
                                  IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
     : base(runtimeEnvironment, loggerFactory)
 {
     _config           = configAccessor.Get <InstrumentConfig>();
     _transportConfig  = configAccessor.Get <TransportConfig>();
     this.skyApmClient = skyApmClient;
 }
Exemple #47
0
        public Program(IRuntimeEnvironment runtimeEnv)
        {
            var loggerFactory = new LoggerFactory();

            CommandOutputProvider = new CommandOutputProvider(runtimeEnv);
            loggerFactory.AddProvider(CommandOutputProvider);
            Logger = loggerFactory.CreateLogger <Program>();
        }
Exemple #48
0
        public Startup(IApplicationEnvironment env, IRuntimeEnvironment runtimeEnvironment)
        {
            // Setup configuration sources.
            var builder = new ConfigurationBuilder(env.ApplicationBasePath)
                .AddJsonFile("config.json");

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }
        public EnvironmentController(
            ILoggerFactory loggerFactory,
            IRuntimeEnvironment runtimeEnv)
            : base(loggerFactory.CreateLogger(nameof(EnvironmentController)))
        {
            this.runtimeEnv = runtimeEnv;

            this.hostname = Environment.MachineName;
        }
Exemple #50
0
        //  private readonly Platform _platform;
        public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv, IRuntimeEnvironment runtimeEnvironment)
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(appEnv.ApplicationBasePath)
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();

            Configuration = builder.Build();
        }
Exemple #51
0
 public DefaultHost(DefaultHostOptions options,
                    IAssemblyLoadContextAccessor loadContextAccessor)
 {
     _projectDirectory = Path.GetFullPath(options.ApplicationBaseDirectory);
     _targetFramework = options.TargetFramework;
     _loadContextAccessor = loadContextAccessor;
     _runtimeEnvironment = PlatformServices.Default.Runtime;
     _serviceProvider = new ServiceProvider();
     Initialize(options, loadContextAccessor);
 }
 internal static string Resolve(IEnvironment envirnment, IFileSystem fileSystem, IRuntimeEnvironment runtimeEnvironment)
 {
     var path = envirnment.GetEnvironmentVariable(DotNetReferenceAssembliesPathEnv);
     if (!string.IsNullOrEmpty(path))
     {
         return path;
     }
     
     return GetDefaultDotNetReferenceAssembliesPath(fileSystem, runtimeEnvironment);
 }
        public Startup(IHostingEnvironment env, IRuntimeEnvironment runtime)
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.ColoredConsole()
                .CreateLogger();

            Configuration = new ConfigurationBuilder(".")
                .AddJsonFile("config.json")
                .Build();
        }
Exemple #54
0
        public TestLogger(IRuntimeEnvironment runtimeEnv, bool debug = false)
        {
            var commandOutputProvider = new CommandOutputProvider(runtimeEnv);
            if (debug)
            {
                commandOutputProvider.LogLevel = LogLevel.Debug;
            }

            _commandOutputLogger = (CommandOutputLogger)commandOutputProvider.CreateLogger("");
        }
 public LoggerFactory(IRuntimeEnvironment runtimeEnvironment,
     IApplicationResourceFactory applicationResourceFactory,
     ILoggerExtension loggerExtension,
     ICorrelationIdProvider correlationIdProvider)
 {
     _runtimeEnvironment = runtimeEnvironment;
     _applicationResourceFactory = applicationResourceFactory;
     _loggerExtension = loggerExtension;
     _correlationIdProvider = correlationIdProvider;
 }
 public DnxHostPlatformServices(HostApplicationEnvironment applicationEnvironment, 
                                IRuntimeEnvironment runtimeEnvironment, 
                                LoaderContainer container, 
                                LoadContextAccessor accessor)
 {
     Application = applicationEnvironment;
     Runtime = runtimeEnvironment;
     AssemblyLoaderContainer = container;
     AssemblyLoadContextAccessor = accessor;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RuntimeInfoMiddleware"/> class
 /// </summary>
 /// <param name="next"></param>
 /// <param name="options"></param>
 public RuntimeInfoMiddleware(
     [NotNull] RequestDelegate next,
     [NotNull] RuntimeInfoPageOptions options,
     [NotNull] ILibraryManager libraryManager,
     [NotNull] IRuntimeEnvironment runtimeEnvironment)
 {
     _next = next;
     _options = options;
     _libraryManager = libraryManager;
     _runtimeEnvironment = runtimeEnvironment;
 }
        public StartupOpenIdConnectTesting(IApplicationEnvironment env, IRuntimeEnvironment runtimeEnvironment)
        {
            //Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, 
            //then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely.
            var builder = new ConfigurationBuilder(env.ApplicationBasePath)
                        .AddJsonFile("config.json")
                        .AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values.

            Configuration = builder.Build();
            _runtimeEnvironment = runtimeEnvironment;
        }
        public StartupSocialTesting(IApplicationEnvironment appEnvironment, IRuntimeEnvironment runtimeEnvironment)
        {
            //Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, 
            //then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely.
            var builder = new ConfigurationBuilder(appEnvironment.ApplicationBasePath)
                        .AddJsonFile("config.json")
                        .AddEnvironmentVariables() //All environment variables in the process's context flow in as configuration values.
                        .AddJsonFile("configoverride.json", optional: true); // Used to override some configuration parameters that cannot be overridden by environment.

            Configuration = builder.Build();
            _runtimeEnvironment = runtimeEnvironment;
        }
 public ExtensionAssemblyLoader(
     IApplicationEnvironment applicationEnvironment,
     //ICache cache,
     IAssemblyLoadContextAccessor assemblyLoadContextAccessor,
     IRuntimeEnvironment runtimeEnvironment,
     IOrchardLibraryManager libraryManager)
 {
     _applicationEnvironment = applicationEnvironment;
     //_cache = cache;
     _assemblyLoadContextAccessor = assemblyLoadContextAccessor;
     _runtimeEnvironment = runtimeEnvironment;
     _libraryManager = libraryManager;
 }