System.Collections.Generic.IEnumerable.First(System.Func)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.First(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2913 Examples 7

19 View Source File : TestContractTestBase.cs
License : MIT License
Project Creator : AElfProject

protected async Task InitializeTestContracts()
        {
            //initialize token
            {
                var createResult = await TokenContractStub.Create.SendAsync(new CreateInput()
                {
                    Symbol = "ELF",
                    Decimals = 8,
                    IsBurnable = true,
                    TokenName = "elf token",
                    TotalSupply = Supply * 10,
                    Issuer = DefaultSender,
                    LockWhiteList =
                    {
                        TokenConverterContractAddress,
                        TreasuryContractAddress
                    }
                });
                CheckResult(createResult.TransactionResult);

                var issueResult = await TokenContractStub.Issue.SendAsync(new IssueInput()
                {
                    Symbol = "ELF",
                    Amount = Supply / 2,
                    To = DefaultSender,
                    Memo = "Set for token converter."
                });
                CheckResult(issueResult.TransactionResult);

                foreach (var resourceRelatedNativeToken in NativTokenToSourceSymbols)
                {
                    createResult = await TokenContractStub.Create.SendAsync(new CreateInput()
                    {
                        Symbol = resourceRelatedNativeToken,
                        Decimals = 8,
                        IsBurnable = true,
                        TokenName = resourceRelatedNativeToken + " elf token",
                        TotalSupply = Supply * 10,
                        Issuer = DefaultSender,
                        LockWhiteList =
                        {
                            TokenConverterContractAddress,
                            TreasuryContractAddress
                        }
                    });
                    CheckResult(createResult.TransactionResult);
                    issueResult = await TokenContractStub.Issue.SendAsync(new IssueInput()
                    {
                        Symbol = resourceRelatedNativeToken,
                        Amount = Supply / 2,
                        To = DefaultSender,
                        Memo = $"Set for {resourceRelatedNativeToken} token converter."
                    });
                    CheckResult(issueResult.TransactionResult);
                }
                foreach (var symbol in ResourceTokenSymbols)
                {
                    var resourceCreateResult = await TokenContractStub.Create.SendAsync(new CreateInput
                    {
                        Symbol = symbol,
                        TokenName = $"{symbol} Token",
                        TotalSupply = ResourceTokenTotalSupply,
                        Decimals = 8,
                        Issuer = DefaultSender,
                        IsBurnable = true,
                        LockWhiteList =
                        {
                            TokenConverterContractAddress,
                            TreasuryContractAddress
                        }
                    });
                    CheckResult(resourceCreateResult.TransactionResult);

                    var resourceIssueResult = await TokenContractStub.Issue.SendAsync(new IssueInput
                    {
                        Symbol = symbol,
                        To = TokenConverterContractAddress,
                        Amount = ResourceTokenTotalSupply,
                        Memo = "Initialize for resources trade"
                    });
                    CheckResult(resourceIssueResult.TransactionResult);
                }
            }
            
            //initialize parliament
            {
                var result = await ParliamentContractStub.Initialize.SendAsync(new Contracts.Parliament.InitializeInput());
                CheckResult(result.TransactionResult);
            }

            //initialize token converter
            {
                var connectors = new List<Connector>();
                var elfConnector = new Connector
                {
                    Symbol = "ELF",
                    IsPurchaseEnabled = true,
                    IsVirtualBalanceEnabled = true,
                    Weight = "0.5",
                    VirtualBalance = VirtualElfSupplyToken
                };
                connectors.Add(elfConnector);
                foreach (var resourceRelatedNativeToken in NativTokenToSourceSymbols)
                {
                    elfConnector = new Connector
                    {
                        Symbol = resourceRelatedNativeToken,
                        IsPurchaseEnabled = true,
                        IsVirtualBalanceEnabled = true,
                        Weight = "0.5",
                        VirtualBalance = VirtualElfSupplyToken
                    };
                    elfConnector.RelatedSymbol = ResourceTokenSymbols.First(x => elfConnector.Symbol.Contains(x));
                    connectors.Add(elfConnector);
                }
                foreach (var symbol in ResourceTokenSymbols)
                {
                    var connector = new Connector
                    {
                        Symbol = symbol,
                        VirtualBalance = ResourceTokenTotalSupply,
                        Weight = "0.5",
                        IsPurchaseEnabled = true,
                        IsVirtualBalanceEnabled = false
                    };
                    connector.RelatedSymbol = NativTokenToSourceSymbols.First(x => x.Contains(connector.Symbol));
                    connectors.Add(connector);
                }

                await TokenConverterContractStub.Initialize.SendAsync(new InitializeInput
                {
                    FeeRate = "0.005",
                    Connectors = {connectors},
                    BaseTokenSymbol = "ELF",
                });
            }

            //initialize treasury contract
            {
                await TreasuryContractStub.InitialTreasuryContract.SendAsync(new Empty());
                await TreasuryContractStub.InitialMiningRewardProfireplacedem.SendAsync(new Empty());
            }
            
            // initialize AEDPos
            {
                await InitializeAElfConsensus();
            }
        }

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

private static Type GetOptionsType(Enreplacedy.ExternalProvider externalProvider)
        {            
            var typeName = $"{typeof(RemoteAuthenticationOptions).Namespace}.{externalProvider.KindName}Options";
            var replacedembly = AppDomain.CurrentDomain.Getreplacedemblies().First(a => a.GetType(typeName) != null);
            return replacedembly.GetType(typeName);
        }

19 View Source File : SubscriberWorker.cs
License : MIT License
Project Creator : ad313

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine($"{DateTime.Now} ----------------------------------------");

            foreach (var channel in AopSubscriberAttribute.ChannelList)
            {
                Console.WriteLine($"{DateTime.Now} AopCache:生产者频道:{channel}");

                var methodList = AopSubscriberAttribute.MethodList.Where(d =>
                    d.GetCustomAttributes<AopSubscriberAttribute>().ToList().Exists(t => t.Channel == channel)).ToList();

                var subscribers = new List<(AopCacheAttribute, AopSubscriberAttribute)>();

                foreach (var method in methodList)
                {
                    var cacheAttribute = method.GetCustomAttribute<AopCacheAttribute>();
                    if (cacheAttribute == null)
                        continue;

                    Console.WriteLine($"{DateTime.Now} AopCache:消费者订阅方法:{method.DeclaringType?.FullName}.{method.Name}");

                    var subscriberTag = method.GetCustomAttributes<AopSubscriberAttribute>().First(d => d.Channel == channel);

                    subscribers.Add((cacheAttribute, subscriberTag));
                }

                ChannelSubscribersDictionary.Add(channel, subscribers);

                Console.WriteLine($"{DateTime.Now} ----------------------------------------");
            }

            //开始订阅
            foreach (var keyValuePair in ChannelSubscribersDictionary)
            {
                _eventBusProvider.Subscribe<Dictionary<string, object>>(keyValuePair.Key, msg =>
                {
                    foreach ((AopCacheAttribute cache, AopSubscriberAttribute sub) item in keyValuePair.Value)
                    {
                        var cacheAttribute = item.cache;
                        var subscriberTag = item.sub;

                        switch (subscriberTag.ActionType)
                        {
                            case ActionType.DeleteByKey:

                                var key = subscriberTag.GetKey(cacheAttribute.Key, msg.Data);
                                key = cacheAttribute.FormatPrefix(key);
                                _cacheProvider.Remove(key);
                                Console.WriteLine($"{DateTime.Now} Key:{msg.Key}:清除缓存:{key}");
                                break;
                            //case ActionType.DeleteByGroup:
                            //    break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                    }
                }, true);
            }

            await Task.CompletedTask;
        }

19 View Source File : Notifiaction.xaml.cs
License : GNU General Public License v3.0
Project Creator : aduskin

private void NoticeGrid_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (e.NewSize.Height != 0.0)
                return;
            var element = sender as Grid;
            RemoveNotification(NotifiactionList.First(n => n.Id == Int32.Parse(element.Tag.ToString())));
        }

19 View Source File : PrimeFactory.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat

public static int GetIndexFromValue(BigInteger value)
		{
			if (value == -1)
			{
				return -1;
			}
			if (primesLast < value)
			{
				IncreaseMaxValue(value);
			}

			BigInteger primeValue = primes.First(p => p >= value);

			int index = primes.IndexOf(primeValue) + 1;
			return index;
		}

19 View Source File : BankIdSimulatedApiClient.cs
License : MIT License
Project Creator : ActiveLogin

private async Task EnsureNoExistingAuth(string personalIdenreplacedyNumber)
        {
            if (_auths.Any(x => x.Value.PersonalIdenreplacedyNumber == personalIdenreplacedyNumber))
            {
                var existingAuthOrderRef = _auths.First(x => x.Value.PersonalIdenreplacedyNumber == personalIdenreplacedyNumber).Key;
                await CancelAsync(new CancelRequest(existingAuthOrderRef)).ConfigureAwait(false);

                throw new BankIdApiException(ErrorCode.AlreadyInProgress, "A login for this user is already in progress.");
            }
        }

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

private void replacedysis_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "SpreadSheets (*.xlsx) | *.xlsx";
            dialog.Multiselect = false;

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    SpreadsheetDoreplacedent spreadsheetDoreplacedent = SpreadsheetDoreplacedent.Open(dialog.FileName, false);
                    workbookPart = spreadsheetDoreplacedent.WorkbookPart;
                }
                catch
                {
                    System.Windows.MessageBox.Show("The specification file is open in a other process");
                }

                SheetData sheetData = null;

                try
                {
                    Sheet sheet = workbookPart.Workbook.Sheets.ChildElements.Cast<Sheet>().First(x => x.Name == "replacedembly Specification");
                    int index = workbookPart.WorksheetParts.ToList().IndexOf(workbookPart.WorksheetParts.Last()) - workbookPart.Workbook.Sheets.ToList().IndexOf(sheet);
                    sheetData = workbookPart.WorksheetParts.ElementAt(index).Worksheet.Elements<SheetData>().First();
                }
                catch
                {
                    System.Windows.MessageBox.Show("Invalid specification file :\nCouldn't find the 'replacedembly Specification' worksheet");
                }

                List<Row> rows = sheetData.Elements<Row>().ToList();
                List<Cell> headerRow = rows.First().Elements<Cell>().ToList();
                rows.RemoveAll(x => !x.Elements<Cell>().Any(y => !string.IsNullOrEmpty(TextInCell(y))));

                string replacedemblyName;

                if (headerRow.Any(x => TextInCell(x) == "Signed"))
                {
                    List<SignatureSpecification> sigspecs = new List<SignatureSpecification>();
                    int sigIndex = headerRow.IndexOf(headerRow.First(x => TextInCell(x) == "Signed"));

                    foreach (Row r in rows)
                    {
                        List<Cell> row = r.Elements<Cell>().ToList();
                        replacedemblyName = TextInCell(row.ElementAt(0));
                        sigspecs.Add(new SignatureSpecification(replacedemblyName, TextInCell(row.ElementAt(sigIndex)) == "x"));
                    }

                    Signaturereplacedyzer sigreplacedyzer = new Signaturereplacedyzer();
                    sigreplacedyzer.replacedyze(Model, sigspecs);
                }

                if (headerRow.Any(x => TextInCell(x) == "Obfuscated"))
                {
                    List<ObfuscationSpecification> obfuscationspecs = new List<ObfuscationSpecification>();
                    int obIndex = headerRow.IndexOf(headerRow.First(x => TextInCell(x) == "Obfuscated"));

                    foreach (Row r in rows)
                    {
                        List<Cell> row = r.Elements<Cell>().ToList();
                        replacedemblyName = TextInCell(row.ElementAt(0));
                        obfuscationspecs.Add(new ObfuscationSpecification(replacedemblyName, TextInCell(row.ElementAt(obIndex)) == "x"));
                    }

                    Obfuscationreplacedyzer obfuscationreplacedyzer = new Obfuscationreplacedyzer();
                    obfuscationreplacedyzer.replacedyze(Model, obfuscationspecs);
                }

                Model.SoftwareComponents.Where(x => x.Name != "System replacedemblies").ToList().ForEach(x => ModelCommonDataOrganizer.UpdateGroups(Model, x));
                UpdateTreeView();
                UpdateErrorNodes(GraphViewer.Graph);
                replacedysis.Visibility = Visibility.Hidden;
            }
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : 71

