System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform)

Here are the examples of the csharp api System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1629 Examples 7

19 View Source File : XInput.cs
License : MIT License
Project Creator : amerkoleci

private static bool IsUAP()
        {
            // This actually checks whether code is running in a modern app. 
            // Currently this is the only situation where we run in app container.
            // If we want to distinguish the two cases in future,
            // EnvironmentHelpers.IsAppContainerProcess in desktop code shows how to check for the AC token.
            if (s_isInAppContainer != -1)
                return s_isInAppContainer == 1;

            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || IsWindows7)
            {
                s_isInAppContainer = 0;
                return false;
            }

            byte[] buffer = Array.Empty<byte>();
            uint bufferSize = 0;
            try
            {
                int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer);
                switch (result)
                {
                    case 15703: // APPMODEL_ERROR_NO_APPLICATION
                        s_isInAppContainer = 0;
                        break;
                    case 0:     // ERROR_SUCCESS
                    case 122:   // ERROR_INSUFFICIENT_BUFFER
                                // Success is actually insufficent buffer as we're really only looking for
                                // not NO_APPLICATION and we're not actually giving a buffer here. The
                                // API will always return NO_APPLICATION if we're not running under a
                                // WinRT process, no matter what size the buffer is.
                        s_isInAppContainer = 1;
                        break;
                    default:
                        throw new InvalidOperationException($"Failed to get AppId, result was {result}.");
                }
            }
            catch (Exception e)
            {
                // We could catch this here, being friendly with older portable surface area should we
                // desire to use this method elsewhere.
                if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal))
                {
                    // API doesn't exist, likely pre Win8
                    s_isInAppContainer = 0;
                }
                else
                {
                    throw;
                }
            }

            return s_isInAppContainer == 1;
        }

19 View Source File : FluentAvaloniaTheme.cs
License : MIT License
Project Creator : amwx

private void GenerateCustomAccentColor(Color? c)
		{
			if (!c.HasValue)
			{
				if (GetUserAccentColor && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
				{
					(_loaded[0] as Styles).Resources["SystemAccentColor"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccent");
					(_loaded[0] as Styles).Resources["SystemAccentColorLight1"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentLight1");
					(_loaded[0] as Styles).Resources["SystemAccentColorLight2"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentLight2");
					(_loaded[0] as Styles).Resources["SystemAccentColorLight3"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentLight3");
					(_loaded[0] as Styles).Resources["SystemAccentColorDark1"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentDark1");
					(_loaded[0] as Styles).Resources["SystemAccentColorDark2"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentDark2");
					(_loaded[0] as Styles).Resources["SystemAccentColorDark3"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentDark3");
				}
				else
				{
					_loaded[0] = (IStyle)AvaloniaXamlLoader.Load(new Uri($"avares://FluentAvalonia/Styling/StylesV2/AccentColors.axaml", UriKind.Absolute), _baseUri);
				}

				return;
			}
			else
			{
				(_loaded[0] as Styles).Resources["SystemAccentColor"] = c.Value;

				Color2 col = c.Value;

				(_loaded[0] as Styles).Resources["SystemAccentColorLight1"] = (Color)col.LightenPercent(0.15f);
				(_loaded[0] as Styles).Resources["SystemAccentColorLight2"] = (Color)col.LightenPercent(0.3f);
				(_loaded[0] as Styles).Resources["SystemAccentColorLight3"] = (Color)col.LightenPercent(0.45f);
				(_loaded[0] as Styles).Resources["SystemAccentColorDark1"] = (Color)col.LightenPercent(-0.15f);
				(_loaded[0] as Styles).Resources["SystemAccentColorDark2"] = (Color)col.LightenPercent(-0.30f);
				(_loaded[0] as Styles).Resources["SystemAccentColorDark3"] = (Color)col.LightenPercent(-0.45f);
			}	
		}

19 View Source File : PopupNotificationProvider.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public static PopupNotificationProvider CreatePlatformNotificationProvider()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return new PopupNotificationProvider(new Win10.Win10ToastNotificationsProvider());
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                // TODO
                return null;
            }

            return null;
        }

19 View Source File : LibraryLoader.cs
License : MIT License
Project Creator : amerkoleci

private static IntPtr GetSymbol(IntPtr library, string symbolName)
        {
            if (string.IsNullOrEmpty(symbolName))
                throw new ArgumentNullException(nameof(symbolName));

            IntPtr handle;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                handle = Win32.GetProcAddress(library, symbolName);
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                handle = Linux.dlsym(library, symbolName);
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                handle = Mac.dlsym(library, symbolName);
            else
                throw new PlatformNotSupportedException($"Current platform is unknown, unable to load symbol '{symbolName}' from library {library}.");

            return handle;
        }

19 View Source File : AppSettingsExtensions.cs
License : MIT License
Project Creator : aliencube

public static bool IsWindows() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

19 View Source File : ValidationHandler.cs
License : MIT License
Project Creator : Akaion

internal static void ValidateOperatingSystem()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                throw new PlatformNotSupportedException("This library is intended for Windows use only and will not work on Linux");
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                throw new PlatformNotSupportedException("This library is intended for Windows use only and will not work on OSX");
            }
        }

19 View Source File : MainWindowViewModel.cs
License : MIT License
Project Creator : amwx

public void SetLightTheme()
        {
			// Only line needed to switch to Light Theme
			AvaloniaLocator.Current.GetService<FluentAvaloniaTheme>().RequestedTheme = "Light";

			// Optional, if you want the native win32 replacedlebar to switch themes too (1809+ only)
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && 
				App.Current.ApplicationLifetime is IClreplacedicDesktopStyleApplicationLifetime cdl)
			{
				AvaloniaLocator.Current.GetService<FluentAvaloniaTheme>()?.ForceNativereplacedleBarToTheme(cdl.MainWindow);
			}

			// Ignore these, these are for the SampleApp only
			App.Current.Resources["ControlExampleStrokeColor"] = new SolidColorBrush(Color.Parse("#0F000000"));
			App.Current.Resources["ControlExampleBackgroundFill"] = new SolidColorBrush(Color.Parse("#F3F3F3"));
			App.Current.Resources["ControlExampleBackgroundFill2"] = new SolidColorBrush(Color.Parse("#F9F9F9"));
		}

19 View Source File : Command.cs
License : Apache License 2.0
Project Creator : adamralph

public static async Task<Result> ReadAsync(
            string name,
            string? args = null,
            string? workingDirectory = null,
            string? windowsName = null,
            string? windowsArgs = null,
            Action<IDictionary<string, string>>? configureEnvironment = null,
            Encoding? encoding = null,
            Func<int, bool>? handleExitCode = null,
            string? standardInput = null,
            CancellationToken cancellationToken = default)
        {
            Validate(name);

            using var process = new Process();

            process.StartInfo = ProcessStartInfo.Create(
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsName ?? name : name,
                (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsArgs ?? args : args) ?? "",
                workingDirectory ?? "",
                true,
                configureEnvironment ?? defaultAction,
                true,
                encoding);

            var runProcess = process.RunAsync(true, defaultEchoPrefix, cancellationToken);

            Task<string> readOutput;
            Task<string> readError;

            try
            {
                await process.StandardInput.WriteAsync(standardInput).ConfigureAwait(false);
                process.StandardInput.Close();

                readOutput = process.StandardOutput.ReadToEndAsync();
                readError = process.StandardError.ReadToEndAsync();
            }
            catch (Exception)
            {
                await runProcess.ConfigureAwait(false);
                throw;
            }

            await Task.WhenAll(runProcess, readOutput, readError).ConfigureAwait(false);

#pragma warning disable CA1849 // Call async methods when in an async method
            var output = readOutput.Result;
            var error = readError.Result;
#pragma warning restore CA1849 // Call async methods when in an async method

            return (handleExitCode?.Invoke(process.ExitCode) ?? false) || process.ExitCode == 0
                ? new Result(output, error)
                : throw new ExitCodeReadException(process.ExitCode, output, error);
        }

19 View Source File : Host.cs
License : MIT License
Project Creator : ancientproject

public static int Main(string[] c_args)
        {
            if (Environment.GetEnvironmentVariable("WT_SESSION") == null && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                Environment.SetEnvironmentVariable($"RUNE_EMOJI_USE", "0");
                Environment.SetEnvironmentVariable($"RUNE_COLOR_USE", "0");
                Environment.SetEnvironmentVariable($"RUNE_NIER_USE", "0");
                Environment.SetEnvironmentVariable($"NO_COLOR", "true");
                ForegroundColor = ConsoleColor.Gray;
                WriteLine($"no windows-terminal: coloring, emoji and nier has disabled.");
                ForegroundColor = ConsoleColor.White;
            }

            AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { ConsoleExtensions.Disable(); };
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            var raw = new FluentCommandLineParser<Args>();
            raw.Setup(x => x.sourceFiles)
                .As('s', "source")
                .WithDescription("Source files.")
                .SetDefault(new List<string>());
            raw.Setup(x => x.OutFile)
                .As('o', "out")
                .WithDescription("Out file.");
            raw.Setup(x => x.extension)
                .As('e', "ext")
                .WithDescription("Extension of file.")
                .SetDefault("dlx");
            raw.Parse(c_args);
            var args = raw.Object;

            var ver = FileVersionInfo.GetVersionInfo(typeof(Host).replacedembly.Location).ProductVersion;
            
            WriteLine($"Ancient replacedembler compiler version {ver}".Pastel(Color.Gray));
            WriteLine($"Copyright (C) 2020 Yuuki Wesp.\n\n".Pastel(Color.Gray));
            
            if (!args.sourceFiles.Any())
            {
                Warn(Warning.NoSource, "No source files specified.");
                return 1;
            }
            if (string.IsNullOrEmpty(args.OutFile))
            {
                Error(Warning.OutFileNotSpecified, "Outputs without source must have the --out option specified.");
                return 1;
            }

            if (!args.sourceFiles.Select(x => new FileInfo(x).Exists).All(x => x))
            {
                Error(Warning.SourceFileNotFound, "One source file not found.");
                return 1;
            }



            var source = File.ReadAllText(args.sourceFiles.First()).Replace("\r", "");
            
            try
            {
                var e = Evolve(source);
                var c = Compile(e, args);

                File.WriteAllBytes($"{args.OutFile}.{args.extension}", c.data);
                File.WriteAllBytes($"{args.OutFile}.pdb", c.map);
                return 0;
            }
            catch (AncientCompileException)
            { }
            catch (AncientEvolveException)
            { }
            catch (Exception e)
            {
                WriteLine(e);
            }

            return 1;
        }

19 View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static  DiskInfo FolderDiskInfo(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return new DiskInfo();
            }
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) )
            {
                return LinuxFolderDiskInfo(path);
            }
            else
            {
                return WindowsFolderDiskInfo(path);
            }
        }

