System.FormattableString.Invariant(System.FormattableString)

Here are the examples of the csharp api System.FormattableString.Invariant(System.FormattableString) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

554 Examples 7

19 View Source File : DigestAuthenticationMiddleware.cs
License : MIT License
Project Creator : gimlichael

public override async Task InvokeAsync(HttpContext context, INonceTracker di)
        {
            _nonceTracker = di;
            if (!Authenticator.TryAuthenticate(context, Options.RequireSecureConnection, AuthorizationHeaderParser, TryAuthenticate))
            {
                await Decorator.Enclose(context).InvokeAuthenticationAsync(Options, async (message, response) =>
                {
                    context.Response.OnStarting(() =>
                    {
                        string etag = context.Response.Headers[HeaderNames.ETag];
                        if (string.IsNullOrEmpty(etag)) { etag = "no-enreplacedy-tag"; }
                        var opaqueGenerator = Options.OpaqueGenerator;
                        var nonceSecret = Options.NonceSecret;
                        var nonceGenerator = Options.NonceGenerator;
                        var staleNonce = context.Items[DigestFields.Stale] as string ?? "false";
                        context.Response.Headers.Add(HeaderNames.WWWAuthenticate, FormattableString.Invariant($"{DigestAuthorizationHeader.Scheme} realm=\"{Options.Realm}\", qop=\"auth, auth-int\", nonce=\"{nonceGenerator(DateTime.UtcNow, etag, nonceSecret())}\", opaque=\"{opaqueGenerator()}\", stale=\"{staleNonce}\", algorithm=\"{ParseAlgorithm(Options.Algorithm)}\""));
                        return Task.CompletedTask;
                    });
                    response.StatusCode = (int)message.StatusCode;
                    await Decorator.Enclose(response.Body).WriteAllAsync(await message.Content.ReadAsByteArrayAsync().ConfigureAwait(false)).ConfigureAwait(false);
                }).ConfigureAwait(false);
            }
            await Next.Invoke(context).ConfigureAwait(false);
        }

19 View Source File : ImageTagHelper.cs
License : MIT License
Project Creator : gimlichael

public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            output.TagMode = TagMode.StartTagOnly;
            output.TagName = "img";
            if (!string.IsNullOrWhiteSpace(Id)) { output.Attributes.Add("id", Id); }
            if (!string.IsNullOrWhiteSpace(Clreplaced)) { output.Attributes.Add("clreplaced", Clreplaced); }
            output.Attributes.Add("src", string.Concat(Options.GetFormattedBaseUrl(), UseCacheBusting ? FormattableString.Invariant($"{Src}?v={CacheBusting.Version}") : Src));
            if (!string.IsNullOrWhiteSpace(Alt)) { output.Attributes.Add("alt", Alt); }
            if (!string.IsNullOrWhiteSpace(replacedle)) { output.Attributes.Add("replacedle", replacedle); }
            return Task.CompletedTask;
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : coldino