internal static MemberInfo GetMember(this Type type, string name)
        {
            return type.GetTypeInfo().DeclaredMembers.First(x => x.Name == name);
        }

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

private async Task ValidateRequestAsync(IEnumerable<string> apis, IEnumerable<string> scopes, ClaimsPrincipal user, string clientId)
        {
            var client = await _clientStore.FindEnabledClientByIdAsync(user.Claims.First(c => c.Type == "client_id").Value).ConfigureAwait(false);
            if (client == null)
            {
                throw new InvalidOperationException($"Client not found for client id '{clientId}'.");
            }

            var apiList = await _resourceStore.FindApiScopesByNameAsync(apis).ConfigureAwait(false);
            foreach (var api in apis)
            {
                if (!apiList.Any(a => a.Name == api))
                {
                    throw new InvalidOperationException($"Api '{api}' not found.");
                }
            }

            var allowedScopes = client.AllowedScopes;
            foreach (var scope in scopes)
            {
                if (!allowedScopes.Any(s => s == scope))
                {
                    throw new InvalidOperationException($"Scope '{scope}' not found in '{clientId}' allowed scopes.");
                }
            }
        }

19 View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1

public WorkbookStream ObfuscateAutoOpen(string localizedLabel = "Auto_Open")
        {
            Random randomUnicodeChar = new Random();
            string[] badUnicodeChars = { "\ufefe", "\uffff", "\ufeff", "\ufffe", "\uffef", "\ufff0", "\ufff1", "\ufff6", "\ufefd", "\u0000", "\udddd" };
            int indexLabel = 0;
            string unicodeLabelWithBadChars = "";
            List<Lbl> labels = GetAllRecordsByType<Lbl>();
            Lbl autoOpenLbl = labels.First(l => l.fBuiltin && l.Name.Value.Equals("\u0001") ||
                                                l.Name.Value.ToLower().StartsWith(localizedLabel.ToLower()));
            Lbl replaceLabelStringLbl = ((BiffRecord)autoOpenLbl.Clone()).AsRecordType<Lbl>();

            //Characters that work
            //fefe, ffff, feff, fffe, ffef, fff0, fff1, fff6, fefd, 0000, dddd
            //Pretty much any character that is invalid unicode - though \ucccc doesn't seem to work - need better criteria for parsing

            foreach (char localizedLabelChar in localizedLabel)
            {
                indexLabel = randomUnicodeChar.Next(localizedLabel.Length);
                for (var i = 0; i < 10; i += 1)
                {
                    unicodeLabelWithBadChars += badUnicodeChars[indexLabel];
                }
                unicodeLabelWithBadChars += localizedLabelChar;
            }
            replaceLabelStringLbl.SetName(new XLUnicodeStringNoCch(unicodeLabelWithBadChars, true));
            replaceLabelStringLbl.fBuiltin = false;

            // Hidden removes from the label manager entirely, but doesn't seem to work if fBuiltin is false
            // replaceLabelStringLbl.fHidden = true;

            WorkbookStream obfuscatedStream = ReplaceRecord(autoOpenLbl, replaceLabelStringLbl);
            obfuscatedStream = obfuscatedStream.FixBoundSheetOffsets();
            return obfuscatedStream;
        }

19 View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio

public static Enreplacedy GetSharePointSiteFromUrl(this OrganizationServiceContext context, Uri absoluteUrl)
		{
			var sharePointSites = context.CreateQuery("sharepointsite").Where(site => site.GetAttributeValue<int?>("statecode") == 0).ToArray(); // all active sites

			var siteUrls = new Dictionary<Guid, string>();

			foreach (var sharePointSite in sharePointSites)
			{
				var siteUrl = sharePointSite.GetAttributeValue<string>("absoluteurl") ?? string.Empty;

				var parentSiteReference = sharePointSite.GetAttributeValue<EnreplacedyReference>("parentsite");

				if (parentSiteReference != null)
				{
					var parentSite = sharePointSites.FirstOrDefault(site => site.Id == parentSiteReference.Id);

					if (parentSite != null)
					{
						siteUrl = "{0}/{1}".FormatWith(parentSite.GetAttributeValue<string>("absoluteurl").TrimEnd('/'), sharePointSite.GetAttributeValue<string>("relativeurl"));
					}
				}

				siteUrls.Add(sharePointSite.Id, siteUrl);
			}

			var siteKeyAndUrl = siteUrls.Select(pair => pair as KeyValuePair<Guid, string>?)
				.FirstOrDefault(pair => string.Equals(pair.Value.Value.TrimEnd('/'), absoluteUrl.ToString().TrimEnd('/'), StringComparison.InvariantCultureIgnoreCase));

			if (siteKeyAndUrl == null)
			{
				throw new ApplicationException("Couldn't find an active SharePoint site with the URL {0}.".FormatWith(absoluteUrl));
			}

			return sharePointSites.First(site => site.Id == siteKeyAndUrl.Value.Key);
		}

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio

public static T? GetAttribute<T>(this XElement element, XName name, IDictionary<T, string> lookup) where T : struct
		{
			var attribute = element.Attribute(name);

			if (attribute != null)
			{
				var value = lookup.First(pair => pair.Value == attribute.Value);

				return value.Key;
			}

			return null;
		}

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task SetCIEnv()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                var existingCI = Environment.GetEnvironmentVariable("CI");
                try
                {
                    // Clear out CI and make sure process invoker sets it.
                    Environment.SetEnvironmentVariable("CI", null);

                    Tracing trace = hc.GetTrace();

                    Int32 exitCode = -1;
                    var processInvoker = new ProcessInvokerWrapper();
                    processInvoker.Initialize(hc);
                    var stdout = new List<string>();
                    var stderr = new List<string>();
                    processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
                    {
                        trace.Info(e.Data);
                        stdout.Add(e.Data);
                    };
                    processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
                    {
                        trace.Info(e.Data);
                        stderr.Add(e.Data);
                    };
#if OS_WINDOWS
                    exitCode = await processInvoker.ExecuteAsync("", "cmd.exe", "/c \"echo %CI%\"", null, CancellationToken.None);
#else
                    exitCode = await processInvoker.ExecuteAsync("", "bash", "-c \"echo $CI\"", null, CancellationToken.None);
#endif

                    trace.Info("Exit Code: {0}", exitCode);
                    replacedert.Equal(0, exitCode);

                    replacedert.Equal("true", stdout.First(x => !string.IsNullOrWhiteSpace(x)));
                }
                finally
                {
                    Environment.SetEnvironmentVariable("CI", existingCI);
                }
            }
        }

19 View Source File : HostSmartContractBridgeContext.cs
License : MIT License
Project Creator : AElfProject

public Address ConvertVirtualAddressToContractAddressWithContractHashName(Hash virtualAddress,
            Address contractAddress)
        {
            var systemHashName = GetSystemContractNameToAddressMapping().First(kv => kv.Value == contractAddress).Key;
            return Address.FromPublicKey(systemHashName.Value.Concat(virtualAddress.Value.ToByteArray().ComputeHash())
                .ToArray());
        }

19 View Source File : DispatchPacketToCommand.cs
License : MIT License
Project Creator : 499116344

public IPacketCommand dispatch_receive_packet(QQCommand command)
        {
            var types = replacedembly.GetExecutingreplacedembly().GetTypes();
            foreach (var type in types)
            {
                var attributes = type.GetCustomAttributes();
                if (!attributes.Any(attr => attr is ReceivePacketCommand))
                {
                    continue;
                }

                var attribute = attributes.First(attr => attr is ReceivePacketCommand) as ReceivePacketCommand;
                if (attribute.Command == command)
                {
                    var receivePacket =
                        Activator.CreateInstance(type, _data, _service, _transponder, _user) as IPacketCommand;
                    return receivePacket;
                }
            }

            return new DefaultReceiveCommand(_data, _service, _transponder, _user);
        }

19 View Source File : BaseNoteVisual.cs
License : MIT License
Project Creator : Aeroluna

private static void Postfix(BaseNoteVisuals __instance, NoteControllerBase ____noteController)
        {
            GameObject gameObject = __instance.gameObject;

            BaseNoteVisuals baseNoteVisuals = gameObject.GetComponent<BaseNoteVisuals>();
            CutoutAnimateEffect cutoutAnimateEffect = _noteCutoutAnimateEffectAccessor(ref baseNoteVisuals);
            CutoutEffect[] cutoutEffects = _cutoutEffectAccessor(ref cutoutAnimateEffect);
            CutoutEffect cutoutEffect = cutoutEffects.First(n => n.name != "NoteArrow"); // 1.11 NoteArrow has been added to the CutoutAnimateEffect and we don't want that
            CutoutManager.NoteCutoutEffects.Add(____noteController, new CutoutEffectWrapper(cutoutEffect));

            if (____noteController is ICubeNoteTypeProvider)
            {
                Type constructed = typeof(DisappearingArrowControllerBase<>).MakeGenericType(____noteController.GetType());
                MonoBehaviour disappearingArrowController = (MonoBehaviour)gameObject.GetComponent(constructed);
                MethodInfo method = GetSetArrowTransparency(disappearingArrowController.GetType());
                DisappearingArrowWrapper wrapper = new DisappearingArrowWrapper(disappearingArrowController, method);
                wrapper.SetCutout(1); // i have no replaced idea how this fixes the weird ghost arrow bug
                CutoutManager.NoteDisappearingArrowWrappers.Add(____noteController, wrapper);
            }
        }

19 View Source File : GrandIdSimulatedApiClient.cs
License : MIT License
Project Creator : ActiveLogin

private async Task EnsureNoExistingLogin(string personalIdenreplacedyNumber)
        {
            if (_bankidFederatedLogins.Any(x => x.Value.PersonalIdenreplacedyNumber == personalIdenreplacedyNumber))
            {
                var existingLoginSessionId = _bankidFederatedLogins.First(x => x.Value.PersonalIdenreplacedyNumber == personalIdenreplacedyNumber).Key;
                await LogoutAsync(new LogoutRequest(existingLoginSessionId)).ConfigureAwait(false);

                throw new GrandIdApiException(ErrorCode.Already_In_Progress, "A login for this user is already in progress.");
            }
        }

19 View Source File : AgoraServiceImplementation.cs
License : MIT License
Project Creator : AgoraIO-Community

public virtual void FirstRemoteVideoDecodedOfUid(AgoraRtcEngineKit engine, nuint uid, CoreGraphics.CGSize size, nint elapsed)
        {
            var id = (uint)uid;
            _knownStreams.Add(id);
            if (!_containers.Any(a => a.StreamUID == id))
            {
                if (_containers.Any(a => a.StreamUID == AgoraService.UnknownRemoteStreamId))
                {
                    var viewHolder = _containers.First(a => a.StreamUID == AgoraService.UnknownRemoteStreamId);
                    viewHolder.StreamUID = id;
                    viewHolder.VideoView.IsOffline = false;
                }
                else
                {
                    OnNewStream(id, (int)size.Width, (int)size.Height);
                }
            }
        }

19 View Source File : JwtCredentialBuilder.cs
License : MIT License
Project Creator : 17MKH