19 View Source File : LibraryLoader.cs
License : MIT License
Project Creator : amerkoleci

public static IntPtr LoadLibrary(string libraryName)
        {
            if (!libraryName.EndsWith(Extension, StringComparison.OrdinalIgnoreCase))
                libraryName += Extension;


            var osPlatform = GetOSPlatform();
            var architecture = GetArchitecture();

            var libraryPath = GetNativereplacedemblyPath(osPlatform, architecture, libraryName);

            static string GetOSPlatform()
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    return "win";
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    return "linux";
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    return "osx";

                throw new ArgumentException("Unsupported OS platform.");
            }

            static string GetArchitecture()
            {
                switch (RuntimeInformation.ProcessArchitecture)
                {
                    case Architecture.X86: return "x86";
                    case Architecture.X64: return "x64";
                    case Architecture.Arm: return "arm";
                    case Architecture.Arm64: return "arm64";
                }

                throw new ArgumentException("Unsupported architecture.");
            }

            static string GetNativereplacedemblyPath(string osPlatform, string architecture, string libraryName)
            {
                var replacedemblyLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

                string[] paths = new[]
                {
                    Path.Combine(replacedemblyLocation, libraryName),
                    Path.Combine(replacedemblyLocation, "runtimes", osPlatform, "native", libraryName),
                    Path.Combine(replacedemblyLocation, "runtimes", $"{osPlatform}-{architecture}", "native", libraryName),
                    Path.Combine(replacedemblyLocation, "native", $"{osPlatform}-{architecture}", libraryName),
                };

                foreach (string path in paths)
                {
                    if (File.Exists(path))
                    {
                        return path;
                    }
                }

                return libraryName;
            }

            IntPtr handle;
#if !NET5_0_OR_GREATER
            handle = LoadPlatformLibrary(libraryPath);
#else
            handle = NativeLibrary.Load(libraryPath);
#endif

            if (handle == IntPtr.Zero)
                throw new DllNotFoundException($"Unable to load library '{libraryName}'.");

            return handle;
        }

19 View Source File : AppSettingsExtensions.cs
License : MIT License
Project Creator : aliencube

public static bool IsMacOs() => RuntimeInformation.IsOSPlatform(OSPlatform.OSX);

19 View Source File : ScanResult.cs
License : Apache License 2.0
Project Creator : airbus-cert

private IntPtr GetMatchesPtr(IntPtr scanContext)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                YR_SCAN_CONTEXT_WIN scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_WIN>(scanContext);
                return scan_context.matches;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                YR_SCAN_CONTEXT_LINUX scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_LINUX>(scanContext);
                return scan_context.matches;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                YR_SCAN_CONTEXT_OSX scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_OSX>(scanContext);
                return scan_context.matches;
            }
            return IntPtr.Zero;
        }

19 View Source File : LibraryLoader.cs
License : MIT License
Project Creator : amerkoleci

public static IntPtr LoadLocalLibrary(string libraryName)
        {
            if (!libraryName.EndsWith(Extension, StringComparison.OrdinalIgnoreCase))
                libraryName += Extension;


            var osPlatform = GetOSPlatform();
            var architecture = GetArchitecture();

            var libraryPath = GetNativereplacedemblyPath(osPlatform, architecture, libraryName);

            static string GetOSPlatform()
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    return "win";
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    return "linux";
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    return "osx";

                throw new ArgumentException("Unsupported OS platform.");
            }

            static string GetArchitecture()
            {
                switch (RuntimeInformation.ProcessArchitecture)
                {
                    case Architecture.X86: return "x86";
                    case Architecture.X64: return "x64";
                    case Architecture.Arm: return "arm";
                    case Architecture.Arm64: return "arm64";
                }

                throw new ArgumentException("Unsupported architecture.");
            }

            static string GetNativereplacedemblyPath(string osPlatform, string architecture, string libraryName)
            {
                var replacedemblyLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

                string[] paths = new[]
                {
                    Path.Combine(replacedemblyLocation, libraryName),
                    Path.Combine(replacedemblyLocation, "runtimes", osPlatform, "native", libraryName),
                    Path.Combine(replacedemblyLocation, "runtimes", $"{osPlatform}-{architecture}", "native", libraryName),
                    Path.Combine(replacedemblyLocation, "native", $"{osPlatform}-{architecture}", libraryName),
                };

                foreach (string path in paths)
                {
                    if (File.Exists(path))
                    {
                        return path;
                    }
                }

                return libraryName;
            }

            IntPtr handle;
#if !NET5_0_OR_GREATER
            handle = LoadPlatformLibrary(libraryPath);
#else
            handle = NativeLibrary.Load(libraryPath);
#endif

            if (handle == IntPtr.Zero)
                throw new DllNotFoundException($"Unable to load library '{libraryName}'.");

            return handle;
        }

19 View Source File : Command.cs
License : Apache License 2.0
Project Creator : adamralph

public static void Run(
            string name,
            string? args = null,
            string? workingDirectory = null,
            bool noEcho = false,
            string? windowsName = null,
            string? windowsArgs = null,
            string? echoPrefix = null,
            Action<IDictionary<string, string>>? configureEnvironment = null,
            bool createNoWindow = false,
            Func<int, bool>? handleExitCode = null,
            CancellationToken cancellationToken = default)
        {
            Validate(name);

            using var process = new Process();

            process.StartInfo = ProcessStartInfo.Create(
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsName ?? name : name,
                (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsArgs ?? args : args) ?? "",
                workingDirectory ?? "",
                false,
                configureEnvironment ?? defaultAction,
                createNoWindow);

            process.Run(noEcho, echoPrefix ?? defaultEchoPrefix, cancellationToken);

            if (!(handleExitCode?.Invoke(process.ExitCode) ?? false) && process.ExitCode != 0)
            {
                throw new ExitCodeException(process.ExitCode);
            }
        }

19 View Source File : SystemsHelper.cs
License : MIT License
Project Creator : Amine-Smahi

private static bool IsMac()
        {
            return RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
        }

19 View Source File : DatabaseFixture.cs
License : Apache License 2.0
Project Creator : AkkaNetContrib

public async Task InitializeAsync()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            var configuration = builder.Build();
            if (configuration["autoProvisionEventStore"] == "true")
            {
                DockerClientConfiguration config;

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ||
                    RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    config = new DockerClientConfiguration(new Uri("unix:///var/run/docker.sock"));
                }
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    config = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine"));
                }
                else
                {
                    throw new Exception("Unsupported OS");
                }

                _client = config.CreateClient();
                var images =
                        await _client.Images.ListImagesAsync(new ImagesListParameters {MatchName = EventStoreImage});
                if (images.Count == 0)
                {
                    // No image found. Pulling latest ..
                    await _client.Images.CreateImageAsync(
                        new ImagesCreateParameters {FromImage = EventStoreImage, Tag = "latest"}, null,
                        IgnoreProgress.Forever);
                }
                //var containers = await this._client.Containers.ListContainersAsync(new ContainersListParameters { All = true });

                _httpPort = Random.Next(2100, 2399);
                int tcpPort = Random.Next(1100, 1399);
                await _client.Containers.CreateContainerAsync(
                    new CreateContainerParameters
                    {
                        Image = EventStoreImage,
                        Name = _eventStoreContainerName,
                        Tty = true,
                        Env = new List<string>
                        {
                            "EVENTSTORE_RUN_PROJECTIONS=All",
                            "EVENTSTORE_START_STANDARD_PROJECTIONS=True",
                            "EVENTSTORE_MEM_DB=1"
                        },
                        HostConfig = new HostConfig
                        {
                            PortBindings = new Dictionary<string, IList<PortBinding>>
                            {
                                {
                                    $"2113/tcp",
                                    new List<PortBinding>
                                    {
                                        new PortBinding
                                        {
                                            HostPort = $"{_httpPort}"
                                        }
                                    }
                                },
                                {
                                    $"1113/tcp",
                                    new List<PortBinding>
                                    {
                                        new PortBinding
                                        {
                                            HostPort = $"{tcpPort}"
                                        }
                                    }
                                }
                            }
                        }
                    });
                // Starting the container ...
                await _client.Containers.StartContainerAsync(_eventStoreContainerName,
                    new ContainerStartParameters { });
                ConnectionString = $"ConnectTo=tcp://admin:[email protected]:{tcpPort}; HeartBeatTimeout=500";
                await Task.Delay(5000);
                await InitializeProjections(_httpPort);
            }
            else
            {
                ConnectionString = $"ConnectTo=tcp://admin:[email protected]:1113; HeartBeatTimeout=500";
                await InitializeProjections(2113);
            }
        }