private void CopyTeleport_Click(object sender, RoutedEventArgs e)
        {
            if (sender is MenuItem mi && mi.Parent is ContextMenu cm && cm.PlacementTarget is DataGridRow dgr && dgr.DataContext is DinoViewModel dvm)
            {
                var z = dvm.Dino.Location.Z + Properties.Settings.Default.TeleportHeightOffset;
                var clipboard = "cheat SetPlayerPos ";
                clipboard += System.FormattableString.Invariant($"{dvm.Dino.Location.X:0.00} {dvm.Dino.Location.Y:0.00} {z:0.00}");
                if (Properties.Settings.Default.TeleportFly)
                {
                    clipboard += " | cheat fly";
                    if (Properties.Settings.Default.TeleportGhost)
                        clipboard += " | cheat ghost";
                }

                try
                {
                    Clipboard.SetText(clipboard, TextDataFormat.Text);
                }
                catch (Exception)
                {
                    MessageBox.Show("Failed to set clipboard - is Larkator sandboxed or run as a different user?", "Error setting clipboard", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                    StatusText = "Failed to set clipboard!";
                    return;
                }

                StatusText = "Copied: " + clipboard;
            }
        }

19 View Source File : DbSetExtensions.cs
License : MIT License
Project Creator : findulov

public static IQueryable<TEnreplacedy> Between<TEnreplacedy>(this DbSet<TEnreplacedy> dbSet, DateTimeOffset startDateOffset, DateTimeOffset endDateOffset)
            where TEnreplacedy : clreplaced
        {
            ValidateDbSet(dbSet);

            var sql = FormattableString.Invariant($"SELECT * FROM [{GetTableName(dbSet)}] FOR SYSTEM_TIME BETWEEN {{0}} AND {{1}}");
            return dbSet.FromSqlRaw(sql, startDateOffset, endDateOffset).AsNoTracking();
        }

19 View Source File : CursorHotspot.cs
License : MIT License
Project Creator : csinkers

public override string ToString() => Invariant($"{X} {Y}");

19 View Source File : Config.cs
License : Apache License 2.0
Project Creator : Capnode

public static string Get(string key, string defaultValue = "")
        {
            // special case environment requests
            if (key == "environment") return GetEnvironment();

            var token = GetToken(Settings.Value, key);
            if (token == null)
            {
                Log.Trace(Invariant($"Config.Get(): Configuration key not found. Key: {key} - Using default value: {defaultValue}"));
                return defaultValue;
            }
            return token.ToString();
        }

19 View Source File : TagHelperOptions.cs
License : MIT License
Project Creator : gimlichael

public string GetFormattedBaseUrl()
        {
            var baseUrlIsNullOrEmpty = string.IsNullOrWhiteSpace(BaseUrl);
            var baseUrlWithForwardingSlash = new Stem(BaseUrl).AttachSuffix("/");
            switch (Scheme)
            {
                case ProtocolUriScheme.None:
                    return baseUrlIsNullOrEmpty ? "" : FormattableString.Invariant($"{baseUrlWithForwardingSlash}");
                case ProtocolUriScheme.Http:
                    return baseUrlIsNullOrEmpty ? "" : FormattableString.Invariant($"{nameof(UriScheme.Http).ToLowerInvariant()}://{baseUrlWithForwardingSlash}");
                case ProtocolUriScheme.Https:
                    return baseUrlIsNullOrEmpty ? "" : FormattableString.Invariant($"{nameof(UriScheme.Https).ToLowerInvariant()}://{baseUrlWithForwardingSlash}");
                case ProtocolUriScheme.Relative:
                    return baseUrlIsNullOrEmpty ? "" : FormattableString.Invariant($"//{baseUrlWithForwardingSlash}");
                default:
                    return "";
            }
        }

19 View Source File : LinkMarker.cs
License : MIT License
Project Creator : Blazor-Diagrams

public static LinkMarker NewRectangle(double width, double height)
            => new LinkMarker(FormattableString.Invariant($"M 0 -{height / 2} {width} -{height / 2} {width} {height / 2} 0 {height / 2} z"), width);

19 View Source File : DoubleDecoratorExtensions.cs
License : MIT License
Project Creator : gimlichael

public static TimeSpan ToTimeSpan(this IDecorator<double> decorator, TimeUnit unitOfTime)
        {
            var input = decorator.Inner;
            if (input == 0.0) { return TimeSpan.Zero; }
            switch (unitOfTime)
            {
                case TimeUnit.Days:
                    return TimeSpan.FromDays(input);
                case TimeUnit.Hours:
                    return TimeSpan.FromHours(input);
                case TimeUnit.Minutes:
                    return TimeSpan.FromMinutes(input);
                case TimeUnit.Seconds:
                    return TimeSpan.FromSeconds(input);
                case TimeUnit.Milliseconds:
                    return TimeSpan.FromMilliseconds(input);
                case TimeUnit.Ticks:
                    if (input < long.MinValue || input > long.MaxValue) { throw new OverflowException(FormattableString.Invariant($"The specified input, {input}, having a time unit specified as Ticks cannot be less than {long.MinValue} or be greater than {long.MaxValue}.")); }
                    if (input == long.MaxValue) { return TimeSpan.MaxValue; } 
                    if (input == long.MinValue) { return TimeSpan.MinValue; } 
                    return TimeSpan.FromTicks((long)input);
                default:
                    throw new InvalidEnumArgumentException(nameof(unitOfTime), (int)unitOfTime, typeof(TimeUnit));
            }
        }

19 View Source File : PathGenerators.Smooth.cs
License : MIT License
Project Creator : Blazor-Diagrams

private static PathGeneratorResult CurveThroughPoints(Point[] route, BaseLinkModel link)
        {
            double? sourceAngle = null;
            double? targetAngle = null;

            if (link.SourceMarker != null)
            {
                sourceAngle = SourceMarkerAdjustement(route, link.SourceMarker.Width);
            }

            if (link.TargetMarker != null)
            {
                targetAngle = TargetMarkerAdjustement(route, link.TargetMarker.Width);
            }

            BezierSpline.GetCurveControlPoints(route, out var firstControlPoints, out var secondControlPoints);
            var paths = new string[firstControlPoints.Length];

            for (var i = 0; i < firstControlPoints.Length; i++)
            {
                var cp1 = firstControlPoints[i];
                var cp2 = secondControlPoints[i];
                paths[i] = FormattableString.Invariant($"M {route[i].X} {route[i].Y} C {cp1.X} {cp1.Y}, {cp2.X} {cp2.Y}, {route[i + 1].X} {route[i + 1].Y}");
            }

            // Todo: adjust marker positions based on closest control points
            return new PathGeneratorResult(paths, sourceAngle, route[0], targetAngle, route[^1]);
        }

19 View Source File : DbSetExtensions.cs
License : MIT License
Project Creator : findulov

public static IQueryable<TEnreplacedy> AsOf<TEnreplacedy>(this DbSet<TEnreplacedy> dbSet, DateTimeOffset dateTimeOffset)
            where TEnreplacedy : clreplaced
        {
            ValidateDbSet(dbSet);

            var sql = FormattableString.Invariant($"SELECT * FROM [{GetTableName(dbSet)}] FOR SYSTEM_TIME AS OF {{0}}");
            return dbSet.FromSqlRaw(sql, dateTimeOffset).AsNoTracking();
        }

19 View Source File : NTCrypto.cs
License : MIT License
Project Creator : Dionach

public static Dictionary<uint, byte[]> DecryptPekList(byte[] systemKey, byte[] encryptedPekListBlob)
        {
            if (systemKey.Length != 16)
            {
                throw new ArgumentOutOfRangeException(nameof(systemKey));
            }

            var version = BitConverter.ToUInt32(encryptedPekListBlob, 0);
            if (!Enum.IsDefined(typeof(PekListVersion), version))
            {
                throw new ArgumentOutOfRangeException(nameof(encryptedPekListBlob), Invariant($"PEK List version \"{version}\" is not supported."));
            }

            var flags = BitConverter.ToUInt32(encryptedPekListBlob, 4);
            if (!Enum.IsDefined(typeof(PekListFlags), flags))
            {
                throw new ArgumentOutOfRangeException(nameof(encryptedPekListBlob), Invariant($"PEK List flags value \"{version}\" is not supported."));
            }

            var salt = encryptedPekListBlob.Skip(8).Take(16).ToArray();
            var encryptedPekList = encryptedPekListBlob.Skip(24).ToArray();
            byte[] decryptedPekList = null;

            switch ((PekListFlags)flags)
            {
                case PekListFlags.ClearText:
                    decryptedPekList = encryptedPekList;
                    break;

                case PekListFlags.Encrypted:
                    switch ((PekListVersion)version)
                    {
                        case PekListVersion.Windows2000:
                            decryptedPekList = DecryptDataUsingRc4AndSalt(systemKey, salt, encryptedPekList, 1000);
                            break;

                        case PekListVersion.Windows2016:
                            decryptedPekList = DecryptDataUsingAes(systemKey, salt, encryptedPekList).ToArray();
                            break;
                    }

                    break;
            }

            return ParsePekList(decryptedPekList);
        }

19 View Source File : ZipStreamWriter.cs
License : Apache License 2.0
Project Creator : Capnode

private void CopyTempFile(int attempts, bool throwOnFailure)
        {
            if (!File.Exists(_tempFilename)) return;

            do
            {
                try
                {
                    File.Copy(_tempFilename, _filename, true);
                    return;
                }
                catch (Exception err)
                {
                    Log.Error(err);
                }
            }
            while (--attempts > 0);

            if (throwOnFailure)
            {
                throw new InvalidOperationException(Invariant($"Unable to save file: {_filename} after {attempts} attempts."));
            }
        }

19 View Source File : BasicAuthenticationMiddleware.cs
License : MIT License
Project Creator : gimlichael

public override async Task InvokeAsync(HttpContext context)
        {
            if (!Authenticator.TryAuthenticate(context, Options.RequireSecureConnection, AuthorizationHeaderParser, TryAuthenticate))
            {
                await Decorator.Enclose(context).InvokeAuthenticationAsync(Options, async (message, response) =>
                {
                    context.Response.OnStarting(() =>
                    {
                        context.Response.Headers.Add(HeaderNames.WWWAuthenticate, FormattableString.Invariant($"{BasicAuthorizationHeader.Scheme} realm=\"{Options.Realm}\""));
                        return Task.CompletedTask;
                    });
                    response.StatusCode = (int)message.StatusCode;
                    await Decorator.Enclose(response.Body).WriteAllAsync(await message.Content.ReadAsByteArrayAsync().ConfigureAwait(false)).ConfigureAwait(false);
                }).ConfigureAwait(false);
            }
            await Next(context).ConfigureAwait(false);
        }

19 View Source File : LinkMarker.cs
License : MIT License
Project Creator : Blazor-Diagrams

public static LinkMarker NewArrow(double width, double height)
            => new LinkMarker(FormattableString.Invariant($"M 0 -{height / 2} {width} 0 0 {height / 2}"), width);

19 View Source File : DigestAuthorizationHeaderBuilder.cs
License : MIT License
Project Creator : gimlichael

public virtual string ComputeHash2(string method, string enreplacedyBody = null)
        {
            Validator.ThrowIfNullOrWhitespace(method, nameof(method));
            method = method.ToUpperInvariant();
            ValidateData(DigestFields.QualityOfProtection, DigestFields.DigestUri);
            var qop = Data[DigestFields.QualityOfProtection];
            var hasIntegrityProtection = qop.Equals("auth-int", StringComparison.OrdinalIgnoreCase);
            if (hasIntegrityProtection && enreplacedyBody == null) { throw new ArgumentNullException(nameof(enreplacedyBody), "The enreplacedy body cannot be null when qop is set to auth-int."); }

            var hashFields = !hasIntegrityProtection
                ? FormattableString.Invariant($"{method}:{Data[DigestFields.DigestUri]}")
                : FormattableString.Invariant($"{method}:{Data[DigestFields.DigestUri]}:{UnkeyedHashFactory.CreateCrypto(Algorithm).ComputeHash(enreplacedyBody, o => o.Encoding = Encoding.UTF8).ToHexadecimalString()}");
            return UnkeyedHashFactory.CreateCrypto(Algorithm).ComputeHash(hashFields, o =>
            {
                o.Encoding = Encoding.UTF8;
            }).ToHexadecimalString();
        }

19 View Source File : Cropper.razor.cs
License : MIT License
Project Creator : Chronostasys

private string GetCropperStyle(double top, double left, double height, double width)
        {
            return FormattableString.Invariant($"top:{top}px;left:{left}px;height:{height}px;width:{width}px;");
        }

19 View Source File : TypeDecoratorExtensions.cs
License : MIT License
Project Creator : gimlichael

public static MethodBase MatchMember(this IDecorator<Type> decorator, string memberName, Action<MethodBaseOptions> setup = null)
        {
            Validator.ThrowIfNullOrWhitespace(memberName, nameof(memberName));
            var options = Patterns.Configure(setup);
            var methods = decorator.Inner.GetMethods(options.Flags).Where(info => info.Name.Equals(memberName, options.Comparison)).ToList();
            var matchedMethod = Parse(methods, options.Types);
            if (matchedMethod != null) { return matchedMethod; }
            throw new AmbiguousMatchException(FormattableString.Invariant($"Ambiguous matching in method resolution. Found {methods.Count} matching the member name of {memberName}. Consider specifying the signature of the member."));
        }

19 View Source File : BarCodeFieldDefaultCommand.cs
License : MIT License
Project Creator : BinaryKits

public override string ToZpl()
        {
            return Invariant($"{this.CommandPrefix}{this.ModuleWidth},{this.WideBarToNarrowBarWidthRatio:0.0},{this.BarCodeHeight}");
        }

19 View Source File : PropertyInfoDecoratorExtensions.cs
License : MIT License
Project Creator : gimlichael

public static bool IsAutoProperty(this IDecorator<PropertyInfo> decorator)
        {
            Validator.ThrowIfNull(decorator, nameof(decorator));
            var hasGetMethodWithAttribute = decorator.Inner.GetMethod != null && decorator.Inner.GetMethod.GetCustomAttribute<CompilerGeneratedAttribute>() != null;
            var hreplacedetMethodWithAttribute = decorator.Inner.SetMethod != null && decorator.Inner.SetMethod.GetCustomAttribute<CompilerGeneratedAttribute>() != null;
            if (hasGetMethodWithAttribute || hreplacedetMethodWithAttribute)
            {
                return decorator.Inner.DeclaringType != null && decorator.Inner.DeclaringType.GetFields(new MemberReflection(excludeInheritancePath: true)).Any(f => f.Name.Contains(FormattableString.Invariant($"<{decorator.Inner.Name}>")));
            }
            return false;
        }

19 View Source File : EventNode.cs
License : MIT License
Project Creator : csinkers

public virtual string ToString(int idOffset)
        {
            int id = Id - idOffset;
            int? next = Next?.Id - idOffset;
            return Invariant($"{(DirectSequence ? " " : "#")}{id}=>{next?.ToString(CultureInfo.InvariantCulture) ?? "!"}: {Event}");
        }

19 View Source File : WaveLibWavLoader.cs
License : MIT License
Project Creator : csinkers

static WaveLib Write(WaveLib existing, replacedetInfo info, ISerializer s, IJsonUtil jsonUtil)
        {
            if (existing == null) throw new ArgumentNullException(nameof(existing));

            PackedChunks.PackNamed(s, WaveLib.MaxSamples, i =>
            {
                var sample = existing.Samples[i];
                if (!sample.Active)
                    return (Array.Empty<byte>(), null);

                string extension = Invariant($"i{sample.Instrument}t{sample.Type}");
                var pattern = info.Get(replacedetProperty.Pattern, "{0}_{1}_{2}.dat");
                var name = info.BuildFilename(pattern, i, extension);
                var bytes= FormatUtil.SerializeToBytes(s2 => WavLoader.Serdes(sample, null, null, s2, jsonUtil));
                return (bytes, name);
            });
            return existing;
        }

19 View Source File : SelectionBoxWidget.razor.cs
License : MIT License
Project Creator : Blazor-Diagrams

private string GenerateStyle()
            => FormattableString.Invariant($"position: absolute; background: {Background}; top: {_selectionBoxTopLeft.Y}px; left: {_selectionBoxTopLeft.X}px; width: {_selectionBoxSize.Width}px; height: {_selectionBoxSize.Height}px;");

19 View Source File : ConverterUtils.cs
License : MIT License
Project Creator : dapr

public static string ConvertTimeSpanValueInDaprFormat(TimeSpan? value)
        {
            // write in format expected by Dapr, it only accepts h, m, s, ms, us(micro), ns
            var stringValue = string.Empty;
            if (value.Value >= TimeSpan.Zero)
            {
                var hours = (value.Value.Days * 24) + value.Value.Hours;
                stringValue = FormattableString.Invariant($"{hours}h{value.Value.Minutes}m{value.Value.Seconds}s{value.Value.Milliseconds}ms");
            }

            return stringValue;
        }

19 View Source File : PathGenerators.Straight.cs
License : MIT License
Project Creator : Blazor-Diagrams

public static PathGeneratorResult Straight(Diagram _, BaseLinkModel link, Point[] route, Point source, Point target)
        {
            route = ConcatRouteAndSourceAndTarget(route, source, target);
            double? sourceAngle = null;
            double? targetAngle = null;

            if (link.SourceMarker != null)
            {
                sourceAngle = SourceMarkerAdjustement(route, link.SourceMarker.Width);
            }

            if (link.TargetMarker != null)
            {
                targetAngle = TargetMarkerAdjustement(route, link.TargetMarker.Width);
            }

            var paths = new string[route.Length - 1];
            for (var i = 0; i < route.Length - 1; i++)
            {
                paths[i] = FormattableString.Invariant($"M {route[i].X} {route[i].Y} L {route[i + 1].X} {route[i + 1].Y}");
            }

            return new PathGeneratorResult(paths, sourceAngle, route[0], targetAngle, route[^1]);
        }

19 View Source File : DbSetExtensions.cs
License : MIT License
Project Creator : findulov

public static IQueryable<TEnreplacedy> AsOf<TEnreplacedy>(this DbSet<TEnreplacedy> dbSet, DateTime date)
            where TEnreplacedy : clreplaced
        {
            ValidateDbSet(dbSet);

            var sql = FormattableString.Invariant($"SELECT * FROM [{GetTableName(dbSet)}] FOR SYSTEM_TIME AS OF {{0}}");
            return dbSet.FromSqlRaw(sql, date).AsNoTracking();
        }

19 View Source File : NTCrypto.cs
License : MIT License
Project Creator : Dionach

public static byte[] DecryptSecret(Dictionary<uint, byte[]> pekList, byte[] encryptedBlob)
        {
            var algorithm = BitConverter.ToUInt16(encryptedBlob, 0);
            if (!Enum.IsDefined(typeof(EncryptionType), algorithm))
            {
                throw new ArgumentOutOfRangeException(nameof(encryptedBlob), Invariant($"Algorithm \"{algorithm}\" is not supported."));
            }

            var pekId = BitConverter.ToUInt32(encryptedBlob, 4);
            var pek = pekList[pekId];

            var salt = encryptedBlob.Skip(8).Take(16).ToArray();
            var encryptedData = encryptedBlob.Skip(24).ToArray();

            switch ((EncryptionType)algorithm)
            {
                case EncryptionType.PekWithRc4AndSalt:
                    return DecryptDataUsingRc4AndSalt(pek, salt, encryptedData, 1);

                case EncryptionType.PekWithAes:
                    // When using AES, data is padded and the first 4 bytes contains the actual data length
                    var length = BitConverter.ToUInt32(encryptedData, 0);
                    encryptedData = encryptedData.Skip(4).ToArray();
                    return DecryptDataUsingAes(pek, salt, encryptedData).Take((int)length).ToArray();

                default:
                    throw new ArgumentOutOfRangeException(nameof(encryptedBlob), Invariant($"Encryption type \"{(EncryptionType)algorithm}\" is not supported."));
            }
        }

19 View Source File : StringExtensions.cs
License : Apache License 2.0
Project Creator : Capnode

public static string Invariant(FormattableString formattable)
        {
            return FormattableString.Invariant(formattable);
        }

19 View Source File : DbSetExtensions.cs
License : MIT License
Project Creator : findulov

public static IQueryable<TEnreplacedy> Between<TEnreplacedy>(this DbSet<TEnreplacedy> dbSet, DateTime startDate, DateTime endDate)
            where TEnreplacedy : clreplaced
        {
            ValidateDbSet(dbSet);

            var sql = FormattableString.Invariant($"SELECT * FROM [{GetTableName(dbSet)}] FOR SYSTEM_TIME BETWEEN {{0}} AND {{1}}");
            return dbSet.FromSqlRaw(sql, startDate, endDate).AsNoTracking();
        }

19 View Source File : BaseLinkModelExtensions.cs
License : MIT License
Project Creator : Blazor-Diagrams

private static string GetCurvePoint(double pX, double pY, double cX, double cY, PortAlignment? alignment)
        {
            var margin = Math.Min(_margin, Math.Pow(Math.Pow(pX - cX, 2) + Math.Pow(pY - cY, 2), .5));
            return alignment switch
            {
                PortAlignment.Top => FormattableString.Invariant($"{pX} {Math.Min(pY - margin, cY)}"),
                PortAlignment.Bottom => FormattableString.Invariant($"{pX} {Math.Max(pY + margin, cY)}"),
                PortAlignment.TopRight => FormattableString.Invariant($"{Math.Max(pX + margin, cX)} {Math.Min(pY - margin, cY)}"),
                PortAlignment.BottomRight => FormattableString.Invariant($"{Math.Max(pX + margin, cX)} {Math.Max(pY + margin, cY)}"),
                PortAlignment.Right => FormattableString.Invariant($"{Math.Max(pX + margin, cX)} {pY}"),
                PortAlignment.Left => FormattableString.Invariant($"{Math.Min(pX - margin, cX)} {pY}"),
                PortAlignment.BottomLeft => FormattableString.Invariant($"{Math.Min(pX - margin, cX)} {Math.Max(pY + margin, cY)}"),
                PortAlignment.TopLeft => FormattableString.Invariant($"{Math.Min(pX - margin, cX)} {Math.Min(pY - margin, cY)}"),
                _ => FormattableString.Invariant($"{cX} {cY}"),
            };

19 View Source File : DbSetExtensions.cs
License : MIT License
Project Creator : findulov

private static void ValidateDbSet<TEnreplacedy>(DbSet<TEnreplacedy> dbSet)
            where TEnreplacedy : clreplaced
        {
            var enreplacedyType = GetEnreplacedyType(dbSet);
            if (!TemporalEnreplacediesCache.IsEnreplacedyConfigurationTemporal(enreplacedyType))
            {
                throw new ArgumentException(FormattableString.Invariant($"The enreplacedy '{enreplacedyType.DisplayName()}' is not using temporal tables."), nameof(dbSet));
            }
        }

19 View Source File : Config.cs
License : Apache License 2.0
Project Creator : Capnode

public static void SetConfigurationFile(string fileName)
        {
            if (File.Exists(fileName))
            {
                Log.Trace(Invariant($"Using {fileName} as configuration file"));
                ConfigurationFileName = fileName;
            }
            else
            {
                Log.Error(Invariant($"Configuration file {fileName} does not exist, using {ConfigurationFileName}"));
            }
        }

19 View Source File : BasicAuthenticationMiddleware.cs
License : MIT License
Project Creator : gimlichael

private bool TryAuthenticate(HttpContext context, BasicAuthorizationHeader header, out ClaimsPrincipal result)
        {
            if (Options.Authenticator == null) { throw new InvalidOperationException(FormattableString.Invariant($"The {nameof(Options.Authenticator)} cannot be null.")); }
            result = Options.Authenticator(header.UserName, header.Preplacedword);
            return Condition.IsNotNull(result);
        }

19 View Source File : ConversionViewModel.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

protected async void OnBaseQuotesUpdatedEventHandler(object sender, EventArgs args)
        {
            if (!(sender is ICurrencyQuotesProvider provider))
                return;

            if (_currencyCode == null || _targetCurrencyCode == null || _baseCurrencyCode == null)
                return;

            var fromCurrencyPrice = provider.GetQuote(_currencyCode, _baseCurrencyCode)?.Bid ?? 0m;
            _amountInBase = _amount * fromCurrencyPrice;

            var fromCurrencyFeePrice = provider.GetQuote(FromCurrency.FeeCurrencyName, _baseCurrencyCode)?.Bid ?? 0m;
            _estimatedPaymentFeeInBase = _estimatedPaymentFee * fromCurrencyFeePrice;

            var toCurrencyFeePrice = provider.GetQuote(ToCurrency.FeeCurrencyName, _baseCurrencyCode)?.Bid ?? 0m;
            _estimatedRedeemFeeInBase = _estimatedRedeemFee * toCurrencyFeePrice;

            var toCurrencyPrice = provider.GetQuote(TargetCurrencyCode, _baseCurrencyCode)?.Bid ?? 0m;
            _rewardForRedeemInBase = _rewardForRedeem * toCurrencyPrice;

            _estimatedMakerNetworkFeeInBase = _estimatedMakerNetworkFee * fromCurrencyPrice;

            _estimatedTotalNetworkFeeInBase =
                _estimatedPaymentFeeInBase +
                (!_hasRewardForRedeem ? _estimatedRedeemFeeInBase : 0) +
                _estimatedMakerNetworkFeeInBase +
                (_hasRewardForRedeem ? _rewardForRedeemInBase : 0);

            if (_amountInBase != 0 && _estimatedTotalNetworkFeeInBase / _amountInBase > 0.3m)
            {
                _isCriticalWarning = true;
                _warning = string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.CvTooHighNetworkFee,
                    FormattableString.Invariant($"{_estimatedTotalNetworkFeeInBase:$0.00}"),
                    FormattableString.Invariant($"{_estimatedTotalNetworkFeeInBase / _amountInBase:0.00%}"));
            }
            else if (_amountInBase != 0 && _estimatedTotalNetworkFeeInBase / _amountInBase > 0.1m)
            {
                _isCriticalWarning = false;
                _warning = string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.CvSufficientNetworkFee,
                    FormattableString.Invariant($"{_estimatedTotalNetworkFeeInBase:$0.00}"),
                    FormattableString.Invariant($"{_estimatedTotalNetworkFeeInBase / _amountInBase:0.00%}"));
            }

            _canConvert = _amountInBase == 0 || _estimatedTotalNetworkFeeInBase / _amountInBase <= 0.75m;

            if (Application.Current.Dispatcher != null)
            {
                await Application.Current.Dispatcher.InvokeAsync(() =>
                {
                    OnPropertyChanged(nameof(AmountInBase));
                    OnPropertyChanged(nameof(EstimatedPaymentFeeInBase));
                    OnPropertyChanged(nameof(EstimatedRedeemFeeInBase));
                    OnPropertyChanged(nameof(RewardForRedeemInBase));

                    OnPropertyChanged(nameof(EstimatedMakerNetworkFeeInBase));
                    OnPropertyChanged(nameof(EstimatedTotalNetworkFeeInBase));

                    OnPropertyChanged(nameof(IsCriticalWarning));
                    OnPropertyChanged(nameof(Warning));
                    OnPropertyChanged(nameof(CanConvert));

                    UpdateTargetAmountInBase(provider);

                }, DispatcherPriority.Background);
            }
        }

19 View Source File : DigestAuthenticationMiddleware.cs
License : MIT License
Project Creator : gimlichael

private bool TryAuthenticate(HttpContext context, DigestAuthorizationHeader header, out ClaimsPrincipal result)
        {
            if (Options.Authenticator == null) { throw new InvalidOperationException(FormattableString.Invariant($"The {nameof(Options.Authenticator)} delegate cannot be null.")); }

            if (header == null)
            {
                result = null;
                return false;
            }

            result = null;
            var nonceExpiredParser = Options.NonceExpiredParser;
            var staleNonce = nonceExpiredParser(header.Nonce, TimeSpan.FromSeconds(30));
            if (staleNonce)
            {
                context.Items.Add(DigestFields.Stale, "true");
                return false;
            }

            if (_nonceTracker != null)
            {
                var nc = Convert.ToInt32(header.NC, 16);
                if (_nonceTracker.TryGetEntry(header.Nonce, out var previousNonce))
                {
                    if (previousNonce.Count == nc)
                    {
                        context.Items.Add(DigestFields.Stale, "true");
                        return false;
                    }
                }
                else
                {
                    _nonceTracker.TryAddEntry(header.Nonce, nc);
                }
            }

            result = Options.Authenticator(header.UserName, out var preplacedword);

            var db = new DigestAuthorizationHeaderBuilder().AddFromDigestAuthorizationHeader(header);
            var ha1 = db.ComputeHash1(preplacedword);
            var ha2 = db.ComputeHash2(context.Request.Method, Decorator.Enclose(context.Request.Body).ToEncodedString(o => o.LeaveOpen = true));
            var serverResponse = db.ComputeResponse(ha1, ha2);

            return serverResponse != null && serverResponse.Equals(header.Response, StringComparison.Ordinal) && Condition.IsNotNull(result);
        }

19 View Source File : Config.cs
License : Apache License 2.0
Project Creator : Capnode

public static T GetValue<T>(string key, T defaultValue = default(T))
        {
            // special case environment requests
            if (key == "environment" && typeof (T) == typeof (string)) return (T) (object) GetEnvironment();

            var token = GetToken(Settings.Value, key);
            if (token == null)
            {
                var defaultValueString = defaultValue is IConvertible
                    ? ((IConvertible) defaultValue).ToString(CultureInfo.InvariantCulture)
                    : defaultValue is IFormattable
                        ? ((IFormattable) defaultValue).ToString(null, CultureInfo.InvariantCulture)
                        : Invariant($"{defaultValue}");

                Log.Trace(Invariant($"Config.GetValue(): {key} - Using default value: {defaultValueString}"));
                return defaultValue;
            }

            var type = typeof(T);
            string value;
            try
            {
                value = token.Value<string>();
            }
            catch (Exception)
            {
                value = token.ToString();
            }

            if (type.IsEnum)
            {
                return (T) Enum.Parse(type, value, true);
            }

            if (typeof(IConvertible).IsreplacedignableFrom(type))
            {
                return (T) Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
            }

            // try and find a static parse method
            try
            {
                var parse = type.GetMethod("Parse", new[]{typeof(string)});
                if (parse != null)
                {
                    var result = parse.Invoke(null, new object[] {value});
                    return (T) result;
                }
            }
            catch (Exception err)
            {
                Log.Trace(Invariant($"Config.GetValue<{typeof(T).Name}>({key},{defaultValue}): Failed to parse: {value}. Using default value."));
                Log.Error(err);
                return defaultValue;
            }

            try
            {
                return JsonConvert.DeserializeObject<T>(value);
            }
            catch (Exception err)
            {
                Log.Trace(Invariant($"Config.GetValue<{typeof(T).Name}>({key},{defaultValue}): Failed to JSON deserialize: {value}. Using default value."));
                Log.Error(err);
                return defaultValue;
            }
        }

19 View Source File : CdnTagHelper.cs
License : MIT License
Project Creator : gimlichael

protected virtual string GetBaseUrl()
        {
            var baseUrlIsNullOrEmpty = string.IsNullOrWhiteSpace(Options.BaseUrl);
            var baseUrlWithForwardingSlash = new Stem(Options.BaseUrl).AttachSuffix("/");
            switch (Options.Scheme)
            {
                case ProtocolUriScheme.None:
                    return baseUrlIsNullOrEmpty ? "" : FormattableString.Invariant($"{baseUrlWithForwardingSlash}");
                case ProtocolUriScheme.Http:
                    return baseUrlIsNullOrEmpty ? "" : FormattableString.Invariant($"{nameof(UriScheme.Http).ToLowerInvariant()}://{baseUrlWithForwardingSlash}");
                case ProtocolUriScheme.Https:
                    return baseUrlIsNullOrEmpty ? "" : FormattableString.Invariant($"{nameof(UriScheme.Https).ToLowerInvariant()}://{baseUrlWithForwardingSlash}");
                case ProtocolUriScheme.Relative:
                    return baseUrlIsNullOrEmpty ? "" : FormattableString.Invariant($"//{baseUrlWithForwardingSlash}");
                default:
                    return "";
            }
        }

19 View Source File : LinkMarker.cs
License : MIT License
Project Creator : Blazor-Diagrams

public static LinkMarker NewCircle(double r)
            => new LinkMarker(FormattableString.Invariant($"M 0, 0 a {r},{r} 0 1,0 {r * 2},0 a {r},{r} 0 1,0 -{r * 2},0"), r * 2);

19 View Source File : ProcessInfo.cs
License : MIT License
Project Creator : gimlichael

public override string ToString()
        {
            var builder = new StringBuilder();
            try
            {
                builder.Append(FormattableString.Invariant($"Id: {Process.Id}"));
                builder.Append(Alphanumeric.CaretChar);
                builder.Append(FormattableString.Invariant($"Name: {Process.ProcessName}"));
                builder.Append(Alphanumeric.CaretChar);
                builder.Append(FormattableString.Invariant($"PriorityClreplaced: {Process.PriorityClreplaced}"));
                builder.Append(Alphanumeric.CaretChar);
                builder.Append(FormattableString.Invariant($"HandleCount: {Process.HandleCount}"));
                builder.Append(Alphanumeric.CaretChar);
                builder.Append(FormattableString.Invariant($"ThreadCount: {Process.Threads.Count}"));
                builder.Append(Alphanumeric.CaretChar);
                builder.Append(FormattableString.Invariant($"WorkingSet64: {ByteStorageCapacity.FromBytes(Process.WorkingSet64, o => o.Prefix = UnitPrefix.Decimal)}"));
                builder.Append(Alphanumeric.CaretChar);
                builder.Append(FormattableString.Invariant($"TotalWorkingSet64: {ByteStorageCapacity.FromBytes(Process.GetProcesses().Select(p => p.WorkingSet64).Sum(), o => o.Prefix = UnitPrefix.Decimal)}"));
                builder.Append(Alphanumeric.CaretChar);
                builder.Append(FormattableString.Invariant($"TotalProcessorTime: {Process.TotalProcessorTime.ToString("G", CultureInfo.InvariantCulture)}"));
            }
            catch (Exception)
            {
                // ignore platform exceptions and the likes hereof
            }
            return builder.ToString();
        }

19 View Source File : Cropper.razor.cs
License : MIT License
Project Creator : Chronostasys

private string GetCroppedImgStyle(double top, double right, double bottom, double left)
        {
            return FormattableString.Invariant($"clip: rect({top}px, {right}px, {bottom}px, {left}px);");
        }

19 View Source File : HmacAuthenticationMiddleware.cs
License : MIT License
Project Creator : gimlichael

private bool TryAuthenticate(HttpContext context, HmacAuthorizationHeader header, out ClaimsPrincipal result)
        {
            if (Options.Authenticator == null) { throw new InvalidOperationException(FormattableString.Invariant($"The {nameof(Options.Authenticator)} cannot be null.")); }

            if (header == null)
            {
                result = null;
                return false;
            }

            var requestBodyMd5 = context.Request.Headers[HeaderNames.ContentMD5].FirstOrDefault()?.ToLowerInvariant();
            if (!string.IsNullOrWhiteSpace(requestBodyMd5) && !UnkeyedHashFactory.CreateCrypto(UnkeyedCryptoAlgorithm.Md5).ComputeHash(context.Request.Body).ToHexadecimalString().Equals(requestBodyMd5, StringComparison.Ordinal))
            {
                result = null;
                return false;
            }
            
            var clientId = header.ClientId;
            result = Options.Authenticator(clientId, out var clientSecret);
            if (clientSecret == null)
            {
                result = null;
                return false;
            }
            var signature = header.Signature;

            var hb = new HmacAuthorizationHeaderBuilder(Options.AuthenticationScheme)
                .AddCredentialScope(header.CredentialScope)
                .AddClientId(clientId)
                .AddClientSecret(clientSecret)
                .AddSignedHeaders(header.SignedHeaders)
                .AddFromRequest(context.Request);

            var computedSignature = hb.ComputeSignature();
            return computedSignature != null && signature.Equals(computedSignature, StringComparison.Ordinal) && Condition.IsNotNull(result);
        }

19 View Source File : UnixHelperProcess.cs
License : MIT License
Project Creator : asmichi

public static UnixHelperProcess Launch(int maxSubchannelCount)
        {
            if (maxSubchannelCount < 1)
            {
                throw new ArgumentException("maxSubchannelCount must be greater than 0.", nameof(maxSubchannelCount));
            }

            var pipePath = UnixFilePal.CreateUniqueSocketPath();

            using var listeningSocket = UnixFilePal.CreateListeningDomainSocket(pipePath, 1);
            var psi = new ProcessStartInfo(HelperPath, Invariant($"\"{pipePath}\""))
            {
                RedirectStandardInput = true,
                RedirectStandardError = false,
                RedirectStandardOutput = false,
                UseShellExecute = false,
            };

            var process = Process.Start(psi);
            process.StandardInput.Close();

            var mainChannel = WaitForConnection(process, listeningSocket);

            return new UnixHelperProcess(process, mainChannel, maxSubchannelCount);

            static Socket WaitForConnection(Process process, Socket listeningSocket)
            {
                Span<byte> helloBuf = stackalloc byte[HelperHello.Length];

                for (int i = 0; i < HelperConnectionPollingCount; i++)
                {
                    if (listeningSocket.Poll(HelperConnectionPollingIntervalMicroSeconds, SelectMode.SelectRead))
                    {
                        var socket = listeningSocket.Accept();
                        int bytes = socket.Receive(helloBuf);
                        if (bytes != HelperHello.Length)
                        {
                            socket.Dispose();
                            continue;
                        }
                        return socket;
                    }

                    if (process.WaitForExit(0))
                    {
                        throw new AsmichiChildProcessLibraryCrashedException(CurrentCulture($"The helper process died with exit code {process.ExitCode}."));
                    }
                }

                throw new AsmichiChildProcessInternalLogicErrorException("The helper process did not connect to this process.");
            }
        }

19 View Source File : LinkTagHelper.cs
License : MIT License
Project Creator : gimlichael

public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            output.TagMode = TagMode.StartTagOnly;
            output.TagName = "link";
            output.Attributes.Add("rel", Rel);
            output.Attributes.Add("href", string.Concat(Options.GetFormattedBaseUrl(), UseCacheBusting ? FormattableString.Invariant($"{Href}?v={CacheBusting.Version}") : Href));
            if (!string.IsNullOrWhiteSpace(Type)) { output.Attributes.Add("type", new HtmlString(Type)); }
            return Task.CompletedTask;
        }