public async Task<IResultModel> Build(List<Claim> claims)
    {
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_options.Key));
        var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var jwtSecurityToken = new JwtSecurityToken(_options.Issuer, _options.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(_options.Expires), signingCredentials);
        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        _logger.LogDebug("生成AccessToken:{token}", token);

        var result = new JwtResultModel
        {
            AccountId = Guid.Parse(claims.First(m => m.Type == MkhClaimTypes.ACCOUNT_ID).Value),
            Platform = claims.First(m => m.Type == MkhClaimTypes.PLATFORM).Value.ToInt(),
            AccessToken = token,
            ExpiresIn = (_options.Expires < 0 ? 120 : _options.Expires) * 60,
            RefreshToken = Guid.NewGuid().ToString().Replace("-", "")
        };

        //存储令牌信息
        await _tokenStorageProvider.Save(result, claims);

        return ResultModel.Success(result);
    }

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

public async Task<string> CreatePersonalAccessTokenAsync(HttpContext context,
            bool isRefenceToken,
            int lifetimeDays,
            IEnumerable<string> apis, 
            IEnumerable<string> scopes, 
            IEnumerable<string> claimTypes)
        {
            CheckParams(apis);

            scopes ??= Array.Empty<string>();
            claimTypes ??= Array.Empty<string>();

            claimTypes = claimTypes.Where(c => c != JwtClaimTypes.Name &&
                c != JwtClaimTypes.ClientId &&
                c != JwtClaimTypes.Subject);

            var user = new ClaimsPrincipal(new ClaimsIdenreplacedy(context.User.Claims.Select(c =>
            {
                if (JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.TryGetValue(c.Type, out string newType))
                {
                    return new Claim(newType, c.Value);
                }
                return c;
            }), "Bearer", JwtClaimTypes.Name, JwtClaimTypes.Role));

            var clientId = user.Claims.First(c => c.Type == JwtClaimTypes.ClientId).Value;
            await ValidateRequestAsync(apis, scopes, user, clientId).ConfigureAwait(false);

            var issuer = context.GetIdenreplacedyServerIssuerUri();
            var sub = user.FindFirstValue(JwtClaimTypes.Subject) ?? user.FindFirstValue("nameid");
            var userName = user.Idenreplacedy.Name;

            return await _tokenService.CreateSecurityTokenAsync(new Token(IdenreplacedyServerConstants.TokenTypes.AccessToken)
            {
                AccessTokenType = isRefenceToken ? AccessTokenType.Reference : AccessTokenType.Jwt,
                Audiences = apis.ToArray(),
                ClientId = clientId,
                Claims = user.Claims.Where(c => claimTypes.Any(t => c.Type == t))
                    .Concat(new[]
                    {
                        new Claim(JwtClaimTypes.Name, userName),
                        new Claim(JwtClaimTypes.ClientId, clientId),
                        new Claim(JwtClaimTypes.Subject, sub)
                    })
                    .Concat(scopes.Select(s => new Claim("scope", s)))
                    .ToArray(),
                CreationTime = DateTime.UtcNow,
                Lifetime = Convert.ToInt32(TimeSpan.FromDays(lifetimeDays).TotalSeconds),
                Issuer = issuer
            });
        }

19 View Source File : RasterCache.cs
License : MIT License
Project Creator : adamped

public void Prepare(PrerollContext context, Layer layer, SKMatrix ctm)
        {
            RasterCacheKey<Layer> cache_key = new RasterCacheKey<Layer>(layer, ctm);
            Entry entry = layer_cache_.First(x=>x == cache_key).id(); // I used Linq, that aint going to be good for performance
         
            entry.access_count = GlobalMembers.ClampSize(entry.access_count + 1, 0, threshold_);
            entry.used_this_frame = true;
            if (!entry.image.is_valid)
            {
                entry.image = GlobalMembers.Rasterize(context.gr_context, ctm, context.dst_color_space, checkerboard_images_, layer.paint_bounds(), (SKCanvas canvas) =>
                {
                    Layer.PaintContext paintContext = new Layer.PaintContext(canvas, null, context.texture_registry, context.raster_cache, context.checkerboard_offscreen_layers);
                    layer.Paint(paintContext);
                });
            }
        }

19 View Source File : RasterCache.cs
License : MIT License
Project Creator : adamped

public RasterCacheResult Get(SKPicture picture, SKMatrix ctm)
        {
            var cache_key = new RasterCacheKey<UniqueEntry>(new UniqueEntry(picture.UniqueId), ctm);
            var it = picture_cache_.First(x => x.Equals(cache_key));
            return it == picture_cache_.Last() ? new RasterCacheResult() : new RasterCacheResult(); // This aint right;
        }

19 View Source File : Fuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private static string FindTheNameOfTheTestInvolved()
        {
            var testName = "(not found)";
            try
            {
                var stackTrace = new StackTrace();

                var testMethod = stackTrace.GetFrames().Select(sf => sf.GetMethod()).First(IsATestMethod);

                testName = $"{testMethod.DeclaringType.Name}.{testMethod.Name}";
            }
            catch
            {
            }

            return testName;
        }

19 View Source File : WebsiteIdeaUserAggregationDataAdapter.cs
License : MIT License
Project Creator : Adoxio

private static IEnumerable<Enreplacedy> CreateIdeaEnreplacediesFromAliasedValues(IEnumerable<Enreplacedy> results)
		{
			var ideas = results
				.Select(result =>
				{
					var idea = new Enreplacedy("adx_idea");

					foreach (var attribute in result.Attributes.Where(attribute => attribute.Value is AliasedValue && attribute.Key.StartsWith("idea.")))
					{
						idea[attribute.Key.Substring(5)] = ((AliasedValue)attribute.Value).Value;
					}

					idea.Id = idea.GetAttributeValue<Guid>("adx_ideaid");

					return idea;
				}).ToArray();

			var distinctIdeaIds = ideas.Select(e => e.Id).Distinct();
			var distinctIdeas = distinctIdeaIds.Select(id => ideas.First(idea => idea.Id == id));

			return distinctIdeas;
		}

19 View Source File : WorkbookStream.cs
License : Apache License 2.0
Project Creator : aaaddress1

public WorkbookStream ObfuscateAutoOpen(string localizedLabel = "Auto_Open")
        {
            Random randomUnicodeChar = new Random();
            string[] badUnicodeChars = { "\ufefe", "\uffff", "\ufeff", "\ufffe", "\uffef", "\ufff0", "\ufff1", "\ufff6", "\ufefd", "\u0000", "\udddd" };
            int indexLabel = 0;
            string unicodeLabelWithBadChars = "";
            List<Lbl> labels = GetAllRecordsByType<Lbl>();
            Lbl autoOpenLbl = labels.First(l => l.fBuiltin && l.Name.Value.Equals("\u0001") ||
                                                l.Name.Value.ToLower().StartsWith(localizedLabel.ToLower()));
            Lbl replaceLabelStringLbl = ((BiffRecord)autoOpenLbl.Clone()).AsRecordType<Lbl>();

            //Characters that work
            //fefe, ffff, feff, fffe, ffef, fff0, fff1, fff6, fefd, 0000, dddd
            //Pretty much any character that is invalid unicode - though \ucccc doesn't seem to work - need better criteria for parsing

            foreach (char localizedLabelChar in localizedLabel)
            {
                indexLabel = randomUnicodeChar.Next(localizedLabel.Length);
                for (var i = 0; i < 10; i += 1)
                    unicodeLabelWithBadChars += badUnicodeChars[indexLabel];
            
                unicodeLabelWithBadChars += localizedLabelChar;
            }
            replaceLabelStringLbl.SetName(new XLUnicodeStringNoCch(unicodeLabelWithBadChars, true));
            replaceLabelStringLbl.fBuiltin = false;

            // Hidden removes from the label manager entirely, but doesn't seem to work if fBuiltin is false
            // replaceLabelStringLbl.fHidden = true;

            WorkbookStream obfuscatedStream = ReplaceRecord(autoOpenLbl, replaceLabelStringLbl);
            obfuscatedStream = obfuscatedStream.FixBoundSheetOffsets();
            return obfuscatedStream;
        }