19 View Source File : FluentAvaloniaTheme.cs
License : MIT License
Project Creator : amwx

private void InitIfNecessary()
		{
			if (!UseSegoeUIOnWindows && !GetUserAccentColor && !DefaultToUserTheme && CustomAccentColor == null)
				return;

			if (CustomAccentColor != null)
			{
				GenerateCustomAccentColor(_customAccentColor);
			}

			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{				
				if (UseSegoeUIOnWindows)
				{
					Win32Interop.OSVERSIONINFOEX osInfo = new Win32Interop.OSVERSIONINFOEX { OSVersionInfoSize = Marshal.SizeOf(typeof(Win32Interop.OSVERSIONINFOEX)) };
					Win32Interop.RtlGetVersion(ref osInfo);

					if (osInfo.BuildNumber >= 22000) // Windows 11
					{
						//This is defined in the BaseResources.axaml file
						(_loaded[1] as Styles).Resources["ContentControlThemeFontFamily"] = new FontFamily("Segoe UI Variable Text");
					}
					else // Windows 10
					{
						//This is defined in the BaseResources.axaml file
						(_loaded[1] as Styles).Resources["ContentControlThemeFontFamily"] = new FontFamily("Segoe UI");
					}                    
				}

				if (CustomAccentColor == null && GetUserAccentColor)
				{
					//These are defined in the AccentColors.axaml file
					(_loaded[0] as Styles).Resources["SystemAccentColor"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccent");
					(_loaded[0] as Styles).Resources["SystemAccentColorLight1"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentLight1");
					(_loaded[0] as Styles).Resources["SystemAccentColorLight2"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentLight2");
					(_loaded[0] as Styles).Resources["SystemAccentColorLight3"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentLight3");
					(_loaded[0] as Styles).Resources["SystemAccentColorDark1"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentDark1");
					(_loaded[0] as Styles).Resources["SystemAccentColorDark2"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentDark2");
					(_loaded[0] as Styles).Resources["SystemAccentColorDark3"] = Win32Interop.GetThemeColorRef("ImmersiveSystemAccentDark3");
				}
			}		
		}

19 View Source File : DynamoDBDockerFixture.cs
License : MIT License
Project Creator : abelperezok

private string DockerApiUri()
        {
            var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);

            if (isWindows)
            {
                return "npipe://./pipe/docker_engine";
            }

            var isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

            if (isLinux)
            {
                return "unix:///var/run/docker.sock";
            }

            throw new Exception("Was unable to determine what OS this is running on, does not appear to be Windows or Linux!?");
        }

19 View Source File : CoreWindow.cs
License : MIT License
Project Creator : amwx

public static IWindowImpl GetWindowImpl()
		{
			if (Design.IsDesignMode)
				return PlatformManager.CreateWindow();

			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				return new CoreWindowImpl();
			}

			return PlatformManager.CreateWindow();
		}

19 View Source File : HardwareInfo.cs
License : Apache License 2.0
Project Creator : alexyakunin

public static string GetCpuModelName()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
                var cmd = Command.Run("wmic", "cpu", "get", "name");
                return cmd.StandardOutput.GetLines().SkipEmpty().Last().Trim();
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
                var cmd = Command.Run("cat", "/proc/cpuinfo");
                return cmd.StandardOutput.GetLines().SkipEmpty()
                    .ToPairs().First(p => p.Name == "model name").Value;
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
                var cmd = Command.Run("sysctl", "-n", "machdep.cpu.brand_string");
                return cmd.StandardOutput.GetLines().SkipEmpty().Last().Trim();
            }
            else 
                throw new NotSupportedException($"Unsupported OS: {RuntimeInformation.OSDescription}");
        }

19 View Source File : HardwareInfo.cs
License : Apache License 2.0
Project Creator : alexyakunin

public static int? GetRamSize()
        {
            try {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
                    var cmd = Command.Run("wmic", "computersystem", "get", "TotalPhysicalMemory");
                    var stringValue = cmd.StandardOutput.GetLines().SkipEmpty().Last().Trim();
                    return (int) Math.Round(long.Parse(stringValue) / Sizes.GB);
                }
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
                    var cmd = Command.Run("cat", "/proc/meminfo");
                    var stringValue = cmd.StandardOutput.GetLines().SkipEmpty()
                        .ToPairs().Single(p => p.Name == "MemTotal")
                        .Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).First();
                    return (int) Math.Round(long.Parse(stringValue) * Sizes.KB / Sizes.GB);
                }
                if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
                    var cmd = Command.Run("system_profiler", "SPHardwareDataType");
                    var stringValue = cmd.StandardOutput.GetLines().SkipEmpty()
                        .ToPairs().Single(p => p.Name == "Memory")
                        .Value.Split(' ', StringSplitOptions.RemoveEmptyEntries).First();
                    return (int) Math.Round(double.Parse(stringValue));
                }
                return null;
            }
            catch {
                return null;
            }
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

private static void OnProcessExit(object sender, EventArgs e)
        {
            if (!IsRunningInContainer)
            {
                if (!ServerManager.ShutdownInitiated)
                    log.Warn("Unsafe server shutdown detected! Data loss is possible!");

                PropertyManager.StopUpdating();
                DatabaseManager.Stop();

                // Do system specific cleanup here
                try
                {
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        MM_EndPeriod(1);
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.ToString());
                }
            }
            else
            {
                ServerManager.DoShutdownNow();
                DatabaseManager.Stop();
            }
        }

19 View Source File : AppSettingsExtensions.cs
License : MIT License
Project Creator : aliencube

public static bool IsLinux() => RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

19 View Source File : ZeroAppConfig.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

private static void CheckConfig()
        {
            var curPath = ConfigurationManager.Root.GetValue("contentRoot", Environment.CurrentDirectory);
            string rootPath;
            if (ConfigurationManager.Root["ASPNETCORE_ENVIRONMENT_"] == "Development")
            {
                ZeroTrace.SystemLog("Option", "Development");
                AppName = ConfigurationManager.Root["AppName"];
                rootPath = curPath;
            }
            else
            {
                ZeroTrace.SystemLog("Option", RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "Linux" : "Windows");
                rootPath = Path.GetDirectoryName(curPath);
                AppName= Path.GetFileName(curPath);
                // ReSharper disable once replacedignNullToNotNullAttribute
                var file = Path.Combine(rootPath, "config", "zero.json");
                if (File.Exists(file))
                    ConfigurationManager.Load(file);
                file = Path.Combine(rootPath, "config", $"{AppName}.json");
                if (File.Exists(file))
                    ConfigurationManager.Load(file);
                var name = ConfigurationManager.Root["AppName"];
                if (name == null)
                    ConfigurationManager.Root["AppName"] = AppName;
                else
                    AppName = name;
            }

            ConfigurationManager.Root["rootPath"] = rootPath;

            var sec = ConfigurationManager.Get("Zero");
            if (sec == null)
                throw new Exception("无法找到主配置节点,路径为Zero,在appsettings.json中设置");
            var global = sec.Child<ZeroAppConfig>("Global");
            if (global == null)
                throw new Exception("无法找到主配置节点,路径为Zero.Global,在appsettings.json中设置");
            Config = string.IsNullOrWhiteSpace(AppName)
                ? sec.Child<ZeroAppConfig>("Station")
                : sec.Child<ZeroAppConfig>(AppName) ?? sec.Child<ZeroAppConfig>("Station");
            

            if (Config == null)
                throw new Exception($"无法找到主配置节点,路径为Zero.{AppName}或Zero.Station,在appsettings.json中设置");
            Config.BinPath = curPath;
            Config.RootPath = rootPath;

            var socketOption = sec.Child<SocketOption>("socketOption");
            if (socketOption != null)
                ZSocket.Option = socketOption;

            if (string.IsNullOrWhiteSpace(AppName))
                ConfigurationManager.Root["AppName"] = AppName = Config.StationName;

            Config.IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
            
            global.LogFolder = string.IsNullOrWhiteSpace(global.LogFolder) ? IOHelper.CheckPath(rootPath, "logs") : global.LogFolder.Trim();
            global.DataFolder = string.IsNullOrWhiteSpace(global.DataFolder) ? IOHelper.CheckPath(rootPath, "datas") : global.DataFolder.Trim();
            global.ServiceName = string.IsNullOrWhiteSpace(global.ServiceName) ? Dns.GetHostName() : global.ServiceName.Trim();
            global.ServiceKey = string.IsNullOrWhiteSpace(global.ServiceKey) ? RandomOperate.Generate(8) : global.ServiceKey.Trim();
            global.ConfigFolder = string.IsNullOrWhiteSpace(global.ConfigFolder) ? IOHelper.CheckPath(rootPath, "config") : global.ConfigFolder.Trim();

            global.ZeroAddress = string.IsNullOrWhiteSpace(global.ZeroAddress) ? "127.0.0.1" : global.ZeroAddress.Trim();
            if (global.ZeroManagePort <= 1024 || Config.ZeroManagePort >= 65000)
                global.ZeroManagePort = 8000;
            if (global.ZeroMonitorPort <= 1024 || Config.ZeroMonitorPort >= 65000)
                global.ZeroMonitorPort = 8001;


            if (global.StationIsolate || Config.StationIsolate)
            {
                Config.ServiceName = string.IsNullOrWhiteSpace(Config.ServiceName) ? global.ServiceName : Config.ServiceName.Trim();
                Config.ServiceKey = string.IsNullOrWhiteSpace(Config.ServiceKey) ? global.ServiceKey : Config.ServiceKey.Trim();
                Config.ZeroAddress = string.IsNullOrWhiteSpace(Config.ZeroAddress) ? global.ZeroAddress : Config.ZeroAddress.Trim();
                if (Config.ZeroManagePort <= 1024 || Config.ZeroManagePort >= 65000)
                    Config.ZeroManagePort = global.ZeroManagePort;
                if (Config.ZeroMonitorPort <= 1024 || Config.ZeroMonitorPort >= 65000)
                    Config.ZeroMonitorPort = global.ZeroMonitorPort;

                Config.DataFolder = string.IsNullOrWhiteSpace(Config.DataFolder) ? global.DataFolder : IOHelper.CheckPath(global.DataFolder, AppName, "datas");
                Config.LogFolder = string.IsNullOrWhiteSpace(Config.LogFolder) ? global.LogFolder : IOHelper.CheckPath(global.LogFolder, AppName, "logs");
                Config.ConfigFolder = string.IsNullOrWhiteSpace(Config.ConfigFolder) ? global.ConfigFolder : IOHelper.CheckPath(rootPath, AppName, "config");
            }
            else
            {
                Config.ServiceName = global.ServiceName;
                Config.ServiceKey = global.ServiceKey;
                Config.ZeroAddress = global.ZeroAddress;
                Config.ZeroManagePort = global.ZeroManagePort;
                Config.ZeroMonitorPort = global.ZeroMonitorPort;

                Config.DataFolder = global.DataFolder;
                Config.LogFolder = global.LogFolder;
                Config.ConfigFolder = global.ConfigFolder;
            }
            TxtRecorder.LogPath = Config.LogFolder;
            ConfigurationManager.Get("LogRecorder")["txtPath"] = Config.LogFolder;

            Config.ZeroManageAddress = ZeroIdenreplacedyHelper.GetRequestAddress("SystemManage", Config.ZeroManagePort);
            Config.ZeroMonitorAddress = ZeroIdenreplacedyHelper.GetWorkerAddress("SystemMonitor", Config.ZeroMonitorPort);
            Config.LocalIpAddress = GetHostIps();
            Config.ShortName = string.IsNullOrWhiteSpace(Config.ShortName) ? Config.StationName : Config.ShortName.Trim();
            Config.RealName = ZeroIdenreplacedyHelper.CreateRealName(false);
            Config.Idenreplacedy = Config.RealName.ToAsciiBytes();
            //模式选择

            if (Config.SpeedLimitModel < SpeedLimitType.Single || Config.SpeedLimitModel > SpeedLimitType.WaitCount)
                Config.SpeedLimitModel = SpeedLimitType.ThreadCount;

            if (Config.TaskCpuMultiple <= 0)
                Config.TaskCpuMultiple = 1;
            else if (Config.TaskCpuMultiple > 128)
                Config.TaskCpuMultiple = 128;

            if (Config.MaxWait < 0xFF)
                Config.MaxWait = 0xFF;
            else if (Config.MaxWait > 0xFFFFF)
                Config.MaxWait = 0xFFFFF;

            ShowOptionInfo(rootPath);
        }