19 View Source File : BranchNode.cs
License : MIT License
Project Creator : csinkers

public override string ToString(int idOffset)
        {
            var id = Id - idOffset;
            var ifTrue = (Next?.Id - idOffset)?.ToString(CultureInfo.InvariantCulture) ?? "!";
            var ifFalse = (NextIfFalse?.Id - idOffset)?.ToString(CultureInfo.InvariantCulture) ?? "!";
            return Invariant($"!{id}?{ifTrue}:{ifFalse}: {Event}");
        }

19 View Source File : PathGenerators.Smooth.cs
License : MIT License
Project Creator : Blazor-Diagrams

public static PathGeneratorResult Smooth(Diagram _, BaseLinkModel link, Point[] route, Point source, Point target)
        {
            route = ConcatRouteAndSourceAndTarget(route, source, target);

            if (route.Length > 2)
                return CurveThroughPoints(route, link);

            route = GetRouteWithCurvePoints(link, route);
            double? sourceAngle = null;
            double? targetAngle = null;

            if (link.SourceMarker != null)
            {
                sourceAngle = SourceMarkerAdjustement(route, link.SourceMarker.Width);
            }

            if (link.TargetMarker != null)
            {
                targetAngle = TargetMarkerAdjustement(route, link.TargetMarker.Width);
            }

            var path = FormattableString.Invariant($"M {route[0].X} {route[0].Y} C {route[1].X} {route[1].Y}, {route[2].X} {route[2].Y}, {route[3].X} {route[3].Y}");
            return new PathGeneratorResult(new[] { path }, sourceAngle, route[0], targetAngle, route[^1]);
        }