19 View Source File : FetchXMLConditionalOperators.cs
License : MIT License
Project Creator : Adoxio

public static string GetValueByKey(ConditionOperator key)
		{
			var keyValue = ConditionOperatorToTextFromLookUp.First(pair => pair.Key == key);
			return keyValue.Value[0];
		}

19 View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio

public static T? GetAttribute<T>(this JToken element, string name, IDictionary<T, string> lookup) where T : struct
		{
			var attribute = element[name];

			if (attribute != null)
			{
				var value = lookup.First(pair => pair.Value == attribute.Value<string>());

				return value.Key;
			}

			return null;
		}

19 View Source File : DataRepository.cs
License : MIT License
Project Creator : Accelerider

public void Save(object data)
        {
            var path = _cache.First(item => ReferenceEquals(item.Value.Settings, data)).Key;

            WriteToLocal(path, data.ToJson(Formatting.Indented, false));
        }

19 View Source File : AutoUpdater.cs
License : MIT License
Project Creator : adrianmteo

public async Task CheckForUpdates(bool force)
        {
            if (Model.Status == UpdateStatus.Checking)
            {
                Logger.Warning("Cannot check for new updates because the status says it's already checking for one");
                return;
            }

            if (!force && Model.LastCheckInMinutes < 30)
            {
                Logger.Warning("Cannot check for new updates because the last check was less than 30m");
                return;
            }

            Logger.Info("Checking for updates...");

            Model.LastCheck = DateTime.Now;
            Model.Status = UpdateStatus.Checking;

            JsonDownloader jsonDownloader = new JsonDownloader();

            try
            {
                GithubModel response = await jsonDownloader.GetObject<GithubModel>("https://api.github.com/repos/adrianmteo/Luna/releases/latest");

                Version newVersion = new Version(response.tag_name.Substring(1));

                if (newVersion > LocalVersion)
                {
                    Logger.Info("Found new update with version {0}", newVersion);

                    GithubModel.replacedets replacedet = response.replacedets.First(e => e.name.ToLower().Contains("exe"));

                    Model.Version = newVersion.ToString();
                    Model.Changelog = response.body;
                    Model.DownloadUrl = replacedet.browser_download_url;
                    Model.DownloadName = replacedet.name;

                    if (AutoUpdate)
                    {
                        await DownloadUpdate();
                    }
                    else
                    {
                        Model.Status = UpdateStatus.NewUpdate;
                    }
                }
                else
                {
                    Logger.Info("No new updates found...");

                    Model.Status = UpdateStatus.NoUpdate;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);

                Model.Status = UpdateStatus.Error;
            }
        }

19 View Source File : ReceivePacket.cs
License : MIT License
Project Creator : 499116344

internal void TlvExecutionProcessing(ICollection<Tlv> tlvs)
        {
            if (_tlvTypes == null)
            {
                var types = replacedembly.GetExecutingreplacedembly().GetTypes();
                _tlvTypes = new Dictionary<int, Type>();
                foreach (var type in types)
                {
                    var attributes = type.GetCustomAttributes();
                    if (!attributes.Any(attr => attr is TlvTagAttribute))
                    {
                        continue;
                    }

                    var attribute = attributes.First(attr => attr is TlvTagAttribute) as TlvTagAttribute;
                    _tlvTypes.Add((int) attribute.Tag, type);
                }
            }
            foreach (var tlv in tlvs)
            {
                if (_tlvTypes.ContainsKey(tlv.Tag))
                {
                    var tlvClreplaced = replacedembly.GetExecutingreplacedembly().CreateInstance(_tlvTypes[tlv.Tag].FullName, true);
                    var methodinfo = _tlvTypes[tlv.Tag].GetMethod("Parser_Tlv");
                    methodinfo.Invoke(tlvClreplaced, new object[] { User, Reader });
                }
            }
        }

19 View Source File : MobilePhoneCall.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static void DoReminisce(int which, NPC npc)
        {
            Monitor.Log($"Doing reminisce");

            if (!ModEntry.inCall)
            {
                Monitor.Log($"Not in call, exiting");
                return;
            }


            Reminisce r = inCallReminiscence[which];
            Dictionary<string, string> dict;
            try
            {
                dict = Helper.Content.Load<Dictionary<string, string>>(Path.Combine("Data", "Events", r.location), ContentSource.GameContent);
            }
            catch (Exception ex)
            {
                Monitor.Log($"Exception loading event dictionary for {r.location}: {ex}");
                return;
            }

            string eventString;
            if (dict.ContainsKey(r.eventId))
                eventString = dict[r.eventId];
            else if (dict.Any(k => k.Key.StartsWith($"{r.eventId}/")))
                eventString = dict.First(k => k.Key.StartsWith($"{r.eventId}/")).Value;
            else
            {
                Monitor.Log($"Event not found for id {r.eventId}");
                return;
            }

            ModEntry.isReminiscing = true;
            (Game1.activeClickableMenu as DialogueBox).closeDialogue();
            Game1.player.currentLocation.lastQuestionKey = "";
            LocationRequest l = Game1.getLocationRequest(r.location);
            ModEntry.isReminiscingAtNight = r.night;
            if (r.mail != null)
            {
                foreach (string m in r.mail.Split(','))
                {
                    if (Game1.player.mailReceived.Contains(m))
                    {
                        Monitor.Log($"Removing received mail {m}");
                        Game1.player.mailReceived.Remove(m);
                    }
                }
            }

            Event e = new Event(eventString)
            {
                exitLocation = new LocationRequest(Game1.player.currentLocation.Name, Game1.player.currentLocation.isStructure.Value, Game1.player.currentLocation)
            };
            Vector2 exitPos = Game1.player.getTileLocation();
            e.onEventFinished += delegate ()
            {
                Monitor.Log($"Event finished");
                ReturnToReminisce();
            };
            ModEntry.reminisceEvent = e;
            Game1.warpFarmer(l, 0, 0, 0);
            l.Location.startEvent(e);
            Game1.player.positionBeforeEvent = exitPos;
        }

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

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task KeepExistingCIEnv()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                var existingCI = Environment.GetEnvironmentVariable("CI");
                try
                {
                    // Clear out CI and make sure process invoker sets it.
                    Environment.SetEnvironmentVariable("CI", null);

                    Tracing trace = hc.GetTrace();

                    Int32 exitCode = -1;
                    var processInvoker = new ProcessInvokerWrapper();
                    processInvoker.Initialize(hc);
                    var stdout = new List<string>();
                    var stderr = new List<string>();
                    processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
                    {
                        trace.Info(e.Data);
                        stdout.Add(e.Data);
                    };
                    processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs e) =>
                    {
                        trace.Info(e.Data);
                        stderr.Add(e.Data);
                    };
#if OS_WINDOWS
                    exitCode = await processInvoker.ExecuteAsync("", "cmd.exe", "/c \"echo %CI%\"", new Dictionary<string, string>() { { "CI", "false" } }, CancellationToken.None);
#else
                    exitCode = await processInvoker.ExecuteAsync("", "bash", "-c \"echo $CI\"", new Dictionary<string, string>() { { "CI", "false" } }, CancellationToken.None);
#endif

                    trace.Info("Exit Code: {0}", exitCode);
                    replacedert.Equal(0, exitCode);

                    replacedert.Equal("false", stdout.First(x => !string.IsNullOrWhiteSpace(x)));
                }
                finally
                {
                    Environment.SetEnvironmentVariable("CI", existingCI);
                }
            }
        }

19 View Source File : CrossChainCommunicationTestHelper.cs
License : MIT License
Project Creator : AElfProject

public bool TryGetHeightByHash(Hash hash, out long height)
        {
            height = 0;
            var dict = CreateDict();
            if (dict.All(kv => kv.Value != hash)) return false;
            height = dict.First(kv => kv.Value == hash).Key;
            return true;
        }

19 View Source File : QueryBody.cs
License : MIT License
Project Creator : 17MKH