19 View Source File : GLFW.cs
License : MIT License
Project Creator : amerkoleci

private static IntPtr LoadGLFWLibrary()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return LibraryLoader.LoadLibrary("glfw3.dll");
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                return LibraryLoader.LoadLibrary("libglfw.so.3.3");
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return LibraryLoader.LoadLibrary("libglfw.3.dylib");
            }

            throw new PlatformNotSupportedException("GLFW platform not supported");
        }

19 View Source File : ExceptionHelper.cs
License : MIT License
Project Creator : alonf

private static bool IsTlsSecurity(Exception singleException)
        {
            if (// WinHttpException (0x80072F8F): A security error occurred.
                (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && (singleException.HResult == unchecked((int)0x80072F8F))) ||
                // CURLE_SSL_CACERT (60): Peer certificate cannot be authenticated with known CA certificates.
                (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && (singleException.HResult == 60)) ||
                singleException is AuthenticationException)
            {
                return true;
            }

            return false;
        }

19 View Source File : ScanResult.cs
License : Apache License 2.0
Project Creator : airbus-cert

private IntPtr GetProfilingInfoPtr(IntPtr scanContext)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                YR_SCAN_CONTEXT_WIN scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_WIN>(scanContext);
                return scan_context.profiling_info;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                YR_SCAN_CONTEXT_LINUX scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_LINUX>(scanContext);
                return scan_context.profiling_info;
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                YR_SCAN_CONTEXT_OSX scan_context = Marshal.PtrToStructure<YR_SCAN_CONTEXT_OSX>(scanContext);
                return scan_context.profiling_info;
            }
            return IntPtr.Zero;
        }

19 View Source File : LibraryLoader.cs
License : MIT License
Project Creator : amerkoleci

private static IntPtr LoadPlatformLibrary(string libraryName)
        {
            if (string.IsNullOrEmpty(libraryName))
                throw new ArgumentNullException(nameof(libraryName));

            IntPtr handle;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                handle = Win32.LoadLibrary(libraryName);
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                handle = Linux.dlopen(libraryName);
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                handle = Mac.dlopen(libraryName);
            else
                throw new PlatformNotSupportedException($"Current platform is unknown, unable to load library '{libraryName}'.");

            return handle;
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : actions

private async static Task<int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace(nameof(GitHub.Runner.Listener));
            trace.Info($"Runner is built for {Constants.Runner.Platform} ({Constants.Runner.PlatformArchitecture}) - {BuildConstants.RunnerPackage.PackageName}.");
            trace.Info($"RuntimeInformation: {RuntimeInformation.OSDescription}.");
            context.WritePerfCounter("RunnerProcessStarted");
            var terminal = context.GetService<ITerminal>();

            // Validate the binaries intended for one OS are not running on a different OS.
            switch (Constants.Runner.Platform)
            {
                case Constants.OSPlatform.Linux:
                    if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        terminal.WriteLine("This runner version is built for Linux. Please install a correct build for your OS.");
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }
                    break;
                case Constants.OSPlatform.OSX:
                    if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                    {
                        terminal.WriteLine("This runner version is built for OSX. Please install a correct build for your OS.");
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }
                    break;
                case Constants.OSPlatform.Windows:
                    if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        terminal.WriteLine("This runner version is built for Windows. Please install a correct build for your OS.");
                        return Constants.Runner.ReturnCode.TerminatedError;
                    }
                    break;
                default:
                    terminal.WriteLine($"Running the runner on this platform is not supported. The current platform is {RuntimeInformation.OSDescription} and it was built for {Constants.Runner.Platform.ToString()}.");
                    return Constants.Runner.ReturnCode.TerminatedError;
            }

            try
            {
                trace.Info($"Version: {BuildConstants.RunnerPackage.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");

                // Validate directory permissions.
                string runnerDirectory = context.GetDirectory(WellKnownDirectory.Root);
                trace.Info($"Validating directory permissions for: '{runnerDirectory}'");
                try
                {
                    IOUtil.ValidateExecutePermission(runnerDirectory);
                }
                catch (Exception e)
                {
                    terminal.WriteError($"An error occurred: {e.Message}");
                    trace.Error(e);
                    return Constants.Runner.ReturnCode.TerminatedError;
                }

                // Parse the command line args.
                var command = new CommandSettings(context, args);
                trace.Info("Arguments parsed");

                // Up front validation, warn for unrecognized commandline args.
                var unknownCommandlines = command.Validate();
                if (unknownCommandlines.Count > 0)
                {
                    terminal.WriteError($"Unrecognized command-line input arguments: '{string.Join(", ", unknownCommandlines)}'. For usage refer to: .\\config.cmd --help or ./config.sh --help");
                }

                // Defer to the Runner clreplaced to execute the command.
                IRunner runner = context.GetService<IRunner>();
                try
                {
                    var returnCode = await runner.ExecuteCommand(command);
                    trace.Info($"Runner execution has finished with return code {returnCode}");
                    return returnCode;
                }
                catch (OperationCanceledException) when (context.RunnerShutdownToken.IsCancellationRequested)
                {
                    trace.Info("Runner execution been cancelled.");
                    return Constants.Runner.ReturnCode.Success;
                }
                catch (NonRetryableException e)
                {
                    terminal.WriteError($"An error occurred: {e.Message}");
                    trace.Error(e);
                    return Constants.Runner.ReturnCode.TerminatedError;
                }

            }
            catch (Exception e)
            {
                terminal.WriteError($"An error occurred: {e.Message}");
                trace.Error(e);
                return Constants.Runner.ReturnCode.RetryableError;
            }
        }

19 View Source File : Vulkan.cs
License : MIT License
Project Creator : amerkoleci