19 View Source File : OptionsBuilder.cs
License : MIT License
Project Creator : aivascu

public virtual object Build(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (!typeof(DbContext).IsreplacedignableFrom(type) || type.IsAbstract)
            {
                throw new ArgumentException(Invariant($"The context type should be a non-abstract clreplaced inherited from {typeof(DbContext)}"), nameof(type));
            }

            var methods = this.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);

            var genericConfigureMethod = Array
                .Find(methods, m => m.Name == nameof(Build) && m.IsGenericMethodDefinition)
                .MakeGenericMethod(type);

            return genericConfigureMethod.Invoke(this, Array.Empty<object>());
        }

19 View Source File : WindowsVersion.cs
License : MIT License
Project Creator : asmichi

private static unsafe bool GetIsWindows1809()
        {
            // Resort to ntdll. OsGetVersionEx and hence Environment.OSVersion.Version (till .NET Core 3.1)
            // will always return Windows 8.1 if the app is not manifested to support newer versions.
            // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getversionexw
            // https://github.com/dotnet/runtime/pull/33651
            var osvi = default(NtDll.RTL_OSVERSIONINFOW);
            osvi.dwOSVersionInfoSize = (uint)sizeof(NtDll.RTL_OSVERSIONINFOW);
            int ntstatus = NtDll.RtlGetVersion(ref osvi);
            if (ntstatus < 0)
            {
                throw new AsmichiChildProcessInternalLogicErrorException(Invariant($"RtlGetVersion failed (0x{ntstatus:X})."));
            }

            return osvi.dwPlatformId == 2
                && osvi.dwMajorVersion == 10
                && osvi.dwMinorVersion == 0
                && osvi.dwBuildNumber == 17763;
        }