public Tuple<QueryJoin, IColumnDescriptor> GetJoin(MemberExpression exp)
    {
        var fieldExp = exp.Expression;

        if (typeof(IEnreplacedy).IsImplementType(fieldExp!.Type))
        {
            var join = Joins.First(m => m.EnreplacedyDescriptor.EnreplacedyType == fieldExp.Type);
            var column = GetColumnDescriptor(exp.Member.Name, join);
            return new Tuple<QueryJoin, IColumnDescriptor>(join, column);
        }

        if (fieldExp.NodeType == ExpressionType.MemberAccess)
        {
            return GetJoin(fieldExp as MemberExpression);
        }

        return null;
    }

19 View Source File : PeerInvalidTransactionTestModule.cs
License : MIT License
Project Creator : AElfProject

public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var peerPoolMock = new Mock<IPeerPool>();
            var peerList = new List<IPeer>
            {
                MockPeer("192.168.1.100:6800", "Peer1"),
                MockPeer("192.168.1.100:6801", "Peer2"),
                MockPeer("192.168.100.100:6800", "Peer3")
            };

            peerPoolMock.Setup(p => p.GetPeers(It.IsAny<bool>()))
                .Returns<bool>(includeFailing => peerList);
            peerPoolMock.Setup(p => p.GetPeersByHost(It.IsAny<string>()))
                .Returns<string>(host => { return peerList.Where(p => p.RemoteEndpoint.Host.Equals(host)).ToList(); });
            peerPoolMock.Setup(p => p.FindPeerByPublicKey(It.IsAny<string>()))
                .Returns<string>(pubkey => peerList.First(p => p.Info.Pubkey.Equals(pubkey)));
            
            context.Services.AddSingleton(o => peerPoolMock.Object);
        }

19 View Source File : AzureKeyVaultCertificateClient.cs
License : MIT License
Project Creator : ActiveLogin

private X509Certificate2 GetX509Certificate2(byte[] certificate)
        {
            var exportedCertCollection = new X509Certificate2Collection();
            exportedCertCollection.Import(certificate, string.Empty, X509KeyStorageFlags.MachineKeySet);

            return exportedCertCollection.Cast<X509Certificate2>().First(x => x.HasPrivateKey);
        }

19 View Source File : ExcelParser.cs
License : MIT License
Project Creator : AgileoAutomation

public List<ComponentSpecification> BuildSpecifications(string filepath)
        {
            List<ComponentSpecification> specs = new List<ComponentSpecification>();

            try
            {
                SpreadsheetDoreplacedent spreadsheetDoreplacedent = SpreadsheetDoreplacedent.Open(filepath, false);
                workbookPart = spreadsheetDoreplacedent.WorkbookPart;
            }
            catch
            {
                MessageBox.Show("The specification file is open in a other process");
                return null;
            }
            
            SheetData sheetData = null;

            try
            {
                Sheet sheet = workbookPart.Workbook.Sheets.ChildElements.Cast<Sheet>().First(x => x.Name == "replacedembly Info");
                int index = workbookPart.WorksheetParts.ToList().IndexOf(workbookPart.WorksheetParts.Last()) - workbookPart.Workbook.Sheets.ToList().IndexOf(sheet);
                sheetData = workbookPart.WorksheetParts.ElementAt(index).Worksheet.Elements<SheetData>().First();
            }
            catch
            {
                MessageBox.Show("Invalid specification file :\nCouldn't find the 'replacedembly Info' worksheet");
                return null;
            }
            

            rows = new List<Row>();
            rows.AddRange(sheetData.Elements<Row>());
            
            int replacedembliesColumn = -1;

            try
            {
                List<Cell> headerRow = rows.First().Elements<Cell>().ToList();
                replacedembliesColumn = headerRow.IndexOf(headerRow.First(x => TextInCell(x) == "replacedemblies"));
            }
            catch
            {
                MessageBox.Show("Invalid specification file :\nPlease respect the spreadsheet pattern, you didn't specified the replacedembly column");
            }

            rows.RemoveAt(0);
            rows.RemoveAll(x => !x.Elements<Cell>().Any(y => !string.IsNullOrEmpty(TextInCell(y))));

            while (rows.Count > 0)
            {
                specs.Add(BuildSpec(0, replacedembliesColumn));
            }

            return specs;
        }

19 View Source File : StateMachineExpression.cs
License : MIT License
Project Creator : 71

protected void SetType(Type lambdaType, Type smType)
        {
            Requires.NotNull(lambdaType, nameof(lambdaType));
            Requires.NotNull(smType, nameof(smType));

            _type = lambdaType;
            _end  = Label(lambdaType, "end");

            _state = Parameter(smType, "state");
            _vsmCtor = smType.GetTypeInfo().DeclaredConstructors.First(x => x.GetParameters().Length == 0);
        }

19 View Source File : AgoraServiceImplementation.cs
License : MIT License
Project Creator : AgoraIO-Community

public virtual void OnFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed)
        {
            var id = (uint)uid;
            _knownStreams.Add(id);
            if (!_containers.Any(a => a.StreamUID == id))
            {
                if (_containers.Any(a => a.StreamUID == AgoraService.UnknownRemoteStreamId))
                {
                    var viewHolder = _containers.First(a => a.StreamUID == AgoraService.UnknownRemoteStreamId);
                    viewHolder.StreamUID = id;
                    viewHolder.VideoView.IsOffline = false;
                }
                else
                {
                    OnNewStream((uint)uid, width, height);
                }
            }
        }

19 View Source File : DacPropertyAttributesAnalyzer.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static void CheckForFieldTypeAttributes(DacPropertyInfo property, SymbolreplacedysisContext symbolContext, PXContext pxContext,
														List<(AttributeInfo Attribute, List<FieldTypeAttributeInfo> Infos)> attributesWithInfos)
		{
			var (typeAttributesDeclaredOnDacProperty, typeAttributesWithConflictingAggregatorDeclarations) = FilterTypeAttributes();

			if (typeAttributesDeclaredOnDacProperty.Count == 0)
				return;

			if (typeAttributesWithConflictingAggregatorDeclarations.Count > 0)
			{
				RegisterDiagnosticForAttributes(symbolContext, pxContext, typeAttributesWithConflictingAggregatorDeclarations,
												Descriptors.PX1023_MultipleTypeAttributesOnAggregators);
			}

			if (typeAttributesDeclaredOnDacProperty.Count > 1)					
			{
				RegisterDiagnosticForAttributes(symbolContext, pxContext, typeAttributesDeclaredOnDacProperty,
												Descriptors.PX1023_MultipleTypeAttributesOnProperty);
			} 
			else if (typeAttributesWithConflictingAggregatorDeclarations.Count == 0)
			{
				var typeAttribute = typeAttributesDeclaredOnDacProperty[0];
				var fieldType = attributesWithInfos.First(attrWithInfo => attrWithInfo.Attribute.Equals(typeAttribute))
												   .Infos
												   .Where(info => info.IsFieldAttribute)
												   .Select(info => info.FieldType)
												   .Distinct()
												   .SingleOrDefault();
		
				CheckAttributeAndPropertyTypesForCompatibility(property, typeAttribute, fieldType, pxContext, symbolContext);
			}

			//-----------------------------------------------Local Functions---------------------------------------
			(List<AttributeInfo>, List<AttributeInfo>) FilterTypeAttributes()
			{
				List<AttributeInfo> typeAttributesOnDacProperty = new List<AttributeInfo>(2);
				List<AttributeInfo> typeAttributesWithInvalidAggregatorDeclarations = new List<AttributeInfo>(2);

				foreach (var (attribute, infos) in attributesWithInfos)
				{
					int countOfTypeAttributeInfos = infos.Count(info => info.IsFieldAttribute);

					if (countOfTypeAttributeInfos == 0)
						continue;

					typeAttributesOnDacProperty.Add(attribute);

					if (countOfTypeAttributeInfos == 1)
						continue;

					int countOfDeclaredFieldTypes = infos.Select(info => info.FieldType)
														 .Distinct()
														 .Count();
					if (countOfDeclaredFieldTypes > 1)
					{
						typeAttributesWithInvalidAggregatorDeclarations.Add(attribute);
					}
				}

				return (typeAttributesOnDacProperty, typeAttributesWithInvalidAggregatorDeclarations);
			}
		}

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