public static VkResult vkInitialize()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                s_vulkanModule = LoadLibrary("vulkan-1.dll");
                if (s_vulkanModule == IntPtr.Zero)
                    return VkResult.ErrorInitializationFailed;

                vkGetInstanceProcAddr_ptr = (delegate* unmanaged[Stdcall]<VkInstance, byte*, delegate* unmanaged[Stdcall]<void>>)GetProcAddress(s_vulkanModule, nameof(vkGetInstanceProcAddr));
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                s_vulkanModule = dlopen("libvulkan.dylib", RTLD_NOW);
                if (s_vulkanModule == IntPtr.Zero)
                    s_vulkanModule = dlopen("libvulkan.1.dylib", RTLD_NOW);
                if (s_vulkanModule == IntPtr.Zero)
                    s_vulkanModule = dlopen("libMoltenVK.dylib", RTLD_NOW);

                if (s_vulkanModule == IntPtr.Zero)
                    return VkResult.ErrorInitializationFailed;

                vkGetInstanceProcAddr_ptr = (delegate* unmanaged[Stdcall]<VkInstance, byte*, delegate* unmanaged[Stdcall]<void>>)dlsym(s_vulkanModule, nameof(vkGetInstanceProcAddr));
            }
            else
            {
                s_vulkanModule = dlopen("libvulkan.so.1", RTLD_NOW);
                if (s_vulkanModule == IntPtr.Zero)
                    s_vulkanModule = dlopen("libvulkan.so", RTLD_NOW);

                if (s_vulkanModule == IntPtr.Zero)
                    return VkResult.ErrorInitializationFailed;

                vkGetInstanceProcAddr_ptr = (delegate* unmanaged[Stdcall]<VkInstance, byte*, delegate* unmanaged[Stdcall]<void>>)dlsym(s_vulkanModule, nameof(vkGetInstanceProcAddr));
            }

            GenLoadLoader(IntPtr.Zero, vkGetInstanceProcAddr);

            return VkResult.Success;
        }

19 View Source File : OpensslEsiaSigner.cs
License : GNU General Public License v3.0
Project Creator : AISGorod

public string Sign(byte[] data)
        {
            Process a = new Process();
            a.StartInfo.FileName = "openssl";
            a.StartInfo.Arguments = $"cms -sign -binary -stream -engine gost -inkey {KEY_FILE} -signer {CRT_FILE} -nodetach -outform pem";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                a.StartInfo.FileName = "wsl";
                a.StartInfo.Arguments = "openssl " + a.StartInfo.Arguments;
            }

            a.StartInfo.RedirectStandardInput = true;
            a.StartInfo.RedirectStandardOutput = true;
            a.StartInfo.UseShellExecute = false;

            a.Start();
            a.StandardInput.Write(Encoding.UTF8.GetString(data)); // просто передавать массив байтов не получается - ломает подпись
            a.StandardInput.Close();

            StringBuilder resultData = new StringBuilder();
            bool isKeyProcessing = false;
            while (!a.StandardOutput.EndOfStream)
            {
                string line = a.StandardOutput.ReadLine();
                if (line == "-----BEGIN CMS-----")
                {
                    isKeyProcessing = true;
                }
                else if (line == "-----END CMS-----")
                {
                    isKeyProcessing = false;
                }
                else if (isKeyProcessing)
                {
                    resultData.Append(line);
                }
            }
            return resultData.ToString();
        }

19 View Source File : Native.cs
License : MIT License
Project Creator : amerkoleci

private static IntPtr LoadNativeLibrary()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return LibraryLoader.LoadLocalLibrary("shaderc_shared.dll");
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                return LibraryLoader.LoadLocalLibrary("libshaderc_shared.so");
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return LibraryLoader.LoadLocalLibrary("libshaderc_shared.dylib");
            }
            else
            {
                return LibraryLoader.LoadLocalLibrary("shaderc_shared");
            }
        }

19 View Source File : HighResolutionDateTime.cs
License : MIT License
Project Creator : Abc-Arbitrage

[DebuggerStepThrough]
        private static bool CheckAvailability()
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                return false;

            try
            {
                GetSystemTimePreciseAsFileTime(out _);
                return true;
            }
            catch (DllNotFoundException)
            {
                // Not running Windows 8 or higher.
                return false;
            }
            catch (EntryPointNotFoundException)
            {
                // Not running Windows 8 or higher.
                return false;
            }
        }

19 View Source File : SystemsHelper.cs
License : MIT License
Project Creator : Amine-Smahi

private static bool IsWindows()
        {
            return RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
        }

19 View Source File : DockerSupport.cs
License : Apache License 2.0
Project Creator : akkadotnet

public async Task SetupContainersAsync()
        {
            DockerClientConfiguration config;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                config = new DockerClientConfiguration(new Uri("unix://var/run/docker.sock"));
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                config = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine"));
            else
                throw new NotSupportedException($"Unsupported OS [{RuntimeInformation.OSDescription}]");
            
            Client = config.CreateClient();

            // Generate random ports for zookeeper and kafka
            ZookeeperPort = TemporaryTcpAddress("127.0.0.1").Port;
            KafkaPort = TemporaryTcpAddress("127.0.0.1").Port;
            
            // Load images, if they not exist yet
            await EnsureImageExistsAsync(ZookeeperImageName, ZookeeperImageTag);
            await EnsureImageExistsAsync(KafkaImageName, KafkaImageTag);

            // Make resources cleanup before allocating new containers/networks
            await ResourceCleanupAsync();

            // create the containers
            await CreateContainerAsync(ZookeeperImageName, ZookeeperImageTag, _zookeeperContainerName, ZookeeperPort, new Dictionary<string, string>()
            {
                ["ZOOKEEPER_CLIENT_PORT"] = ZookeeperPort.ToString(),
                ["ZOOKEEPER_TICK_TIME"] = "2000",
            });
            await CreateContainerAsync(KafkaImageName, KafkaImageTag, _kafkaContainerName, KafkaPort, new Dictionary<string, string>()
            {
                ["KAFKA_BROKER_ID"] = "1",
                ["KAFKA_NUM_PARreplacedIONS"] = "3",
                ["KAFKA_ZOOKEEPER_CONNECT"] = $"{_zookeeperContainerName}:{ZookeeperPort}", // referencing zookeeper container directly in common docker network
                ["KAFKA_LISTENERS"] = $"PLAINTEXT://:{KafkaPort}",
                ["KAFKA_ADVERTISED_LISTENERS"] = $"PLAINTEXT://127.0.0.1:{KafkaPort}",
                ["KAFKA_AUTO_CREATE_TOPICS_ENABLE"] = "true",
                ["KAFKA_DELETE_TOPIC_ENABLE"] = "true",
                ["KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR"] = "1",
                ["KAFKA_OPTS"] = "-Djava.net.preferIPv4Stack=True"
            });

            // Setting up network for containers to communicate
            var network = await Client.Networks.CreateNetworkAsync(new NetworksCreateParameters(new NetworkCreate())
            {
                Name = _networkName
            });
            await Client.Networks.ConnectNetworkAsync(network.ID, new NetworkConnectParameters()
            {
                Container = _kafkaContainerName
            });
            await Client.Networks.ConnectNetworkAsync(network.ID, new NetworkConnectParameters()
            {
                Container = _zookeeperContainerName
            });

            // start the containers
            await Client.Containers.StartContainerAsync(_zookeeperContainerName, new ContainerStartParameters());
            await Client.Containers.StartContainerAsync(_kafkaContainerName, new ContainerStartParameters());
        }

19 View Source File : SystemsHelper.cs
License : MIT License
Project Creator : Amine-Smahi

private static bool IsLinux()
        {
            return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
        }

19 View Source File : Command.cs
License : Apache License 2.0
Project Creator : adamralph

public static async Task RunAsync(
            string name,
            string? args = null,
            string? workingDirectory = null,
            bool noEcho = false,
            string? windowsName = null,
            string? windowsArgs = null,
            string? echoPrefix = null,
            Action<IDictionary<string, string>>? configureEnvironment = null,
            bool createNoWindow = false,
            Func<int, bool>? handleExitCode = null,
            CancellationToken cancellationToken = default)
        {
            Validate(name);

            using var process = new Process();

            process.StartInfo = ProcessStartInfo.Create(
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsName ?? name : name,
                (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsArgs ?? args : args) ?? "",
                workingDirectory ?? "",
                false,
                configureEnvironment ?? defaultAction,
                createNoWindow);

            await process.RunAsync(noEcho, echoPrefix ?? defaultEchoPrefix, cancellationToken).ConfigureAwait(false);

            if (!(handleExitCode?.Invoke(process.ExitCode) ?? false) && process.ExitCode != 0)
            {
                throw new ExitCodeException(process.ExitCode);
            }
        }

19 View Source File : FluentAvaloniaTheme.cs
License : MIT License
Project Creator : amwx