19 View Source File : BaseLinkModelExtensions.cs
License : MIT License
Project Creator : Blazor-Diagrams

public static string GenerateCurvedPath(this BaseLinkModel link)
        {
            var sX = link.GetMiddleSourceX();
            var sY = link.GetMiddleSourceY();
            double tX, tY;

            if (link.IsAttached)
            {
                tX = link.GetMiddleTargetX();
                tY = link.GetMiddleTargetY();
            }
            else
            {
                tX = link.OnGoingPosition!.X;
                tY = link.OnGoingPosition.Y;
            }

            var cX = (sX + tX) / 2;
            var cY = (sY + tY) / 2;

            var curvePointA = GetCurvePoint(sX, sY, cX, cY, link.SourcePort.Alignment);
            var curvePointB = GetCurvePoint(tX, tY, cX, cY, link.TargetPort?.Alignment);
            return FormattableString.Invariant($"M {sX} {sY} C {curvePointA}, {curvePointB}, {tX} {tY}");
        }

19 View Source File : JSRuntimeUnhandledInvocationException.cs
License : MIT License
Project Creator : bUnit-dev

private static string CreateErrorMessage(JSRuntimeInvocation invocation)
		{
			var sb = new StringBuilder();
			sb.AppendLine("bUnit's JSInterop has not been configured to handle the call:");
			sb.AppendLine();

			if (invocation.IsVoidResultInvocation)
			{
				sb.AppendLine(FormattableString.Invariant($"    {invocation.InvocationMethodName}({GetArguments(invocation)})"));
			}
			else
			{
				sb.AppendLine(FormattableString.Invariant($"    {invocation.InvocationMethodName}<{GetGenericInvocationArguments(invocation)}>({GetArguments(invocation)})"));
			}

			sb.AppendLine();
			sb.AppendLine("Configure bUnit's JSInterop to handle the call with following:");
			sb.AppendLine();

			if (IsImportModuleInvocation(invocation))
			{
				sb.AppendLine(FormattableString.Invariant($"    SetupModule({GetArguments(invocation, includeIdentifier: false)})"));
			}
			else
			{
				if (invocation.IsVoidResultInvocation)
				{
					sb.AppendLine(FormattableString.Invariant($"    SetupVoid({GetArguments(invocation)})"));
				}
				else
				{
					sb.AppendLine(FormattableString.Invariant($"    Setup<{GetReturnTypeName(invocation.ResultType)}>({GetArguments(invocation)})"));
				}

				if (invocation.Arguments.Any())
				{
					sb.AppendLine("or the following, to match any arguments:");
					if (invocation.IsVoidResultInvocation)
						sb.AppendLine(FormattableString.Invariant($"    SetupVoid(\"{invocation.Identifier}\", _ => true)"));
					else
						sb.AppendLine(FormattableString.Invariant($"    Setup<{GetReturnTypeName(invocation.ResultType)}>(\"{invocation.Identifier}\", _ => true)"));
				}
			}

			sb.AppendLine();
			sb.AppendLine("The setup methods are available on an instance of the BunitJSInterop or");
			sb.AppendLine("BunitJSModuleInterop type. The standard BunitJSInterop is available");
			sb.AppendLine("through the TestContext.JSInterop property, and a BunitJSModuleInterop");
			sb.AppendLine("instance is returned from calling SetupModule on a BunitJSInterop instance.");
			return sb.ToString();
		}