private static IValidator GetValidatorForModel(object enreplacedy, object model, IStringLocalizer localizer)
        {
            if (model is IEnreplacedyResource resource)
            {
                var enreplacedyValidatorType = typeof(EnreplacedyResourceValidator<>).MakeGenericType(model.GetType());              
                return (IValidator)Activator.CreateInstance(enreplacedyValidatorType, enreplacedy, resource.ResourceKind, localizer);
            }
            var abstractValidatorType = typeof(AbstractValidator<>).MakeGenericType(model.GetType());
            var replacedemby = AppDomain.CurrentDomain.Getreplacedemblies().Where(a => a.FullName.Contains("Aguacongas.TheIdServer.BlazorApp"))
                .FirstOrDefault(a => a.GetTypes().Any(t => t.IsSubclreplacedOf(abstractValidatorType)));
            if (replacedemby == null)
            {
                return null;
            }

            var modelValidatorType = replacedemby.GetTypes().First(t => t.IsSubclreplacedOf(abstractValidatorType));

            var modelValidatorInstance = (IValidator)Activator.CreateInstance(modelValidatorType, enreplacedy, localizer);
            return modelValidatorInstance;
        }

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

[Test, Explicit("Requires custom data")]
        public async Task TocSizeTest()
        {
            var path = @"E:\FakeCDs\PS3 Games\ird";
            var result = new List<(string filename, long size)>();
            foreach (var f in Directory.EnumerateFiles(path, "*.ird", SearchOption.TopDirectoryOnly))
            {
                var bytes = await File.ReadAllBytesAsync(f).ConfigureAwait(false);
                var ird = IrdParser.Parse(bytes);
                using (var header = GetDecompressHeader(ird))
                    result.Add((Path.GetFileName(f), header.Length));
            }
            replacedert.That(result.Count, Is.GreaterThan(0));

            var groupedStats = (from t in result
                    group t by t.size into g
                    select new {size = g.Key, count = g.Count()}
                ).OrderByDescending(i => i.count)
                .ThenByDescending(i => i.size)
                .ToList();

            var largest = groupedStats.Max(i => i.size);
            var largesreplacedem = result.First(i => i.size == largest);
            Console.WriteLine($"Largest TOC: {largesreplacedem.filename} ({largest.replacedtorageUnit()})");

            foreach (var s in groupedStats)
                Console.WriteLine($"{s.count} items of size {s.size}");

            replacedert.That(groupedStats.Count, Is.EqualTo(1));
        }

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

public static void RemoveEnreplacedyId<TEnreplacedy>(this ICollection<TEnreplacedy> collection, string id) where TEnreplacedy : Enreplacedy.IEnreplacedyId
        {
            collection.Remove(collection.First(e => e.Id == id));
        }

19 View Source File : RasterCache.cs
License : MIT License
Project Creator : adamped

public bool Prepare(GRContext context, SKPicture picture, SKMatrix transformation_matrix, SKColorSpace dst_color_space, bool is_complex, bool will_change)
        {
            if (!GlobalMembers.IsPictureWorthRasterizing(picture, will_change, is_complex))
            {
                // We only deal with pictures that are worthy of rasterization.
                return false;
            }

            // Decompose the matrix (once) for all subsequent operations. We want to make
            // sure to avoid volumetric distortions while accounting for scaling.
            //MatrixDecomposition matrix = new MatrixDecomposition(transformation_matrix);

            //if (!matrix.IsValid())
            //{
            //    // The matrix was singular. No point in going further.
            //    return false;
            //}

            RasterCacheKey<UniqueEntry> cache_key = new RasterCacheKey<UniqueEntry>(new UniqueEntry(picture.UniqueId), transformation_matrix);

            Entry entry = picture_cache_.First(x => x.Equals(cache_key)).id(); // I used Linq, that aint going to be good for performance
            entry.access_count = GlobalMembers.ClampSize(entry.access_count + 1, 0, threshold_);
            entry.used_this_frame = true;

            if (entry.access_count < threshold_ || threshold_ == 0)
            {
                // Frame threshold has not yet been reached.
                return false;
            }

            if (!entry.image.is_valid)
            {
                entry.image = GlobalMembers.RasterizePicture(picture, context, transformation_matrix, dst_color_space, checkerboard_images_);
            }
            return true;
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : 71

internal static MemberInfo GetMember(this TypeInfo type, string name)
        {
            return type.DeclaredMembers.First(x => x.Name == name);
        }

19 View Source File : ServiceBuilder.cs
License : MIT License
Project Creator : 1100100

public async Task StartAsync(CancellationToken cancellationToken)
        {
            UraganoSettings.ClientGlobalInterceptors.Reverse();
            UraganoSettings.ServerGlobalInterceptors.Reverse();

            var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
            var enableServer = UraganoSettings.ServerSettings != null;

            var types = ReflectHelper.GetDependencyTypes();
            var services = types.Where(t => t.IsInterface && typeof(IService).IsreplacedignableFrom(t)).Select(@interface => new
            {
                Interface = @interface,
                Implementation = types.FirstOrDefault(p => p.IsClreplaced && p.IsPublic && !p.IsAbstract && !p.Name.EndsWith("_____UraganoClientProxy") && @interface.IsreplacedignableFrom(p))
            }).ToList();

            foreach (var service in services)
            {
                var imp = service.Implementation;

                var routeAttr = service.Interface.GetCustomAttribute<ServiceRouteAttribute>();
                var routePrefix = routeAttr == null ? $"{service.Interface.Namespace}/{service.Interface.Name}" : routeAttr.Route;


                var interfaceMethods = service.Interface.GetMethods();

                List<MethodInfo> implementationMethods = null;
                if (enableServer && imp != null)
                    implementationMethods = imp.GetMethods().ToList();

                var disableClientIntercept = service.Interface.GetCustomAttribute<NonInterceptAttribute>(true) != null;
                var clientClreplacedInterceptors = new List<Type>();
                if (!disableClientIntercept)
                    clientClreplacedInterceptors = service.Interface.GetCustomAttributes(true).Where(p => p is IInterceptor)
                    .Select(p => p.GetType()).ToList();

                var serverClreplacedInterceptors = new List<Type>();
                var disableServerIntercept = false;
                if (enableServer && imp != null)
                {
                    disableServerIntercept = imp.GetCustomAttribute<NonInterceptAttribute>(true) != null;
                    if (!disableServerIntercept)
                        serverClreplacedInterceptors = imp.GetCustomAttributes(true).Where(p => p is IInterceptor)
                            .Select(p => p.GetType()).ToList();
                }

                foreach (var interfaceMethod in interfaceMethods)
                {
                    MethodInfo serverMethod = null;
                    var idAttr = interfaceMethod.GetCustomAttribute<ServiceRouteAttribute>();
                    var route = idAttr == null ? $"{routePrefix}/{interfaceMethod.Name}" : $"{routePrefix}/{idAttr.Route}";

                    var clientInterceptors = new List<Type>();
                    if (enableClient && !disableClientIntercept && interfaceMethod.GetCustomAttribute<NonInterceptAttribute>(true) == null)
                    {
                        clientInterceptors.AddRange(UraganoSettings.ClientGlobalInterceptors);
                        clientInterceptors.AddRange(clientClreplacedInterceptors);
                        clientInterceptors.AddRange(interfaceMethod.GetCustomAttributes(true)
                            .Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
                        clientInterceptors.Reverse();
                    }


                    var serverInterceptors = new List<Type>();
                    if (enableServer && imp != null)
                    {
                        serverMethod = implementationMethods.First(p => IsImplementationMethod(interfaceMethod, p));
                        if (!disableServerIntercept && serverMethod?.GetCustomAttribute<NonInterceptAttribute>(true) == null)
                        {
                            serverInterceptors.AddRange(UraganoSettings.ServerGlobalInterceptors);
                            serverInterceptors.AddRange(serverClreplacedInterceptors.ToList());
                            if (serverMethod != null)
                                serverInterceptors.AddRange(serverMethod.GetCustomAttributes(true)
                                    .Where(p => p is IInterceptor).Select(p => p.GetType()).ToList());
                            serverInterceptors.Reverse();
                        }
                    }

                    ServiceFactory.Create(route, serverMethod, interfaceMethod, serverInterceptors, clientInterceptors);
                }
            }

            await Task.CompletedTask;
        }

19 View Source File : DefaultJwtTokenStorageProvider.cs
License : MIT License
Project Creator : 17MKH

public async Task Save(JwtResultModel model, List<Claim> claims)
    {
        var enreplacedy = await _repository.Find(m => m.AccountId == model.AccountId && m.Platform == model.Platform)
            .ToFirst();

        var exists = true;
        if (enreplacedy == null)
        {
            exists = false;
            enreplacedy = new JwtAuthInfoEnreplacedy
            {
                AccountId = model.AccountId,
                Platform = model.Platform
            };
        }

        enreplacedy.LoginIP = claims.First(m => m.Type == MkhClaimTypes.IP).Value;
        enreplacedy.LoginTime = claims.First(m => m.Type == MkhClaimTypes.LOGIN_TIME).Value.ToLong();
        enreplacedy.RefreshToken = model.RefreshToken;

        //默认刷新令牌有效期7天
        enreplacedy.RefreshTokenExpiredTime = DateTime.Now.AddDays(_jwtOptions.RefreshTokenExpires <= 0 ? 7 : _jwtOptions.RefreshTokenExpires);

        if (exists)
        {
            await _repository.Update(enreplacedy);
        }
        else
        {
            await _repository.Add(enreplacedy);
        }

        //刷新令牌加入缓存
        await _cacheHandler.Set(_cacheKeys.RefreshToken(model.AccountId, model.Platform), model.RefreshToken, enreplacedy.RefreshTokenExpiredTime);
    }

19 View Source File : TokenAuthController.cs
License : MIT License
Project Creator : 52ABP

private static List<Claim> CreateJwtClaims(ClaimsIdenreplacedy idenreplacedy)
        {
            var claims = idenreplacedy.Claims.ToList();
            var nameIdClaim = claims.First(c => c.Type == ClaimTypes.NameIdentifier);

            // Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
            claims.AddRange(new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, nameIdClaim.Value),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
            });

            return claims;
        }