private void Init(bool clear = false)
		{
			if (clear && _loaded != null) //This is a complete refresh, e.g., changing Version #
			{
				for (int i = 0; i < _loaded.Length; i++)
				{
					(_loaded[i] as IResourceProvider)?.RemoveOwner(Owner);
				}
				_loaded = null;
			}

			//Make sure we don't get an invalid version number
			string thm = GetTheme();

            // Must populate this incrementally, otherwise some resources won't evaluate if they're in other files
            _loaded = new IStyle[4];
            _loaded[0] = (IStyle)AvaloniaXamlLoader.Load(new Uri($"avares://FluentAvalonia/Styling/StylesV2/AccentColors.axaml", UriKind.Absolute), _baseUri);
            _loaded[1] = (IStyle)AvaloniaXamlLoader.Load(new Uri($"avares://FluentAvalonia/Styling/StylesV2/BaseResources.axaml", UriKind.Absolute), _baseUri);
            _loaded[2] = (IStyle)AvaloniaXamlLoader.Load(new Uri($"avares://FluentAvalonia/Styling/StylesV2/{thm}Resources.axaml", UriKind.Absolute), _baseUri);
            _loaded[3] = (IStyle)AvaloniaXamlLoader.Load(new Uri($"avares://FluentAvalonia/Styling/StylesV2/Controls.axaml", UriKind.Absolute), _baseUri);

			// TODO: Figure out how to load HighContrast theme colors from system
			// This only loads one version of the HC theme & doesn't respect the variants
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
			{
				// Populate HighContrast from System Colors
				if (string.Equals(thm, HighContrastModeString))
				{
					bool GetSystemColor(SystemColors color, out Color c)
					{
						try
						{
							var intCol = Win32Interop.GetSysColor(color);
							var r = (byte)((intCol >> 16) & 0xFF);
							var g = (byte)((intCol >> 8) & 0xFF);
							var b = (byte)(intCol & 0xFF);

							c = Color.FromRgb(r, g, b);

							return true;
						}
						catch
						{
							c = Colors.Transparent;
							return false;
						}
					}

					if (GetSystemColor(SystemColors.COLOR_WINDOWTEXT, out Color windowT))
						(_loaded[0] as Styles).Resources["SystemColorWindowTextColor"] = windowT;

					if (GetSystemColor(SystemColors.COLOR_GRAYTEXT, out Color grey))
						(_loaded[0] as Styles).Resources["SystemColorGrayTextColor"] = grey;

					if (GetSystemColor(SystemColors.COLOR_BTNFACE, out Color btn))
						(_loaded[0] as Styles).Resources["SystemColorButtonFaceColor"] = btn;

					if (GetSystemColor(SystemColors.COLOR_WINDOW, out Color window))
						(_loaded[0] as Styles).Resources["SystemColorWindowColor"] = window;

					if (GetSystemColor(SystemColors.COLOR_BTNTEXT, out Color btnT))
						(_loaded[0] as Styles).Resources["SystemColorButtonTextColor"] = btnT;

					if (GetSystemColor(SystemColors.COLOR_HIGHLIGHT, out Color highlight))
						(_loaded[0] as Styles).Resources["SystemColorHighlightColor"] = highlight;

					if (GetSystemColor(SystemColors.COLOR_HIGHLIGHTTEXT, out Color highlightT))
						(_loaded[0] as Styles).Resources["SystemColorHighlightTextColor"] = highlightT;

					if (GetSystemColor(SystemColors.COLOR_HOTLIGHT, out Color hotlight))
						(_loaded[0] as Styles).Resources["SystemColorHotlightColor"] = hotlight;
				}
			}

			InitIfNecessary();
		}

19 View Source File : SampleDbMigrationService.cs
License : MIT License
Project Creator : albyho

private void AddInitialMigration()
        {
            Logger.LogInformation("Creating initial migration...");

            string argumentPrefix;
            string fileName;

            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                argumentPrefix = "-c";
                fileName = "/bin/bash";
            }
            else
            {
                argumentPrefix = "/C";
                fileName = "cmd.exe";
            }

            var procStartInfo = new ProcessStartInfo(fileName,
                $"{argumentPrefix} \"abp create-migration-and-run-migrator \"{GetEnreplacedyFrameworkCoreProjectFolderPath()}\"\""
            );

            try
            {
                Process.Start(procStartInfo);
            }
            catch (Exception)
            {
                throw new Exception("Couldn't run ABP CLI...");
            }
        }

19 View Source File : FluentAvaloniaTheme.cs
License : MIT License
Project Creator : amwx

private string GetTheme()
		{
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && DefaultToUserTheme)
			{
				Win32Interop.OSVERSIONINFOEX osInfo = new Win32Interop.OSVERSIONINFOEX { OSVersionInfoSize = Marshal.SizeOf(typeof(Win32Interop.OSVERSIONINFOEX)) };
				Win32Interop.RtlGetVersion(ref osInfo);

                try
                {
                    var hc = new Win32Interop.HIGHCONTRAST
                    {
                        cbSize = (uint)Marshal.SizeOf<Win32Interop.HIGHCONTRAST>()
                    };

                    bool ok = Win32Interop.SystemParametersInfo(0x0042 /*SPI_GETHIGHCONTRAST*/, 0, ref hc, 0);

                    if (ok && (hc.dwFlags & HCF.HCF_HIGHCONTRASTON) == HCF.HCF_HIGHCONTRASTON)
                    {
                        _mode = HighContrastModeString;
                        return _mode;
                    }
                }
                catch { }
				

                bool useDark = Win32Interop.GetSystemTheme(osInfo);
				_mode = useDark ? DarkModeString : LightModeString;
				return _mode;
			}

			if (_mode == LightModeString || _mode == DarkModeString || _mode == HighContrastModeString)
				return _mode;

			_mode = LightModeString; // Default to Mode
			return _mode;
		}

19 View Source File : Program.cs
License : MIT License
Project Creator : 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 View Source File : MainWindowViewModel.cs
License : MIT License
Project Creator : amwx

public void SetDarkTheme()
        {
			// Only line needed to switch to Dark Theme
			AvaloniaLocator.Current.GetService<FluentAvaloniaTheme>().RequestedTheme = "Dark";

			// Optional, if you want the native win32 replacedlebar to switch themes too (1809+ only)
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
				App.Current.ApplicationLifetime is IClreplacedicDesktopStyleApplicationLifetime cdl)
			{
				AvaloniaLocator.Current.GetService<FluentAvaloniaTheme>()?.ForceNativereplacedleBarToTheme(cdl.MainWindow);
			}

			// Ignore these, these are for the SampleApp only
			App.Current.Resources["ControlExampleStrokeColor"] = new SolidColorBrush(Color.Parse("#12FFFFFF"));
			App.Current.Resources["ControlExampleBackgroundFill"] = new SolidColorBrush(Color.Parse("#202020"));
			App.Current.Resources["ControlExampleBackgroundFill2"] = new SolidColorBrush(Color.Parse("#292929"));
		}

19 View Source File : ThemeManager.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public static void SetSystemTheme()
        {
            var useDarkTheme = false;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                useDarkTheme = !Native.Windows.WindowsUtils.IsAppLightThemePreferred();
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                useDarkTheme = Native.MacOS.MacUtils.IsDarkModeEnabled();
            }

            if (useDarkTheme)
            {
                SetDarkTheme();
            }
            else
            {
                SetLightTheme();
            }
        }

19 View Source File : TargetCollectionExtensions.cs
License : Apache License 2.0
Project Creator : adamralph