19 View Source File : SystemHive.cs
License : MIT License
Project Creator : Dionach

public static byte[] LoadSystemKeyFromHive(string systemHivePath)
        {
            systemHivePath = systemHivePath ?? throw new ArgumentNullException(nameof(systemHivePath));

            // Load the registry hive
            var hive = new RegistryHiveOnDemand(systemHivePath);

            // Get the current control set version from the hive
            var currentControlSetVersion = int.Parse(hive.GetKey("Select").Values[0].ValueData, CultureInfo.InvariantCulture);

            // Get the clreplaced name of the four subkeys in which the sytem key is stored, and convert to hex to get the scrambled system key
            var scrambledKeyList = new List<byte>();

            foreach (var keyName in new string[] { "JD", "Skew1", "GBG", "Data" })
            {
                var key = hive.GetKey(Invariant($"ControlSet00{currentControlSetVersion}\\Control\\Lsa\\{keyName}"));
                var clreplacedName = key.ClreplacedName;
                scrambledKeyList.AddRange(Enumerable.Range(0, clreplacedName.Length / 2).Select(x => Convert.ToByte(clreplacedName.Substring(x * 2, 2), 16)).ToArray());
            }

            var scrambledKey = scrambledKeyList.ToArray();

            // Unscramble the system key based on the known transforms
            var systemKeyList = new List<byte>();

            for (var i = 0; i < scrambledKey.Length; i++)
            {
                systemKeyList.Add(scrambledKey[SYSTEMKEYTRANSFORMS[i]]);
            }

            return systemKeyList.ToArray();
        }

See More Examples