19 View Source File : UpdateWorldController.cs
License : Apache License 2.0
Project Creator : AantCoder

public static void ApplyWorldObject(WorldObjectEntry worldObjectEntry)
        {
            var err = "";
            try
            {
                List<WorldObject> allWorldObjects = Find.WorldObjects.AllWorldObjects;
                err += "1 ";
                if (worldObjectEntry.LoginOwner == SessionClientController.My.Login)
                {
                    //для своих нужно только занести в MyWorldObjectEntry (чтобы запомнить ServerId)
                    if (!WorldObjectEntrys.Any(wo => wo.Value.ServerId == worldObjectEntry.ServerId))
                    {
                        err += "2 ";

                        for (int i = 0; i < allWorldObjects.Count; i++)
                        {
                            err += "3 ";
                            if (!WorldObjectEntrys.ContainsKey(allWorldObjects[i].ID)
                                && allWorldObjects[i].Tile == worldObjectEntry.Tile
                                && (allWorldObjects[i] is Caravan && worldObjectEntry.Type == WorldObjectEntryType.Caravan
                                    || allWorldObjects[i] is MapParent && worldObjectEntry.Type == WorldObjectEntryType.Base))
                            {
                                err += "4 ";
                                var id = allWorldObjects[i].ID;
                                Loger.Log("SetMyID " + id + " ServerId " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name);
                                WorldObjectEntrys.Add(id, worldObjectEntry);

                                ConverterServerId[worldObjectEntry.ServerId] = id;
                                err += "5 ";
                                return;
                            }
                        }

                        err += "6 ";
                        Loger.Log("ToDel " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name);

                        //объект нужно удалить на сервере - его нету у самого игрока (не заполняется при самом первом обновлении после загрузки)
                        if (ToDelete != null) ToDelete.Add(worldObjectEntry);
                        err += "7 ";
                    }
                    else
                    {
                        //если такой есть, то обновляем информацию
                        var pair = WorldObjectEntrys.First(wo => wo.Value.ServerId == worldObjectEntry.ServerId);
                        WorldObjectEntrys[pair.Key] = worldObjectEntry;
                    }
                    return;
                }

                //поиск уже существующих
                CaravanOnline worldObject = null;
                /*
                int existId;
                if (ConverterServerId.TryGetValue(worldObjectEntry.ServerId, out existId))
                {
                    for (int i = 0; i < allWorldObjects.Count; i++)
                    {
                        if (allWorldObjects[i].ID == existId && allWorldObjects[i] is CaravanOnline)
                        {
                            worldObject = allWorldObjects[i] as CaravanOnline;
                            break;
                        }
                    }
                }
                */
                err += "8 ";
                worldObject = GetOtherByServerId(worldObjectEntry.ServerId, allWorldObjects);

                err += "9 ";
                //если тут база другого игрока, то удаление всех кто занимает этот тайл, кроме караванов (удаление новых НПЦ и событий с занятых тайлов)
                if (worldObjectEntry.Type == WorldObjectEntryType.Base)
                {
                    err += "10 ";
                    for (int i = 0; i < allWorldObjects.Count; i++)
                    {
                        err += "11 ";
                        if (allWorldObjects[i].Tile == worldObjectEntry.Tile && allWorldObjects[i] != worldObject
                            && !(allWorldObjects[i] is Caravan) && !(allWorldObjects[i] is CaravanOnline)
                            && (allWorldObjects[i].Faction == null || !allWorldObjects[i].Faction.IsPlayer))
                        {
                            err += "12 ";
                            Loger.Log("Remove " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name);
                            Find.WorldObjects.Remove(allWorldObjects[i]);
                        }
                    }
                }

                err += "13 ";
                //создание
                if (worldObject == null)
                {
                    err += "14 ";
                    worldObject = worldObjectEntry.Type == WorldObjectEntryType.Base
                        ? (CaravanOnline)WorldObjectMaker.MakeWorldObject(ModDefOf.BaseOnline)
                        : (CaravanOnline)WorldObjectMaker.MakeWorldObject(ModDefOf.CaravanOnline);
                    err += "15 ";
                    worldObject.SetFaction(Faction.OfPlayer);
                    worldObject.Tile = worldObjectEntry.Tile;
                    Find.WorldObjects.Add(worldObject);
                    err += "16 ";
                    ConverterServerId.Add(worldObjectEntry.ServerId, worldObject.ID);
                    Loger.Log("Add " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name + " " + worldObjectEntry.LoginOwner);
                    err += "17 ";
                }
                else
                {
                    err += "18 ";
                    ConverterServerId[worldObjectEntry.ServerId] = worldObject.ID; //на всякий случай
                    err += "19 ";
                    //Loger.Log("SetID " + worldObjectEntry.ServerId + " " + worldObjectEntry.Name);
                }
                err += "20 ";
                //обновление
                worldObject.Tile = worldObjectEntry.Tile;
                err += "21 ";
                worldObject.OnlineWObject = worldObjectEntry;
            }
            catch
            {
                Loger.Log("ApplyWorldObject ErrorLog: " + err);
                throw;
            }
        }

19 View Source File : FetchXMLConditionalOperators.cs
License : MIT License
Project Creator : Adoxio

public static ConditionOperator GetKeyByValue(string value)
		{
			var keyValue = ConditionOperatorToTextFromLookUp.First(pair => pair.Value.Contains(value));
			return keyValue.Key;
		}

See More Examples