private static async Task RunAsync(
            this TargetCollection targets,
            IReadOnlyCollection<string> args,
            IReadOnlyCollection<string> names,
            IOptions options,
            IReadOnlyCollection<string> unknownOptions,
            bool showHelp,
            Func<Exception, bool> messageOnly,
            string messagePrefix,
            TextWriter outputWriter,
            TextWriter diagnosticsWriter)
        {
            if (options.Clear)
            {
                try
                {
                    Console.Clear();
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
                {
                    await diagnosticsWriter.WriteLineAsync($"{messagePrefix}: Failed to clear the console: {ex}").Tax();
                }
            }

            var noColor = options.NoColor;

            if (Environment.GetEnvironmentVariable("NO_COLOR") != null)
            {
                if (options.Verbose)
                {
                    await diagnosticsWriter.WriteLineAsync($"{messagePrefix}: NO_COLOR environment variable is set. Colored output is disabled.").Tax();
                }

                noColor = true;
            }

            var host = options.Host.DetectIfNull();

            var operatingSystem =
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                    ? OperatingSystem.Windows
                    : RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                        ? OperatingSystem.Linux
                        : RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
                            ? OperatingSystem.MacOS
                            : OperatingSystem.Unknown;

            var output = new Output(
                outputWriter,
                args,
                options.DryRun,
                host,
                options.Host.HasValue,
                noColor,
                options.NoExtendedChars,
                operatingSystem,
                options.Parallel,
                messagePrefix,
                options.SkipDependencies,
                options.Verbose);

            var outputState = await output.Initialize(options.Verbose ? diagnosticsWriter : TextWriter.Null).Tax();

            try
            {
                await output.Header(() => typeof(TargetCollection).replacedembly.GetVersion()).Tax();

                await targets.RunAsync(
                    names,
                    options.DryRun,
                    options.ListDependencies,
                    options.ListInputs,
                    options.ListTargets,
                    options.ListTree,
                    options.Parallel,
                    options.SkipDependencies,
                    unknownOptions,
                    showHelp,
                    messageOnly,
                    output).Tax();
            }
            finally
            {
                await outputState.DisposeAsync().Tax();
            }
        }

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

public async Task FindDiscKeyAsync(string discKeyCachePath)
        {
            // reload disc keys
            try
            {
                foreach (var keyProvider in DiscKeyProviders)
                {
                    Log.Trace($"Getting keys from {keyProvider.GetType().Name}...");
                    var newKeys = await keyProvider.EnumerateAsync(discKeyCachePath, ProductCode, Cts.Token).ConfigureAwait(false);
                    Log.Trace($"Got {newKeys.Count} keys");
                    lock (AllKnownDiscKeys)
                    {
                        foreach (var keyInfo in newKeys)
                        {
                            try
                            {
                                if (!AllKnownDiscKeys.TryGetValue(keyInfo.DecryptedKeyId, out var duplicates))
                                    AllKnownDiscKeys[keyInfo.DecryptedKeyId] = duplicates = new HashSet<DiscKeyInfo>();
                                duplicates.Add(keyInfo);
                            }
                            catch (Exception e)
                            {
                                Log.Error(e);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to load disc keys");
            }
            // check if user provided something new since the last attempt
            var untestedKeys = new HashSet<string>();
            lock (AllKnownDiscKeys)
                untestedKeys.UnionWith(AllKnownDiscKeys.Keys);
            untestedKeys.ExceptWith(TestedDiscKeys);
            if (untestedKeys.Count == 0)
                throw new KeyNotFoundException("No valid disc decryption key was found");

            // select physical device
            string physicalDevice = null;
            List<string> physicalDrives = new List<string>();
            Log.Trace("Trying to enumerate physical drives...");
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    physicalDrives = EnumeratePhysicalDrivesWindows();
                else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    physicalDrives = EnumeratePhysicalDrivesLinux();
                else
                    throw new NotImplementedException("Current OS is not supported");
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw;
            }
            Log.Debug($"Found {physicalDrives.Count} physical drives");

            if (physicalDrives.Count == 0)
                throw new InvalidOperationException("No optical drives were found");

            foreach (var drive in physicalDrives)
            {
                try
                {
                    Log.Trace($"Checking physical drive {drive}...");
                    using var discStream = File.Open(drive, FileMode.Open, FileAccess.Read, FileShare.Read);
                    var tmpDiscReader = new CDReader(discStream, true, true);
                    if (tmpDiscReader.FileExists("PS3_DISC.SFB"))
                    {
                        Log.Trace("Found PS3_DISC.SFB, getting sector data...");
                        var discSfbInfo = tmpDiscReader.GetFileInfo("PS3_DISC.SFB");
                        if (discSfbInfo.Length == discSfbData.Length)
                        {
                            var buf = new byte[discSfbData.Length];
                            var sector = tmpDiscReader.PathToClusters(discSfbInfo.FullName).First().Offset;
                            Log.Trace($"PS3_DISC.SFB sector number is {sector}, reading content...");
                            discStream.Seek(sector * tmpDiscReader.ClusterSize, SeekOrigin.Begin);
                            discStream.ReadExact(buf, 0, buf.Length);
                            if (buf.SequenceEqual(discSfbData))
                            {
                                physicalDevice = drive;
                                break;
                            }
                            Log.Trace("SFB content check failed, skipping the drive");
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Debug($"Skipping drive {drive}: {e.Message}");
                }
            }
            if (physicalDevice == null)
                throw new AccessViolationException("Couldn't get physical access to the drive");

            Log.Debug($"Selected physical drive {physicalDevice}");
            driveStream = File.Open(physicalDevice, FileMode.Open, FileAccess.Read, FileShare.Read);

            // find disc license file
            discReader = new CDReader(driveStream, true, true);
            FileRecord detectionRecord = null;
            byte[] expectedBytes = null;
            try
            {
                foreach (var path in Detectors.Keys)
                    if (discReader.FileExists(path))
                    {
                        var clusterRange = discReader.PathToClusters(path);
                        detectionRecord = new FileRecord(path, clusterRange.Min(r => r.Offset), discReader.GetFileLength(path));
                        expectedBytes = Detectors[path];
                        if (detectionRecord.Length == 0)
                            continue;
                        
                        Log.Debug($"Using {path} for disc key detection");
                        break;
                    }
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            if (detectionRecord == null)
                throw new FileNotFoundException("Couldn't find a single disc key detection file, please report");

            if (Cts.IsCancellationRequested)
                return;

            SectorSize = discReader.ClusterSize;

            // select decryption key
            driveStream.Seek(detectionRecord.StartSector * discReader.ClusterSize, SeekOrigin.Begin);
            detectionSector = new byte[discReader.ClusterSize];
            detectionBytesExpected = expectedBytes;
            sectorIV = Decrypter.GetSectorIV(detectionRecord.StartSector);
            Log.Debug($"Initialized {nameof(sectorIV)} ({sectorIV?.Length * 8} bit) for sector {detectionRecord.StartSector}: {sectorIV?.ToHexString()}");
            driveStream.ReadExact(detectionSector, 0, detectionSector.Length);
            string discKey = null;
            try
            {
                discKey = untestedKeys.AsParallel().FirstOrDefault(k => !Cts.IsCancellationRequested && IsValidDiscKey(k));
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
            if (discKey == null)
                throw new KeyNotFoundException("No valid disc decryption key was found");

            if (Cts.IsCancellationRequested)
                return;

            lock (AllKnownDiscKeys)
                AllKnownDiscKeys.TryGetValue(discKey, out allMatchingKeys);
            var discKeyInfo = allMatchingKeys?.First();
            DiscKeyFilename = Path.GetFileName(discKeyInfo?.FullPath);
            DiscKeyType = discKeyInfo?.KeyType ?? default;
        }

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

public void DetectDisc(string inDir = "", Func<Dumper, string> outputDirFormatter = null)
        {
            outputDirFormatter ??= d => $"[{d.ProductCode}] {d.replacedle}";
            string discSfbPath = null;
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                var drives = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.CDRom && d.IsReady);
                if (string.IsNullOrEmpty(inDir))
                {
                    foreach (var drive in drives)
                    {
                        discSfbPath = Path.Combine(drive.Name, "PS3_DISC.SFB");
                        if (!File.Exists(discSfbPath))
                            continue;

                        input = drive.Name;
                        Drive = drive.Name[0];
                        break;
                    }
                }
                else
                {
                    discSfbPath = Path.Combine(inDir, "PS3_DISC.SFB");
                    if (File.Exists(discSfbPath))
                    {
                        input = Path.GetPathRoot(discSfbPath);
                        Drive = discSfbPath[0];
                    }
                }
            }
            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                if (string.IsNullOrEmpty(inDir))
                    inDir = "/media";
                discSfbPath = IOEx.GetFilepaths(inDir, "PS3_DISC.SFB", 2).FirstOrDefault();
                if (!string.IsNullOrEmpty(discSfbPath))
                    input = Path.GetDirectoryName(discSfbPath);
            }
            else
                throw new NotImplementedException("Current OS is not supported");

            if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(discSfbPath))
                throw new DriveNotFoundException("No valid PS3 disc was detected. Disc must be detected and mounted.");

            Log.Info("Selected disc: " + input);
            discSfbData = File.ReadAllBytes(discSfbPath);
            var replacedleId = CheckDiscSfb(discSfbData);
            var paramSfoPath = Path.Combine(input, "PS3_GAME", "PARAM.SFO");
            if (!File.Exists(paramSfoPath))
                throw new InvalidOperationException($"Specified folder is not a valid PS3 disc root (param.sfo is missing): {input}");

            using (var stream = File.Open(paramSfoPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                ParamSfo = ParamSfo.ReadFrom(stream);
            CheckParamSfo(ParamSfo);
            if (replacedleId != ProductCode)
                Log.Warn($"Product codes in ps3_disc.sfb ({replacedleId}) and in param.sfo ({ProductCode}) do not match");

            // todo: maybe use discutils instead to read TOC as one block
            var files = IOEx.GetFilepaths(input, "*", SearchOption.AllDirectories);
            DiscFilenames = new List<string>();
            var totalFilesize = 0L;
            var rootLength = input.Length;
            foreach (var f in files)
            {
                try { totalFilesize += new FileInfo(f).Length; } catch { }
                DiscFilenames.Add(f.Substring(rootLength));
            }
            TotalFileSize = totalFilesize;
            TotalFileCount = DiscFilenames.Count;

            OutputDir = new string(outputDirFormatter(this).ToCharArray().Where(c => !InvalidChars.Contains(c)).ToArray());
            Log.Debug($"Output: {OutputDir}");
        }

19 View Source File : Program.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Main(string[] args)
        {
            var consolereplacedle = $"ACEmulator - v{ServerBuildInfo.FullVersion}";

            Console.replacedle = consolereplacedle;

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);

            // Typically, you wouldn't force the current culture on an entire application unless you know sure your application is used in a specific region (which ACE is not)
            // We do this because almost all of the client/user input/output code does not take culture into account, and replacedumes en-US formatting.
            // Without this, many commands that require special characters like , and . will break
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            // Init our text encoding options. This will allow us to use more than standard ANSI text, which the client also supports.
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            // Look for the log4net.config first in the current environment directory, then in the Executingreplacedembly location
            var exeLocation = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);
            var containerConfigDirectory = "/ace/Config";
            var log4netConfig = Path.Combine(exeLocation, "log4net.config");
            var log4netConfigExample = Path.Combine(exeLocation, "log4net.config.example");
            var log4netConfigContainer = Path.Combine(containerConfigDirectory, "log4net.config");

            if (IsRunningInContainer && File.Exists(log4netConfigContainer))
                File.Copy(log4netConfigContainer, log4netConfig, true);

            var log4netFileInfo = new FileInfo("log4net.config");
            if (!log4netFileInfo.Exists)
                log4netFileInfo = new FileInfo(log4netConfig);

            if (!log4netFileInfo.Exists)
            {
                var exampleFile = new FileInfo(log4netConfigExample);
                if (!exampleFile.Exists)
                {
                    Console.WriteLine("log4net Configuration file is missing.  Please copy the file log4net.config.example to log4net.config and edit it to match your needs before running ACE.");
                    throw new Exception("missing log4net configuration file");
                }
                else
                {
                    if (!IsRunningInContainer)
                    {
                        Console.WriteLine("log4net Configuration file is missing,  cloning from example file.");
                        File.Copy(log4netConfigExample, log4netConfig);
                    }
                    else
                    {                        
                        if (!File.Exists(log4netConfigContainer))
                        {
                            Console.WriteLine("log4net Configuration file is missing, ACEmulator is running in a container,  cloning from docker file.");
                            var log4netConfigDocker = Path.Combine(exeLocation, "log4net.config.docker");
                            File.Copy(log4netConfigDocker, log4netConfig);
                            File.Copy(log4netConfigDocker, log4netConfigContainer);
                        }
                        else
                        {
                            File.Copy(log4netConfigContainer, log4netConfig);
                        }

                    }
                }
            }

            var logRepository = LogManager.GetRepository(replacedembly.GetEntryreplacedembly());
            XmlConfigurator.ConfigureAndWatch(logRepository, log4netFileInfo);

            if (Environment.ProcessorCount < 2)
                log.Warn("Only one vCPU was detected. ACE may run with limited performance. You should increase your vCPU count for anything more than a single player server.");

            // Do system specific initializations here
            try
            {
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // On many windows systems, the default resolution for Thread.Sleep is 15.6ms. This allows us to command a tighter resolution
                    MM_BeginPeriod(1);
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }

            log.Info("Starting ACEmulator...");

            if (IsRunningInContainer)
                log.Info("ACEmulator is running in a container...");
            
            var configFile = Path.Combine(exeLocation, "Config.js");
            var configConfigContainer = Path.Combine(containerConfigDirectory, "Config.js");

            if (IsRunningInContainer && File.Exists(configConfigContainer))
                File.Copy(configConfigContainer, configFile, true);

            if (!File.Exists(configFile))
            {
                if (!IsRunningInContainer)
                    DoOutOfBoxSetup(configFile);
                else
                {
                    if (!File.Exists(configConfigContainer))
                    {
                        DoOutOfBoxSetup(configFile);
                        File.Copy(configFile, configConfigContainer);
                    }
                    else
                        File.Copy(configConfigContainer, configFile);
                }
            }

            log.Info("Initializing ConfigManager...");
            ConfigManager.Initialize();

            if (ConfigManager.Config.Server.WorldName != "ACEmulator")
            {
                consolereplacedle = $"{ConfigManager.Config.Server.WorldName} | {consolereplacedle}";
                Console.replacedle = consolereplacedle;
            }

            if (ConfigManager.Config.Offline.PurgeDeletedCharacters)
            {
                log.Info($"Purging deleted characters, and their possessions, older than {ConfigManager.Config.Offline.PurgeDeletedCharactersDays} days ({DateTime.Now.AddDays(-ConfigManager.Config.Offline.PurgeDeletedCharactersDays)})...");
                ShardDatabaseOfflineTools.PurgeCharactersInParallel(ConfigManager.Config.Offline.PurgeDeletedCharactersDays, out var charactersPurged, out var playerBiotasPurged, out var possessionsPurged);
                log.Info($"Purged {charactersPurged:N0} characters, {playerBiotasPurged:N0} player biotas and {possessionsPurged:N0} possessions.");
            }

            if (ConfigManager.Config.Offline.PurgeOrphanedBiotas)
            {
                log.Info($"Purging orphaned biotas...");
                ShardDatabaseOfflineTools.PurgeOrphanedBiotasInParallel(out var numberOfBiotasPurged);
                log.Info($"Purged {numberOfBiotasPurged:N0} biotas.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromFriendLists)
            {
                log.Info($"Pruning invalid friends from all friend lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromFriendLists(out var numberOfFriendsPruned);
                log.Info($"Pruned {numberOfFriendsPruned:N0} invalid friends found on friend lists.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedObjectsFromShortcutBars)
            {
                log.Info($"Pruning invalid shortcuts from all shortcut bars...");
                ShardDatabaseOfflineTools.PruneDeletedObjectsFromShortcutBars(out var numberOfShortcutsPruned);
                log.Info($"Pruned {numberOfShortcutsPruned:N0} deleted objects found on shortcut bars.");
            }

            if (ConfigManager.Config.Offline.PruneDeletedCharactersFromSquelchLists)
            {
                log.Info($"Pruning invalid squelches from all squelch lists...");
                ShardDatabaseOfflineTools.PruneDeletedCharactersFromSquelchLists(out var numberOfSquelchesPruned);
                log.Info($"Pruned {numberOfSquelchesPruned:N0} invalid squelched characters found on squelch lists.");
            }

            if (ConfigManager.Config.Offline.AutoUpdateWorldDatabase)
            {
                CheckForWorldDatabaseUpdate();

                if (ConfigManager.Config.Offline.AutoApplyWorldCustomizations)
                    AutoApplyWorldCustomizations();
            }
            else
                log.Info($"AutoUpdateWorldDatabase is disabled...");

            if (ConfigManager.Config.Offline.AutoApplyDatabaseUpdates)
                AutoApplyDatabaseUpdates();
            else
                log.Info($"AutoApplyDatabaseUpdates is disabled...");

            // This should only be enabled manually. To enable it, simply uncomment this line
            //ACE.Database.OfflineTools.Shard.BiotaGuidConsolidator.ConsolidateBiotaGuids(0xC0000000, out int numberOfBiotasConsolidated, out int numberOfErrors);

            ShardDatabaseOfflineTools.CheckForBiotaPropertiesPaletteOrderColumnInShard();

            // pre-load starterGear.json, abort startup if file is not found as it is required to create new characters.
            if (Factories.StarterGearFactory.GetStarterGearConfiguration() == null)
            {
                log.Fatal("Unable to load or parse starterGear.json. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Initializing ServerManager...");
            ServerManager.Initialize();

            log.Info("Initializing DatManager...");
            DatManager.Initialize(ConfigManager.Config.Server.DatFilesDirectory, true);

            log.Info("Initializing DatabaseManager...");
            DatabaseManager.Initialize();

            if (DatabaseManager.InitializationFailure)
            {
                log.Fatal("DatabaseManager initialization failed. ACEmulator will now abort startup.");
                ServerManager.StartupAbort();
                Environment.Exit(0);
            }

            log.Info("Starting DatabaseManager...");
            DatabaseManager.Start();

            log.Info("Starting PropertyManager...");
            PropertyManager.Initialize();

            log.Info("Initializing GuidManager...");
            GuidManager.Initialize();

            if (ConfigManager.Config.Server.ServerPerformanceMonitorAutoStart)
            {
                log.Info("Server Performance Monitor auto starting...");
                ServerPerformanceMonitor.Start();
            }

            if (ConfigManager.Config.Server.WorldDatabasePrecaching)
            {
                log.Info("Precaching Weenies...");
                DatabaseManager.World.CacheAllWeenies();
                log.Info("Precaching Cookbooks...");
                DatabaseManager.World.CacheAllCookbooks();
                log.Info("Precaching Events...");
                DatabaseManager.World.GetAllEvents();
                log.Info("Precaching House Portals...");
                DatabaseManager.World.CacheAllHousePortals();
                log.Info("Precaching Points Of Interest...");
                DatabaseManager.World.CacheAllPointsOfInterest();
                log.Info("Precaching Spells...");
                DatabaseManager.World.CacheAllSpells();
                log.Info("Precaching Treasures - Death...");
                DatabaseManager.World.CacheAllTreasuresDeath();
                log.Info("Precaching Treasures - Material Base...");
                DatabaseManager.World.CacheAllTreasureMaterialBase();
                log.Info("Precaching Treasures - Material Groups...");
                DatabaseManager.World.CacheAllTreasureMaterialGroups();
                log.Info("Precaching Treasures - Material Colors...");
                DatabaseManager.World.CacheAllTreasureMaterialColor();
                log.Info("Precaching Treasures - Wielded...");
                DatabaseManager.World.CacheAllTreasureWielded();
            }
            else
                log.Info("Precaching World Database Disabled...");

            log.Info("Initializing PlayerManager...");
            PlayerManager.Initialize();

            log.Info("Initializing HouseManager...");
            HouseManager.Initialize();

            log.Info("Initializing InboundMessageManager...");
            InboundMessageManager.Initialize();

            log.Info("Initializing SocketManager...");
            SocketManager.Initialize();

            log.Info("Initializing WorldManager...");
            WorldManager.Initialize();

            log.Info("Initializing EventManager...");
            EventManager.Initialize();

            // Free up memory before the server goes online. This can free up 6 GB+ on larger servers.
            log.Info("Forcing .net garbage collection...");
            for (int i = 0 ; i < 10 ; i++)
                GC.Collect();

            // This should be last
            log.Info("Initializing CommandManager...");
            CommandManager.Initialize();

            if (!PropertyManager.GetBool("world_closed", false).Item)
            {
                WorldManager.Open(null);
            }
        }

19 View Source File : ConfigureSigningCredentials.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static X509KeyStorageFlags GetStorageFlags(KeyDefinition key)
        {
            var x509KeyStorageFlags = (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? X509KeyStorageFlags.PersistKeySet :
                            X509KeyStorageFlags.DefaultKeySet);
            var defaultFlags = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ?
                UnsafeEphemeralKeySet : x509KeyStorageFlags;

            if (key.StorageFlags == null)
            {
                return defaultFlags;
            }

            var flagsList = key.StorageFlags.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            if (flagsList.Length == 0)
            {
                return defaultFlags;
            }

            var result = ParseCurrentFlag(flagsList[0]);
            foreach (var flag in flagsList.Skip(1))
            {
                result |= ParseCurrentFlag(flag);
            }

            return result;

            static X509KeyStorageFlags ParseCurrentFlag(string candidate)
            {
                if (Enum.TryParse<X509KeyStorageFlags>(candidate, out var flag))
                {
                    return flag;
                }
                else
                {
                    throw new InvalidOperationException($"Invalid storage flag '{candidate}'");
                }
            }
        }

19 View Source File : DataProtectionConfiguration.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private static string GetKeysDirectory()
        {
            var environmentVariable = System.Environment.GetEnvironmentVariable("ALTINN_KEYS_DIRECTORY");
            if (!string.IsNullOrWhiteSpace(environmentVariable))
            {
                return environmentVariable;
            }

            // Return a key directory based on the current operating system
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                // This is the default behaviour for keys in Windows.
                return Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "ASP.NET", "DataProtection-Keys");
            }

            // replacedume *nix like systems
            return "/mnt/keys";
        }

See More Examples