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

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

2385 Examples 7

19 View Source File : CelesteNetChatComponent.cs
License : MIT License
Project Creator : 0x0ade

protected override void Render(GameTime gameTime, bool toBuffer) {
            float scale = Scale;
            Vector2 fontScale = Vector2.One * scale;

            if (Active) {
                Context.RenderHelper.Rect(25f * scale, UI_HEIGHT - 125f * scale, UI_WIDTH - 50f * scale, 100f * scale, Color.Black * 0.8f);

                CelesteNetClientFont.Draw(
                    ">",
                    new(50f * scale, UI_HEIGHT - 105f * scale),
                    Vector2.Zero,
                    fontScale * new Vector2(0.5f, 1f),
                    Color.White * 0.5f
                );
                float offs = CelesteNetClientFont.Measure(">").X * scale;

                string text = Typing;
                CelesteNetClientFont.Draw(
                    text,
                    new(50f * scale + offs, UI_HEIGHT - 105f * scale),
                    Vector2.Zero,
                    fontScale,
                    Color.White
                );

                if (!Calc.BetweenInterval(_Time, 0.5f)) {

                    if (CursorIndex == Typing.Length) {
                        offs += CelesteNetClientFont.Measure(text).X * scale;
                        CelesteNetClientFont.Draw(
                            "_",
                            new(50f * scale + offs, UI_HEIGHT - 105f * scale),
                            Vector2.Zero,
                            fontScale,
                            Color.White * 0.5f
                        );
                    } else {
                        // draw cursor at correct location, but move back half a "." width to not overlap following char
                        offs += CelesteNetClientFont.Measure(Typing.Substring(0, CursorIndex)).X * scale;
                        offs -= CelesteNetClientFont.Measure(".").X / 2f * scale;

                        CelesteNetClientFont.Draw(
                               "|",
                               new(50f * scale + offs, UI_HEIGHT - 110f * scale),
                               Vector2.Zero,
                               fontScale * new Vector2(.5f, 1.2f),
                               Color.White * 0.6f
                           );
                    }
                }
            }

            lock (Log) {
                List<DataChat> log = Mode switch {
                    ChatMode.Special => LogSpecial,
                    ChatMode.Off => Dummy<DataChat>.EmptyList,
                    _ => Log,
                };

                int count = log.Count;
                if (count > 0) {
                    DateTime now = DateTime.UtcNow;

                    float y = UI_HEIGHT - 50f * scale;
                    if (Active)
                        y -= 105f * scale;

                    float logLength = Settings.ChatLogLength;
                    for (int i = 0; i < count && i < logLength; i++) {
                        DataChat msg = log[count - 1 - i];

                        float alpha = 1f;
                        float delta = (float) (now - msg.ReceivedDate).TotalSeconds;
                        if (!Active && delta > 3f)
                            alpha = 1f - Ease.CubeIn(delta - 3f);
                        if (alpha <= 0f)
                            continue;

                        string time = msg.Date.ToLocalTime().ToLongTimeString();

                        string text = msg.ToString(true, false);
                        logLength -= Math.Max(0, text.Count(c => c == '\n') - 1) * 0.75f;

                        int lineScaleTry = 0;
                        float lineScale = scale;
                        RetryLineScale:
                        Vector2 lineFontScale = Vector2.One * lineScale;

                        Vector2 sizeTime = CelesteNetClientFontMono.Measure(time) * lineFontScale;
                        Vector2 sizeText = CelesteNetClientFont.Measure(text) * lineFontScale;
                        Vector2 size = new(sizeTime.X + 25f * scale + sizeText.X, Math.Max(sizeTime.Y - 5f * scale, sizeText.Y));

                        if ((size.X + 100f * scale) > UI_WIDTH && lineScaleTry < 4) {
                            lineScaleTry++;
                            lineScale -= scale * 0.1f;
                            goto RetryLineScale;
                        }

                        float height = 50f * scale + size.Y;

                        y -= height;

                        Context.RenderHelper.Rect(25f * scale, y, size.X + 50f * scale, height, Color.Black * 0.8f * alpha);
                        CelesteNetClientFontMono.Draw(
                            time,
                            new(50f * scale, y + 20f * scale),
                            Vector2.Zero,
                            lineFontScale,
                            msg.Color * alpha * (msg.ID == uint.MaxValue ? 0.8f : 1f)
                        );
                        CelesteNetClientFont.Draw(
                            text,
                            new(75f * scale + sizeTime.X, y + 25f * scale),
                            Vector2.Zero,
                            lineFontScale,
                            msg.Color * alpha * (msg.ID == uint.MaxValue ? 0.8f : 1f)
                        );
                    }
                }

19 View Source File : SqModelMeta.cs
License : MIT License
Project Creator : 0x1000000

public bool HasPk()
        {
            var pkCount = this.Properties.Count(i => i.IsPrimaryKey);
            return pkCount > 0 && pkCount < this.Properties.Count;
        }

19 View Source File : PlayerStatusHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(FightWithNpcCommand command, CancellationToken cancellationToken)
        {
            var playerId = command.PlayerId;
            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                return Unit.Value;
            }

            var npcId = command.NpcId;
            var npc = await _npcDomainService.Get(npcId);
            if (npc == null)
            {
                return Unit.Value;
            }


            if (!npc.CanFight)
            {
                await _bus.RaiseEvent(new DomainNotification($"你不能与[{npc.Name}]切磋!"));
                return Unit.Value;
            }


            if (player.RoomId != npc.RoomId)
            {
                await _bus.RaiseEvent(new DomainNotification($"[{npc.Name}]已经离开此地,无法发起切磋!"));
                return Unit.Value;
            }

            if (npc.IsDead)
            {
                await _bus.RaiseEvent(new DomainNotification($"[{npc.Name}]已经死了,无法发起切磋!"));
                return Unit.Value;
            }

            var npcFightingPlayerId = await _redisDb.StringGet<int>(string.Format(RedisKey.NpcFighting, npc.Id));
            if (npcFightingPlayerId > 0 && npcFightingPlayerId != playerId)
            {
                await _bus.RaiseEvent(new DomainNotification($"[{npc.Name}]拒绝了你的切磋请求!"));
                return Unit.Value;
            }



            var hasChangedStatus= await BeginChangeStatus(new PlayerStatusModel
            {
                PlayerId = playerId,
                Status = PlayerStatusEnum.切磋,
                TargetType = TargetTypeEnum.Npc,
                TargetId = npcId
            });

            if (hasChangedStatus)
            {
                await _mudProvider.ShowMessage(playerId, $"【切磋】你对着[{npc.Name}]说道:在下[{player.Name}],领教阁下的高招!");

                await _mudProvider.ShowMessage(playerId, $"【切磋】[{npc.Name}]说道:「既然阁下赐教,在下只好奉陪,我们点到为止。」");

                await _redisDb.StringSet(string.Format(RedisKey.NpcFighting, npc.Id), playerId, DateTime.Now.AddSeconds(20));

                int minDelay = npc.Speed;
                int maxDelay = minDelay + 1000;

                var actionPoint = await _redisDb.StringGet<int>(string.Format(RedisKey.ActionPoint, playerId));
                await _mudProvider.ShowActionPoint(playerId, actionPoint);

                await _recurringQueue.Publish($"npc_{npc.Id}", new NpcStatusModel
                {
                    NpcId = npc.Id,
                    Status = NpcStatusEnum.切磋,
                    TargetId = playerId,
                    TargetType = TargetTypeEnum.玩家
                }, minDelay, maxDelay);

                await _mudProvider.ShowBox(playerId, new { boxName = "fighting" });


                var myWeapons = await _playerWareDomainService.GetAllWeapon(playerId);
                var myWeaponIds = myWeapons.Select(x => x.WareId);

                var weapons = (await _wareDomainService.GetAll()).Where(x => x.Category == WareCategoryEnum.武器 && myWeaponIds.Contains(x.Id)).ToList();



                var skillModels = new List<SkillModel>();

                var playerSkills = await _playerSkillDomainService.GetAll(player.Id);

                var ids = playerSkills?.Select(x => x.SkillId);

                var skills = (await _skillDomainService.GetAll()).Where(x => x.Category == SkillCategoryEnum.外功 && ids.Contains(x.Id));
                foreach (var playerSkill in playerSkills)
                {
                    var skill = skills.FirstOrDefault(x => x.Id == playerSkill.SkillId);
                    if (skill != null)
                    {
                        switch (skill.Type)
                        {
                            case SkillTypeEnum.刀法:
                                if (weapons.Count(x => x.Type == WareTypeEnum.刀) == 0)
                                {
                                    continue;
                                }
                                break;
                            case SkillTypeEnum.剑法:
                                if (weapons.Count(x => x.Type == WareTypeEnum.剑) == 0)
                                {
                                    continue;
                                }
                                break;
                            case SkillTypeEnum.枪棍:
                                if (weapons.Count(x => x.Type == WareTypeEnum.枪) == 0)
                                {
                                    continue;
                                }
                                break;

                        }

                        var skillModel = _mapper.Map<SkillModel>(skill);
                        skillModel.ObjectSkillId = playerSkill.Id;
                        skillModel.Level = playerSkill.Level;
                        skillModel.Exp = playerSkill.Exp;
                        skillModel.IsDefault = playerSkill.IsDefault;
                        skillModels.Add(skillModel);
                    }

                }

                if (skillModels.Count(x => (x.Type == SkillTypeEnum.刀法 || x.Type == SkillTypeEnum.剑法 || x.Type == SkillTypeEnum.枪棍) && x.IsDefault) == 0)
                {
                    skillModels.FirstOrDefault(x => x.Type == SkillTypeEnum.拳脚).IsDefault = true;
                }

                await _mudProvider.ShowFightingSkill(playerId, skillModels);
            }


            return Unit.Value;
        }

19 View Source File : SkillCommandHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task<Unit> Handle(ShowFightingSkillCommand command, CancellationToken cancellationToken)
        {
            var playerId = command.PlayerId;
            var player = await _playerDomainService.Get(playerId);
            if (player == null)
            {
                return Unit.Value;
            }

            var myWeapons = await _playerWareDomainService.GetAllWeapon(playerId);
            var myWeaponIds = myWeapons.Select(x => x.WareId);

            var weapons = (await _wareDomainService.GetAll()).Where(x => x.Category == WareCategoryEnum.武器 && myWeaponIds.Contains(x.Id)).ToList();



            var skillModels = new List<SkillModel>();

            var playerSkills = await _playerSkillDomainService.GetAll(player.Id);

            var ids = playerSkills?.Select(x => x.SkillId);

            var skills = (await _skillDomainService.GetAll()).Where(x => x.Category == SkillCategoryEnum.外功 && ids.Contains(x.Id));
            foreach (var playerSkill in playerSkills)
            {
                var skill = skills.FirstOrDefault(x => x.Id == playerSkill.SkillId);
                if (skill != null)
                {
                    switch (skill.Type)
                    {
                        case SkillTypeEnum.刀法:
                            if (weapons.Count(x => x.Type == WareTypeEnum.刀) == 0)
                            {
                                continue;
                            }
                            break;
                        case SkillTypeEnum.剑法:
                            if (weapons.Count(x => x.Type == WareTypeEnum.剑) == 0)
                            {
                                continue;
                            }
                            break;
                        case SkillTypeEnum.枪棍:
                            if (weapons.Count(x => x.Type == WareTypeEnum.枪) == 0)
                            {
                                continue;
                            }
                            break;

                    }
           
                    var skillModel = _mapper.Map<SkillModel>(skill);
                    skillModel.ObjectSkillId = playerSkill.Id;
                    skillModel.Level = playerSkill.Level;
                    skillModel.Exp = playerSkill.Exp;
                    skillModel.IsDefault = playerSkill.IsDefault;
                    skillModels.Add(skillModel);
                }

            }

            if (skillModels.Count(x => (x.Type == SkillTypeEnum.刀法 || x.Type == SkillTypeEnum.剑法 || x.Type == SkillTypeEnum.枪棍) && x.IsDefault) == 0)
            {
                skillModels.FirstOrDefault(x => x.Type == SkillTypeEnum.拳脚).IsDefault = true;
            }

            await _mudProvider.ShowFightingSkill(playerId, skillModels);
            return Unit.Value;
        }

19 View Source File : RectangleSelection.cs
License : MIT License
Project Creator : Abdesol

public static bool PerformRectangularPaste(TextArea textArea, TextViewPosition startPosition, string text, bool selectInsertedText)
		{
			if (textArea == null)
				throw new ArgumentNullException("textArea");
			if (text == null)
				throw new ArgumentNullException("text");
			int newLineCount = text.Count(c => c == '\n'); // TODO might not work in all cases, but single \r line endings are really rare today.
			TextLocation endLocation = new TextLocation(startPosition.Line + newLineCount, startPosition.Column);
			if (endLocation.Line <= textArea.Doreplacedent.LineCount) {
				int endOffset = textArea.Doreplacedent.GetOffset(endLocation);
				if (textArea.Selection.EnableVirtualSpace || textArea.Doreplacedent.GetLocation(endOffset) == endLocation) {
					RectangleSelection rsel = new RectangleSelection(textArea, startPosition, endLocation.Line, GetXPos(textArea, startPosition));
					rsel.ReplaceSelectionWithText(text);
					if (selectInsertedText && textArea.Selection is RectangleSelection) {
						RectangleSelection sel = (RectangleSelection)textArea.Selection;
						textArea.Selection = new RectangleSelection(textArea, startPosition, sel.endLine, sel.endXPos);
					}
					return true;
				}
			}
			return false;
		}

19 View Source File : TransactionService.cs
License : MIT License
Project Creator : Abdulrhman5

private TransactionForUserDownstreamListDto AggregateTransactionWithObject8User(List<TransactionUpstreamDto> trans, List<UserDto> users, List<TransactionObjectDto> objects)
        {
            var downStreamTransactions = new List<TransactionDownstreamDto>();
            foreach (var tran in trans)
            {
                downStreamTransactions.Add(new TransactionDownstreamDto
                {
                    RegistrationId = tran.RegistrationId,
                    ReceivingId = tran.ReceivingId,
                    ReturnId = tran.ReturnId,
                    RegistredAtUtc = tran.RegistredAtUtc,
                    HourlyCharge = tran.HourlyCharge,
                    ReceivedAtUtc = tran.ReceivedAtUtc,
                    ReturenedAtUtc = tran.ReturenedAtUtc,
                    ShouldReturnAfter = tran.ShouldReturnAfter,
                    TransactionStatus = tran.TransactionStatus,
                    TranscationType = tran.TranscationType,
                    Object = objects.Find(o => o.Id == tran.ObjectId),
                    Owner = users.Find(u => u.Id.EqualsIC(tran.OwnerId) || u.Id.EqualsIC(tran.ReceiverId)),
                    Receiver = users.Find(u => u.Id.EqualsIC(tran.OwnerId) || u.Id.EqualsIC(tran.ReceiverId))
            });
            }
            var userId = _httpContext.Request.Query["userId"].GetValue();
            return new TransactionForUserDownstreamListDto()
            {
                Transactions = downStreamTransactions,
                OtherUsersReservationsCount = downStreamTransactions.Count(t => t.Owner.Id.EqualsIC(userId)),
                TheUserReservationsCount = downStreamTransactions.Count(t => t.Receiver.Id.EqualsIC(userId))
            };
        }

19 View Source File : ClusterDef.cs
License : MIT License
Project Creator : abdullin

public void AddService(string svc, Func<IEnv, IEngine> run) {
            if (!svc.Contains(':')) {
                var count = Services.Count(p => p.Key.Machine == svc);
                
                svc = svc + ":svc" + count;
            }
            Services.Add(new ServiceId(svc), run);
        }

19 View Source File : CalculaValor.cs
License : MIT License
Project Creator : abrandaol-youtube

public void DefineValor(Pizza pizza)
        {
            var totalIngradientes = Enum.GetValues(typeof(IngredientesType)).Cast<Enum>().Count(pizza.IngredientesType.HasFlag);

            /*
             *  Expressão apra calculo do valor total da pizza
             *
             *  (Total de Ingradientes x R$ 1,70) + ( o tamanho da pizza x R$ 10,00) + (se for doce mais R$ 10,00) +
             *  (Se a borda for de chocolate é o tamanho da borda x R$ 5,00 e se for salgada x R$ 2,00)             
             */
            var valorIngredintes = totalIngradientes * 1.70;
            var valorTamanho = (int)pizza.PizzaSize * 10;
            var valorTipo = pizza.PizzaType == PizzaType.Doce ? 10 : 0;

            var valorBorda = 0;

            if (pizza.Borda != null)
            {
                valorBorda = pizza.Borda.BordaType == BordaType.Chocolate
                    ? (5 * (int)pizza.Borda.BordaSize)
                    : (2 * (int)pizza.Borda.BordaSize);
            }

            pizza.Valor = valorIngredintes + valorTamanho + valorTipo + valorBorda;
        }

19 View Source File : BuilderEntityMetadata.cs
License : MIT License
Project Creator : abvogel

public void RemoveRelationshipsWhereIdentical(String relationshipName, Dictionary<Guid, List<Guid>> relatedEnreplacedies)
        {
            if (!RelatedEnreplacedies.ContainsKey(relationshipName))
                return;

            foreach (var id in relatedEnreplacedies.Keys)
            {
                if (!RelatedEnreplacedies[relationshipName].ContainsKey(id))
                    return;

                var newRelatedIds = this.RelatedEnreplacedies[relationshipName][id].Except(relatedEnreplacedies[id]);
                if (newRelatedIds.Count() == 0)
                {
                    this.RelatedEnreplacedies[relationshipName].Remove(id);
                    if (this.RelatedEnreplacedies[relationshipName].Count == 0)
                        this.RelatedEnreplacedies.Remove(relationshipName);
                } else
                {
                    this.RelatedEnreplacedies[relationshipName][id] = newRelatedIds.ToList();
                }
            }
        }

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

public int GetWeenieCacheCount()
        {
            return weenieCache.Count(r => r.Value != null);
        }

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

public int GetCookbookCacheCount()
        {
            lock (cookbookCache)
                return cookbookCache.Count(r => r.Value != null);
        }

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

public int GetEncounterCacheCount()
        {
            return cachedEncounters.Count(r => r.Value != null);
        }

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

public int GetEventsCacheCount()
        {
            return cachedEvents.Count(r => r.Value != null);
        }

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

public int GetLandblockInstancesCacheCount()
        {
            return cachedLandblockInstances.Count(r => r.Value != null);
        }

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

public int GetPointsOfInterestCacheCount()
        {
            return cachedPointsOfInterest.Count(r => r.Value != null);
        }

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

public int GetSpellCacheCount()
        {
            return spellCache.Count(r => r.Value != null);
        }

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

public int GetDeathTreasureCacheCount()
        {
            return cachedDeathTreasure.Count(r => r.Value != null);
        }

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

public int GetWieldedTreasureCacheCount()
        {
            return cachedWieldedTreasure.Count(r => r.Value != null);
        }

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

public static bool ResolveACEParameters(Session session, IEnumerable<string> aceParsedParameters, IEnumerable<ACECommandParameter> parameters, bool rawIncluded = false)
        {
            string parameterBlob = "";
            if (rawIncluded)
            {
                parameterBlob = aceParsedParameters.First();
            }
            else
            {
                parameterBlob = aceParsedParameters.Count() > 0 ? aceParsedParameters.Aggregate((a, b) => a + " " + b).Trim(new char[] { ' ', ',' }) : string.Empty;
            }
            int commaCount = parameterBlob.Count(x => x == ',');

            List<ACECommandParameter> acps = parameters.ToList();
            for (int i = acps.Count - 1; i > -1; i--)
            {
                ACECommandParameter acp = acps[i];
                acp.ParameterNo = i + 1;
                if (parameterBlob.Length > 0)
                {
                    try
                    {
                        switch (acp.Type)
                        {
                            case ACECommandParameterType.PositiveLong:
                                Match match4 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match4.Success)
                                {
                                    if (!long.TryParse(match4.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    if (val <= 0)
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match4.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match4.Groups[1].Index).Trim(new char[] { ' ' });
                                }
                                break;
                            case ACECommandParameterType.Long:
                                Match match3 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match3.Success)
                                {
                                    if (!long.TryParse(match3.Groups[1].Value, out long val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match3.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match3.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.ULong:
                                Match match2 = Regex.Match(parameterBlob, @"(-?\d+)$", RegexOptions.IgnoreCase);
                                if (match2.Success)
                                {
                                    if (!ulong.TryParse(match2.Groups[1].Value, out ulong val))
                                    {
                                        return false;
                                    }
                                    acp.Value = val;
                                    acp.Defaulted = false;
                                    parameterBlob = (match2.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match2.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                }
                                break;
                            case ACECommandParameterType.Location:
                                Position position = null;
                                Match match = Regex.Match(parameterBlob, @"([\d\.]+[ns])[^\d\.]*([\d\.]+[ew])$", RegexOptions.IgnoreCase);
                                if (match.Success)
                                {
                                    string ns = match.Groups[1].Value;
                                    string ew = match.Groups[2].Value;
                                    if (!TryParsePosition(new string[] { ns, ew }, out string errorMessage, out position))
                                    {
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMessage, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMessage);
                                        }
                                        return false;
                                    }
                                    else
                                    {
                                        acp.Value = position;
                                        acp.Defaulted = false;
                                        int coordsStartPos = Math.Min(match.Groups[1].Index, match.Groups[2].Index);
                                        parameterBlob = (coordsStartPos == 0) ? string.Empty : parameterBlob.Substring(0, coordsStartPos).Trim(new char[] { ' ', ',' });
                                    }
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                Player targetPlayer = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer == null)
                                {
                                    string errorMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(errorMsg);
                                    }
                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerNameOrIid:
                                if (i != 0)
                                {
                                    throw new Exception("Player parameter must be the first parameter, since it can contain spaces.");
                                }

                                if (!parameterBlob.Contains(' '))
                                {
                                    if (uint.TryParse(parameterBlob, out uint iid))
                                    {
                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {iid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            break;
                                        }
                                    }
                                }
                                Player targetPlayer3 = PlayerManager.GetOnlinePlayer(parameterBlob);
                                if (targetPlayer3 == null)
                                {
                                    string logMsg = $"Unable to find player {parameterBlob}";
                                    if (session != null)
                                    {
                                        ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                    }
                                    else
                                    {
                                        Console.WriteLine(logMsg);
                                    }

                                    return false;
                                }
                                else
                                {
                                    acp.Value = targetPlayer3;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.OnlinePlayerIid:
                                Match matcha5 = Regex.Match(parameterBlob, /*((i == 0) ? "" : @"\s+") +*/ @"(\d{10})$|(0x[0-9a-f]{8})$", RegexOptions.IgnoreCase);
                                if (matcha5.Success)
                                {
                                    string strIid = "";
                                    if (matcha5.Groups[2].Success)
                                    {
                                        strIid = matcha5.Groups[2].Value;
                                    }
                                    else if (matcha5.Groups[1].Success)
                                    {
                                        strIid = matcha5.Groups[1].Value;
                                    }
                                    try
                                    {
                                        uint iid = 0;
                                        if (strIid.StartsWith("0x"))
                                        {
                                            iid = Convert.ToUInt32(strIid, 16);
                                        }
                                        else
                                        {
                                            iid = uint.Parse(strIid);
                                        }

                                        Player targetPlayer2 = PlayerManager.GetOnlinePlayer(iid);
                                        if (targetPlayer2 == null)
                                        {
                                            string logMsg = $"Unable to find player with iid {strIid}";
                                            if (session != null)
                                            {
                                                ChatPacket.SendServerMessage(session, logMsg, ChatMessageType.Broadcast);
                                            }
                                            else
                                            {
                                                Console.WriteLine(logMsg);
                                            }
                                            return false;
                                        }
                                        else
                                        {
                                            acp.Value = targetPlayer2;
                                            acp.Defaulted = false;
                                            parameterBlob = (matcha5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, matcha5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        string errorMsg = $"Unable to parse {strIid} into a player iid";
                                        if (session != null)
                                        {
                                            ChatPacket.SendServerMessage(session, errorMsg, ChatMessageType.Broadcast);
                                        }
                                        else
                                        {
                                            Console.WriteLine(errorMsg);
                                        }
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.PlayerName:
                                if (i != 0)
                                {
                                    throw new Exception("Player name parameter must be the first parameter, since it can contain spaces.");
                                }
                                parameterBlob = parameterBlob.TrimEnd(new char[] { ' ', ',' });
                                if (string.IsNullOrWhiteSpace(parameterBlob))
                                {
                                    break;
                                }
                                else
                                {
                                    acp.Value = parameterBlob;
                                    acp.Defaulted = false;
                                }
                                break;
                            case ACECommandParameterType.Uri:
                                Match match5 = Regex.Match(parameterBlob, @"(https?:\/\/(www\.)?[[email protected]:%._\+~#=]{2,256}\.[a-z]{2,6}\b([[email protected]:%_\+.~#?&//=]*))$", RegexOptions.IgnoreCase);
                                if (match5.Success)
                                {
                                    string strUri = match5.Groups[1].Value;
                                    try
                                    {
                                        Uri url = new Uri(strUri);
                                        acp.Value = url;
                                        acp.Defaulted = false;
                                        parameterBlob = (match5.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match5.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.DoubleQuoteEnclosedText:
                                Match match6 = Regex.Match(parameterBlob.TrimEnd(), @"(\"".*\"")$", RegexOptions.IgnoreCase);
                                if (match6.Success)
                                {
                                    string txt = match6.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.Trim('"');
                                        acp.Defaulted = false;
                                        parameterBlob = (match6.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match6.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.CommaPrefixedText:
                                if (i == 0)
                                {
                                    throw new Exception("this parameter type is not appropriate as the first parameter");
                                }
                                if (i == acps.Count - 1 && !acp.Required && commaCount < acps.Count - 1)
                                {
                                    break;
                                }
                                Match match7 = Regex.Match(parameterBlob.TrimEnd(), @"\,\s*([^,]*)$", RegexOptions.IgnoreCase);
                                if (match7.Success)
                                {
                                    string txt = match7.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(new char[] { ' ', ',' });
                                        acp.Defaulted = false;
                                        parameterBlob = (match7.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match7.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.SimpleWord:
                                Match match8 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match8.Success)
                                {
                                    string txt = match8.Groups[1].Value;
                                    try
                                    {
                                        acp.Value = txt.TrimStart(' ');
                                        acp.Defaulted = false;
                                        parameterBlob = (match8.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match8.Groups[1].Index).Trim(new char[] { ' ', ',' });
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                            case ACECommandParameterType.Enum:
                                if (acp.PossibleValues == null)
                                {
                                    throw new Exception("The enum parameter type must be accompanied by the PossibleValues");
                                }
                                if (!acp.PossibleValues.IsEnum)
                                {
                                    throw new Exception("PossibleValues must be an enum type");
                                }
                                Match match9 = Regex.Match(parameterBlob.TrimEnd(), @"([a-zA-Z1-9_]+)\s*$", RegexOptions.IgnoreCase);
                                if (match9.Success)
                                {
                                    string txt = match9.Groups[1].Value;
                                    try
                                    {
                                        txt = txt.Trim(new char[] { ' ', ',' });
                                        Array etvs = Enum.GetValues(acp.PossibleValues);
                                        foreach (object etv in etvs)
                                        {
                                            if (etv.ToString().ToLower() == txt.ToLower())
                                            {
                                                acp.Value = etv;
                                                acp.Defaulted = false;
                                                parameterBlob = (match9.Groups[1].Index == 0) ? string.Empty : parameterBlob.Substring(0, match9.Groups[1].Index).Trim(new char[] { ' ' });
                                                break;
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                        return false;
                                    }
                                }
                                break;
                        }
                    }
                    catch
                    {
                        return false;
                    }
                }
                if (acp.Defaulted)
                {
                    acp.Value = acp.DefaultValue;
                }

                if (acp.Required && acp.Defaulted)
                {
                    if (!string.IsNullOrWhiteSpace(acp.ErrorMessage))
                    {
                        if (session != null)
                        {
                            ChatPacket.SendServerMessage(session, acp.ErrorMessage, ChatMessageType.Broadcast);
                        }
                        else
                        {
                            Console.WriteLine(acp.ErrorMessage);
                        }
                    }

                    return false;
                }
            }
            return true;
        }

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

public int NumTinkers(MaterialType type)
        {
            return Tinkers.Count(i => i == type);
        }

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

public static int GetSessionCount()
        {
            sessionLock.EnterReadLock();
            try
            {
                return sessionMap.Count(s => s != null);
            }
            finally
            {
                sessionLock.ExitReadLock();
            }
        }

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

public static int GetAuthenticatedSessionCount()
        {
            sessionLock.EnterReadLock();
            try
            {
                return sessionMap.Count(s => s != null && s.AccountId != 0);
            }
            finally
            {
                sessionLock.ExitReadLock();
            }
        }

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

public static bool IsAccountAtMaxCharacterSlots(string accountName)
        {
            var slotsAvailable = (int)PropertyManager.GetLong("max_chars_per_account").Item;
            var onlinePlayersTotal = 0;
            var offlinePlayersTotal = 0;

            playersLock.EnterReadLock();
            try
            {
                onlinePlayersTotal = onlinePlayers.Count(a => a.Value.Account.AccountName.Equals(accountName, StringComparison.OrdinalIgnoreCase));
                offlinePlayersTotal = offlinePlayers.Count(a => a.Value.Account.AccountName.Equals(accountName, StringComparison.OrdinalIgnoreCase));
            }
            finally
            {
                playersLock.ExitReadLock();
            }

            return (onlinePlayersTotal + offlinePlayersTotal) >= slotsAvailable;
        }

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

private int CountPackItems()
        {
            return Inventory.Values.Count(wo => !wo.UseBackpackSlot);
        }

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

private int CountContainers()
        {
            return Inventory.Values.Count(wo => wo.UseBackpackSlot);
        }

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

public int GetHookGroupCurrentCount(HookGroupType hookGroupType) => Hooks.Count(h => h.HasItem && (h.Item?.HookGroup ?? HookGroupType.Undef) == hookGroupType);

19 View Source File : Favorites.cs
License : MIT License
Project Creator : acoppes

public bool IsFavorite(Object reference)
        {
            return favoritesList.Count(f => f.reference == reference) > 0;
        }

19 View Source File : SelectionHistory.cs
License : MIT License
Project Creator : acoppes

public void RemoveEntries(Entry.State state)
        {
            var deletedCount = _history.Count(e => e.GetReferenceState() == state);

            var currentSelectionDestroyed = currentSelection == null || currentSelection.GetReferenceState() == state;
            
            _history.RemoveAll(e => e.GetReferenceState() == state);

            currentSelectionIndex -= deletedCount;

            if (currentSelectionIndex < 0)
                currentSelectionIndex = 0;

            if (currentSelectionDestroyed)
                currentSelectionIndex = -1;
        }

19 View Source File : Game.cs
License : Microsoft Public License
Project Creator : achimismaili

public void PlayAt(int row, int column)
        {
            var emptyCellsCount = _board.SelectMany(s=>s).Count(s => s == N);
            var player = X;
            if (emptyCellsCount % 2 == 0)
                player = O;

            _board[row][column] = player;
        }

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

private static bool CheckForMultipleSpecialAttributes(SymbolreplacedysisContext symbolContext, PXContext pxContext,
															  List<(AttributeInfo Attribute, List<FieldTypeAttributeInfo> Infos)> attributesWithInfos)
		{
			var (specialAttributesDeclaredOnDacProperty, specialAttributesWithConflictingAggregatorDeclarations) = FilterSpecialAttributes();

			if (specialAttributesDeclaredOnDacProperty.Count == 0 ||
				(specialAttributesDeclaredOnDacProperty.Count == 1 && specialAttributesWithConflictingAggregatorDeclarations.Count == 0))
			{
				return true;
			}

			if (specialAttributesDeclaredOnDacProperty.Count > 1)
			{
				RegisterDiagnosticForAttributes(symbolContext, pxContext, specialAttributesDeclaredOnDacProperty,
												Descriptors.PX1023_MultipleSpecialTypeAttributesOnProperty);
			}

			if (specialAttributesWithConflictingAggregatorDeclarations.Count > 0)
			{
				RegisterDiagnosticForAttributes(symbolContext, pxContext, specialAttributesDeclaredOnDacProperty,
												Descriptors.PX1023_MultipleSpecialTypeAttributesOnAggregators);
			}

			return false;

			//-----------------------------------------------Local Functions---------------------------------------
			(List<AttributeInfo>, List<AttributeInfo>) FilterSpecialAttributes()
			{
				List<AttributeInfo> specialAttributesOnDacProperty = new List<AttributeInfo>(2);
				List<AttributeInfo> specialAttributesInvalidAggregatorDeclarations = new List<AttributeInfo>(2);

				foreach (var (attribute, infos) in attributesWithInfos)
				{
					int countOfSpecialAttributeInfos = infos.Count(atrInfo => atrInfo.IsSpecial);

					if (countOfSpecialAttributeInfos > 0)
					{
						specialAttributesOnDacProperty.Add(attribute);
					}

					if (countOfSpecialAttributeInfos > 1)
					{
						specialAttributesInvalidAggregatorDeclarations.Add(attribute);
					}
				}

				return (specialAttributesOnDacProperty, specialAttributesInvalidAggregatorDeclarations);
			}
		}

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 : PXGraphEventSemanticModel.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private bool IsValidGraphEvent(IMethodSymbol eventCandidate, EventHandlerSignatureType signatureType, GraphEventCategory eventCategory)
		{
			if (eventCandidate.IsStatic || eventCandidate.Parameters.Length > 2 || eventCategory == GraphEventCategory.None)
				return false;
			else if (signatureType != EventHandlerSignatureType.Default)
				return true;

			const char underscore = '_';

			if (eventCandidate.Name[0] == underscore || eventCandidate.Name[eventCandidate.Name.Length - 1] == underscore)
				return false;

			int underscoresCount = eventCandidate.Name.Count(c => c == underscore);

			return eventCategory switch
			{
				GraphEventCategory.Row => underscoresCount == 1,
				GraphEventCategory.Field => underscoresCount == 2,
				_ => false,
			};

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

protected virtual ChangeInfluenceScope? GetChangeScopeFromBlockNode(BlockSyntax blockNode, in TextChange textChange,
																			ContainmentModeChange containingModeChange)
		{
			if (!(blockNode.Parent is MemberDeclarationSyntax))
				return ChangeInfluenceScope.StatementsBlock;

			bool changeContainedOpenBrace = textChange.Span.Contains(blockNode.OpenBraceToken.Span);
			bool changeContainedCloseBrace = textChange.Span.Contains(blockNode.CloseBraceToken.Span);
			int openBracesNewCount = textChange.NewText.Count(c => c == '{');
			int closeBracesNewCount = textChange.NewText.Count(c => c == '}');

			if (changeContainedOpenBrace && openBracesNewCount != 1)
				return ChangeInfluenceScope.Clreplaced;
			else if (changeContainedCloseBrace && closeBracesNewCount != 1)
				return ChangeInfluenceScope.Clreplaced;
			else
				return ChangeInfluenceScope.StatementsBlock;
		}

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

public override Task<IdenreplacedyResult> ValidateAsync(string item)
		{
			if (item == null)
			{
				throw new ArgumentNullException("item");
			}

			var errors = new List<string>();

			if (string.IsNullOrWhiteSpace(item) || item.Length < RequiredLength)
			{
				errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordTooShort(RequiredLength)));
			}

			var failsRequireNonLetterOrDigit = item.All(IsLetterOrDigit);

			if (RequireNonLetterOrDigit && failsRequireNonLetterOrDigit)
			{
				errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresNonLetterAndDigit()));
			}

			var failsRequireDigit = item.All(c => !IsDigit(c));

			if (RequireDigit && failsRequireDigit)
			{
				errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresDigit()));
			}

			var failsRequireLowercase = item.All(c => !IsLower(c));

			if (RequireLowercase && failsRequireLowercase)
			{
				errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresLower()));
			}

			var failsRequireUppercase = item.All(c => !IsUpper(c));

			if (RequireUppercase && failsRequireUppercase)
			{
				errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresUpper()));
			}

			var preplacedes = new[] { !failsRequireNonLetterOrDigit, !failsRequireDigit, !failsRequireLowercase, !failsRequireUppercase };
			var preplacedCount = preplacedes.Count(preplaced => preplaced);

			if (EnforcePreplacedwordPolicy && preplacedCount < 3)
			{
				errors.Add(ToResult(IdenreplacedyErrors.PreplacedwordRequiresThreeClreplacedes()));
			}

			if (errors.Count == 0)
			{
				return Task.FromResult(IdenreplacedyResult.Success);
			}

			return Task.FromResult(IdenreplacedyResult.Failed(string.Join(" ", errors)));
		}

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

private void RespawnChests()
        {
            Utility.ForAllLocations(delegate(GameLocation l)
            {
                if (l is FarmHouse || (!Config.AllowIndoorSpawns && !l.IsOutdoors) || !IsLocationAllowed(l))
                    return;

                Monitor.Log($"Respawning chests in {l.name}");
                IList<Vector2> objectsToRemovePos = l.overlayObjects
                    .Where(o => o.Value is Chest && o.Value.Name.StartsWith(namePrefix))
                    .Select(o => o.Key)
                    .ToList();
                int rem = objectsToRemovePos.Count;
                foreach (var pos in objectsToRemovePos)
                {
                    l.overlayObjects.Remove(pos);
                }
                Monitor.Log($"Removed {rem} chests");
                int width = l.map.Layers[0].LayerWidth;
                int height = l.map.Layers[0].LayerHeight;
                bool IsValid(Vector2 v) => !l.isWaterTile((int)v.X, (int)v.Y) && !l.isTileOccupiedForPlacement(v) && !l.isCropAtTile((int)v.X, (int)v.Y);
                bool IsValidIndex(int i) => IsValid(new Vector2(i % width, i / width));
                int freeTiles = Enumerable.Range(0, width * height).Count(IsValidIndex);
                Monitor.Log($"Got {freeTiles} free tiles");
                int maxChests = Math.Min(freeTiles, (int)Math.Floor(freeTiles * Config.ChestDensity) + (Config.RoundNumberOfChestsUp ? 1 : 0));
                Monitor.Log($"Max chests: {maxChests}");
                while (maxChests > 0)
                {
                    Vector2 freeTile = l.getRandomTile();
                    if (!IsValid(freeTile))
                        continue;
                    Chest chest;
                    if (advancedLootFrameworkApi == null)
                    {
                        //Monitor.Log($"Adding ordinary chest");
                        chest = new Chest(0, new List<Item>() { MineShaft.getTreasureRoomItem() }, freeTile, false, 0);
                    }
                    else
                    {
                        double fraction = Math.Pow(myRand.NextDouble(), 1 / Config.RarityChance);
                        int level = (int)Math.Ceiling(fraction * Config.Mult);
                        //Monitor.Log($"Adding expanded chest of value {level} to {l.name}");
                        chest = advancedLootFrameworkApi.MakeChest(treasuresList, Config.ItemListChances, Config.MaxItems, Config.MinItemValue, Config.MaxItemValue, level, Config.IncreaseRate, Config.ItemsBaseMaxValue, Config.CoinBaseMin, Config.CoinBaseMax, freeTile);
                        chest.playerChoiceColor.Value = MakeTint(fraction);
                    }
                    chest.name = namePrefix;
                    l.overlayObjects[freeTile] = chest;
                    maxChests--;
                }
            });
        }

19 View Source File : Weapon.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public override string DetermineDescription()
        {
            string description = "";

            string particle = "A";
            switch (weaponName[0]) {
                case ('a'): case ('e'):
                case ('i'): case ('o'):
                case ('u'):
                case ('A'): case ('E'):
                case ('I'): case ('O'):
                case ('U'):
                    particle = "An";
                    break;
            }
            if (enchantments == null || enchantments.Count == 0)
                return $"{particle} {weaponName}.";
            else
            {
                description = $"An enchanted {weaponName} which ";

                foreach (WeaponEnchantment enchant in enchantments)
                    if (enchant.AppliedEffect != null)
                        description += $"has a {enchant.AppliedEffect.Chance}% chance to inflict {enchant.AppliedEffect.Name}, ";

                foreach (WeaponEnchantment enchant in enchantments)
                    if (enchant.VictimDamage != 0)
                        description += $"deals {enchant.VictimDamage} {enchant.DamageType.ToString().ToLower()} dmg, ";

                description = description.Substring(0, description.LastIndexOf(',')) + '.';

                if (description.Count(c => c == ',') > 0)
                {
                    int commaIndex = description.LastIndexOf(',');
                    description = description.Substring(0, commaIndex) + " and " + description.Substring(commaIndex + 2, description.Length - (commaIndex + 2));
                }

                return description;
            }


        }

19 View Source File : Creature.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

private void LvlArmorSkill(int amount)
        {
            List<Armor> equipment = Body.GetArmorList();
            int lightArmorPieces = equipment.Count(armor => armor.GetSkill() == Skill.LightArmor);
            int heavyArmorPieces = equipment.Count(armor => armor.GetSkill() == Skill.HeavyArmor);

            if (lightArmorPieces == heavyArmorPieces)
            {
                Stats.LvlSkill(Skill.LightArmor, amount / 2, this);
                Stats.LvlSkill(Skill.HeavyArmor, amount / 2, this);
            }
            if (lightArmorPieces > heavyArmorPieces)
                Stats.LvlSkill(Skill.LightArmor, amount, this);
            else if (lightArmorPieces == 0 && heavyArmorPieces == 0)
                Stats.LvlSkill(Skill.Unarmored, amount, this);
            else
                Stats.LvlSkill(Skill.HeavyArmor, amount, this);
        }

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

public static int GetLen(this string a)
        {
            if (string.IsNullOrWhiteSpace(a))
                return 0;
            return a.Length + a.Count(p => p > 255);
        }

19 View Source File : WebvttSubripConverter.cs
License : GNU General Public License v3.0
Project Creator : AhmedOS

public String ConvertToSubrip(String webvttSubreplacedle)
        {
            StringReader reader = new StringReader(webvttSubreplacedle);
            StringBuilder output = new StringBuilder();
            int lineNumber = 1;
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (IsTimecode(line))
                {

                    output.AppendLine(lineNumber.ToString());
                    lineNumber++;

                    line = line.Replace('.', ',');

                    line = DeleteCueSettings(line);

                    string timeSrt1 = line.Substring(0, line.IndexOf('-'));
                    string timeSrt2 = line.Substring(line.IndexOf('>') + 1);
                    int divIt1 = timeSrt1.Count(x => x == ':');
                    int divIt2 = timeSrt1.Count(x => x == ':');

                    string timeFormat = simpleTimeFormat;
                    if (divIt1 != divIt2)
                        throw new Exception(Strings.invalidTimeFormat);

                    if (divIt1 == 2 && divIt2 == 2)
                        timeFormat = extendedTimeFormat;

                    DateTime timeAux1 = DateTime.ParseExact(timeSrt1.Trim(), timeFormat, CultureInfo.InvariantCulture);
                    DateTime timeAux2 = DateTime.ParseExact(timeSrt2.Trim(), timeFormat, CultureInfo.InvariantCulture);
                    line = timeAux1.ToString(extendedTimeFormat) + " --> " + timeAux2.ToString(extendedTimeFormat);

                    output.AppendLine(line);

                    bool foundCaption = false;
                    while (true)
                    {
                        if ((line = reader.ReadLine()) == null)
                        {
                            if (foundCaption)
                                break;
                            else
                                throw new Exception(Strings.invalidFile);
                        }
                        if (String.IsNullOrEmpty(line) || String.IsNullOrWhiteSpace(line))
                        {
                            output.AppendLine();
                            break;
                        }
                        foundCaption = true;
                        output.AppendLine(line);
                    }
                }
            }
            return output.ToString();
        }

19 View Source File : EFExtends.cs
License : MIT License
Project Creator : AiursoftWeb

public static void Sync<T, M>(this DbSet<T> dbSet,
            Expression<Func<T, bool>> filter,
            IList<M> collection)
            where T : clreplaced
            where M : ISyncable<T>
        {
            foreach (var item in collection.DistinctBySync<T, M>())
            {
                var itemCountShallBe = collection.Count(t => t.EqualsInDb(item.Map()));
                var items = dbSet
                    .IgnoreQueryFilters()
                    .Where(filter)
                    .AsEnumerable()
                    .Where(t => item.EqualsInDb(t))
                    .ToList();
                var itemCount = items.Count;

                if (itemCount > itemCountShallBe)
                {
                    dbSet.RemoveRange(items.Skip(itemCountShallBe));
                }
                else if (itemCount < itemCountShallBe)
                {
                    for (int i = 0; i < itemCountShallBe - itemCount; i++)
                    {
                        dbSet.Add(item.Map());
                    }
                }
            }
            var toDelete = dbSet
                .Where(filter)
                .AsEnumerable()
                .Where(t => !collection.Any(p => p.EqualsInDb(t)));
            dbSet.RemoveRange(toDelete);
        }

19 View Source File : MissionGeneratorImages.cs
License : GNU General Public License v3.0
Project Creator : akaAgar

internal void GenerateKneeboardImage(DCSMission mission)
        {
            var text = mission.Briefing.GetBriefingKneeBoardText();
            var blocks = text.Split(new string[] {"\r\n\r\n"}, StringSplitOptions.RemoveEmptyEntries);
            var pages = new List<string>();
            var buildingPage = "";
            foreach (var block in blocks)
            {
                if(buildingPage.Count(f => f =='\n') + block.Count(f => f =='\n') > 32) {
                    pages.Add(buildingPage);
                    buildingPage = "";
                }
                buildingPage = $"{buildingPage}{block}\n\n";  
            }
            if(!String.IsNullOrWhiteSpace(buildingPage))
                pages.Add(buildingPage);


            var inc = 1;
            foreach (var page in pages)
            {
                byte[] imageBytes;
                using (ImageMaker imgMaker = new ImageMaker())
                {
                    imgMaker.ImageSizeX = 800;
                    imgMaker.ImageSizeY = 1200;
                    imgMaker.TextOverlay.Shadow = false;
                    imgMaker.TextOverlay.Color = Color.Black;
                    imgMaker.TextOverlay.Text =  $"{page}\n {inc}/{pages.Count()}";
                    imgMaker.TextOverlay.FontSize = 14.0f;
                    imgMaker.TextOverlay.FontFamily = "Arial";
                    imgMaker.TextOverlay.Alignment = ContentAlignment.TopLeft;

                    List<ImageMakerLayer> layers = new List<ImageMakerLayer>{
                        new ImageMakerLayer("notebook.png")
                    };

                    var random = new Random();

                    if(random.Next(100) < 3)
                        layers.Add(easterEggLogos[random.Next(easterEggLogos.Count)]);


                    imageBytes = imgMaker.GetImageBytes(layers.ToArray());
                }
                mission.AddMediaFile($"KNEEBOARD/IMAGES/comms_{mission.UniqueID}_{inc}.jpg", imageBytes);
                inc++;
            }
        }

19 View Source File : OutfitPatcher.cs
License : MIT License
Project Creator : AkiniKites

private void UpdateModelVariants(Patch patch, IEnumerable<OutfitDetail> outfits, bool modifiedOnly, 
            Func<OutfitDetail, HzdCore, HumanoidBodyVariant, bool> updateVariant)
        {
            foreach (var group in outfits.Where(x => !modifiedOnly || x.Modified).GroupBy(x => x.Model.Source))
            {
                var core = patch.AddFile(group.Key);

                var changes = new List<(BaseGGUUID SourceId, BaseGGUUID NewId, 
                    HumanoidBodyVariant Data, Action collapse)>();
                var variants = core.GetTypesById<HumanoidBodyVariant>();

                foreach (var outfit in group)
                {
                    var variant = variants[outfit.VariantId];

                    //copy the variant
                    var newVariant = CopyVariant(variant, out var isOriginal);

                    if (updateVariant(outfit, core, newVariant))
                    {
                        void collapseVariant()
                        {
                            //okay to collapse armor variants into original
                            if (isOriginal && outfit.IsCharacter) return;
                            
                            core.Binary.RemoveObject(variant);
                            newVariant.ObjectUUID = variant.ObjectUUID;
                            outfit.VariantId = variant.ObjectUUID;

                            if (isOriginal)
                                newVariant.Name.Value = variant.Name.Value;
                        }

                        var change = changes.FirstOrDefault(x => HzdUtils.EqualsIgnoreId(x.Data, newVariant));
                        if (change.NewId != null)
                        {
                            changes.Add((change.SourceId, change.NewId, null, () =>
                            {
                                //okay to collapse armor variants into original
                                if (isOriginal && outfit.IsCharacter) return;

                                outfit.VariantId = variant.ObjectUUID;
                            }));

                            outfit.VariantId = change.NewId;
                            continue;
                        }
                        
                        changes.Add((variant.ObjectUUID, newVariant.ObjectUUID, newVariant, collapseVariant));
                        outfit.VariantId = newVariant.ObjectUUID;
                        core.Binary.AddObject(newVariant);
                    }
                }

                //only 1 new variant copy, collapse changes into original
                foreach (var changeGroup in changes.GroupBy(x => x.SourceId)
                    .Where(g => g.Count(x => x.Data != null) == 1))
                {
                    foreach (var change in changeGroup)
                        change.collapse();
                }

                if (changes.Any())
                {
                    core.Save();
                }
            }
        }

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

public override string ToString() => string.Join(", ", EnsembleCharacterDatas.Select(i => $"{i.CharacterId:X}:{i.NoteNumbers.Count(j => j != 0)}"));

19 View Source File : VariablesList.cs
License : MIT License
Project Creator : alaabenfatma

private void VariableName_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (_varList.SelectedItem != null)
            {
                var item = (VariableItem) _varList.SelectedItem;
                item.Name = _variableName.Text;
                var index = _backupVariables.IndexOf(item);
                _backupVariables[index].Name = item.Name;
                RenameNodes(ref item);
            }

            var c = _variables.Count(item => item.Name == _variableName.Text);
            var varListSelectedItem = (VariableItem) _varList.SelectedItem;
            if (varListSelectedItem != null && (c > 1 || varListSelectedItem.Name == ""))
                _variableName.Foreground = Brushes.Red;
            else
                _variableName.Foreground = Brushes.AliceBlue;

            if (Equals(_variableName.Foreground, Brushes.AliceBlue)) return;

            _variableName.Focus();
            _variableName.CaretIndex = _variableName.Text.Length;
            e.Handled = true;
        }

19 View Source File : Startup.cs
License : MIT License
Project Creator : alanedwardes

public void ConfigureServices(IServiceCollection services)
        {
            const string LfsBucketVariable = "LFS_BUCKET";
            const string LfsUsernameVariable = "LFS_USERNAME";
            const string LfsPreplacedwordVariable = "LFS_PreplacedWORD";
            const string GitHubOrganisationVariable = "GITHUB_ORGANISATION";
            const string GitHubRepositoryVariable = "GITHUB_REPOSITORY";
            const string BitBucketWorkspaceVariable = "BITBUCKET_WORKSPACE";
            const string BitBucketRepositoryVariable = "BITBUCKET_REPOSITORY";
            const string S3AccelerationVariable = "S3_ACCELERATION";
            const string LfsAzureStorageConnectionStringVariable = "LFS_AZUREBLOB_CONNECTIONSTRING";
            const string LfsAzureStorageContainerNameVariable = "LFS_AZUREBLOB_CONTAINERNAME";

            var config = new ConfigurationBuilder()
                .AddEnvironmentVariables()
                .Build();

            string lfsBucket = config[LfsBucketVariable];
            string lfsAzureStorageConnectionString = config[LfsAzureStorageConnectionStringVariable];
            string lfsUsername = config[LfsUsernameVariable];
            string lfsPreplacedword = config[LfsPreplacedwordVariable];
            string gitHubOrganisation = config[GitHubOrganisationVariable];
            string gitHubRepository = config[GitHubRepositoryVariable];
            string bitBucketWorkspace = config[BitBucketWorkspaceVariable];
            string bitBucketRepository = config[BitBucketRepositoryVariable];
            bool s3Acceleration = bool.Parse(config[S3AccelerationVariable] ?? "false");

            bool isS3Storage = !string.IsNullOrWhiteSpace(lfsBucket);
            bool isAzureStorage = !string.IsNullOrWhiteSpace(lfsAzureStorageConnectionString);
            bool isDictionaryAuthentication = !string.IsNullOrWhiteSpace(lfsUsername) && !string.IsNullOrWhiteSpace(lfsPreplacedword);
            bool isGitHubAuthentication = !string.IsNullOrWhiteSpace(gitHubOrganisation) && !string.IsNullOrWhiteSpace(gitHubRepository);
            bool isBitBucketAuthentication = !string.IsNullOrWhiteSpace(bitBucketWorkspace) && !string.IsNullOrWhiteSpace(bitBucketRepository);

            // If all authentication mechanims are set, or none are set throw an error
            if (new[] {isDictionaryAuthentication, isGitHubAuthentication, isBitBucketAuthentication}.Count(x => x) != 1)
            {
                throw new InvalidOperationException($"Unable to detect authentication mechanism. Please set {LfsUsernameVariable} and {LfsPreplacedwordVariable} for simple user/preplacedword auth" +
                                                    $" or {GitHubOrganisationVariable} and {GitHubRepositoryVariable} for authentication against that repository on GitHub");
            }

            if (isDictionaryAuthentication)
            {
                services.AddLfsDictionaryAuthenticator(new Dictionary<string, string> { { lfsUsername, lfsPreplacedword } });
            }

            if (isGitHubAuthentication)
            {
                services.AddLfsGitHubAuthenticator(new GitHubAuthenticatorConfig { Organisation = gitHubOrganisation, Repository = gitHubRepository });
            }

            if (isBitBucketAuthentication)
            {
                services.AddLfsBitBucketAuthenticator(new BitBucketAuthenticatorConfig { Workspace = bitBucketWorkspace, Repository = bitBucketRepository });
            }

            if (isS3Storage)
            {
                services.AddLfsS3Adapter(new S3BlobAdapterConfig { Bucket = lfsBucket }, new AmazonS3Client(new AmazonS3Config { UseAccelerateEndpoint = s3Acceleration }));
            }
            else if (isAzureStorage)
            {
                services.AddLfsAzureBlobAdapter(new AzureBlobAdapterConfig
                {
                    ConnectionString = lfsAzureStorageConnectionString,
                    ContainerName = config[LfsAzureStorageContainerNameVariable]
                });
            }
            else
            {
                throw new InvalidOperationException($"Missing environment variable {LfsBucketVariable} or {LfsAzureStorageConnectionStringVariable}.");
            }

            services.AddLfsApi();

            services.AddLogging(x => x.AddLambdaLogger());
        }

19 View Source File : ProceduralWorldsGUI.cs
License : MIT License
Project Creator : alelievr

private T		GetGUISettingData< T >(PWGUIFieldType fieldType, Func< T > newGUISettings) where T : PWGUISettings
		{
			if (!currentSettingIndices.ContainsKey(fieldType))
				currentSettingIndices[fieldType] = 0;
			
			int fieldIndex = currentSettingIndices[fieldType];

			//TODO: a more intelligent system to get back the stored GUI setting
			if (fieldIndex == settingsStorage.Count(s => s.fieldType == fieldType))
			{
				var s = newGUISettings();
				s.fieldType = fieldType;

				settingsStorage.Add(s);
			}

			int i = 0;
			var fieldSetting = settingsStorage.FirstOrDefault(s => {
				if (i == fieldIndex && s.fieldType == fieldType)
					return true;
				if (s.fieldType == fieldType)
					i++;
				return false;
			});

			currentSettingIndices[fieldType]++;
			return fieldSetting as T;
		}

19 View Source File : OutputNode.cs
License : MIT License
Project Creator : alelievr

protected override void Enable()
        {
            base.Enable();
			// Checks that the output have always at least one element:
			if (outputTextureSettings.Count == 0)
				AddTextureOutput(OutputTextureSettings.Preset.Color);

			// Sanitize main texture value:
			if (outputTextureSettings.Count((o => o.isMain)) != 1)
			{
				outputTextureSettings.ForEach(o => o.isMain = false);
				outputTextureSettings.First().isMain = true;
			}
		}

19 View Source File : AnchorField.cs
License : MIT License
Project Creator : alelievr

public void UpdateAnchors()
		{
			//if this anchor field is a multiple input, check if all our anchors are linked
			// and if so, add a new one
			if (multiple && anchorType == AnchorType.Input)
			{
				if (anchors.All(a => a.linkCount > 0))
					CreateNewAnchor();

				//if there are more than 1 unlinked anchor, delete the others:
				if (anchors.Count(a => a.linkCount == 0) > 1)
					RemoveDuplicatedUnlinkedAnchors();
			}
		}

19 View Source File : PlotPanel.cs
License : MIT License
Project Creator : AlexGyver

private void UpdateAxesPosition() {
      if (stackedAxes.Value) {
        var count = axes.Values.Count(axis => axis.IsAxisVisible);
        var start = 0.0;
        foreach (var pair in axes.Reverse()) {
          var axis = pair.Value;
          var type = pair.Key;
          axis.StartPosition = start;
          var delta = axis.IsAxisVisible ? 1.0 / count : 0;
          start += delta;
          axis.EndPosition = start;
          axis.PositionTier = 0;
          axis.MajorGridlineStyle = LineStyle.Solid;
          axis.MinorGridlineStyle = LineStyle.Solid;   
        }
      } else {
        var tier = 0;
        foreach (var pair in axes.Reverse()) {
          var axis = pair.Value;
          var type = pair.Key;
          if (axis.IsAxisVisible) {
            axis.StartPosition = 0;
            axis.EndPosition = 1;
            axis.PositionTier = tier;
            tier++;
          } else {
            axis.StartPosition = 0;
            axis.EndPosition = 0;
            axis.PositionTier = 0;
          }
          axis.MajorGridlineStyle = LineStyle.None;
          axis.MinorGridlineStyle = LineStyle.None;          
        }
      }

    }

19 View Source File : ValidatorBase.cs
License : Apache License 2.0
Project Creator : alexreinert

private async Task<SpfQualifier> CheckMechanismAsync(SpfMechanism mechanism, IPAddress ip, DomainName domain, string sender, State state, CancellationToken token)
		{
			switch (mechanism.Type)
			{
				case SpfMechanismType.All:
					return mechanism.Qualifier;

				case SpfMechanismType.A:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					DomainName aMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

					bool? isAMatch = await IsIpMatchAsync(aMechanismDomain, ip, mechanism.Prefix, mechanism.Prefix6, token);
					if (!isAMatch.HasValue)
						return SpfQualifier.TempError;

					if (isAMatch.Value)
					{
						return mechanism.Qualifier;
					}
					break;

				case SpfMechanismType.Mx:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					DomainName mxMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

					DnsResolveResult<MxRecord> dnsMxResult = await ResolveDnsAsync<MxRecord>(mxMechanismDomain, RecordType.Mx, token);
					if ((dnsMxResult == null) || ((dnsMxResult.ReturnCode != ReturnCode.NoError) && (dnsMxResult.ReturnCode != ReturnCode.NxDomain)))
						return SpfQualifier.TempError;

					int mxCheckedCount = 0;

					foreach (MxRecord mxRecord in dnsMxResult.Records)
					{
						if (++mxCheckedCount == 10)
							break;

						bool? isMxMatch = await IsIpMatchAsync(mxRecord.ExchangeDomainName, ip, mechanism.Prefix, mechanism.Prefix6, token);
						if (!isMxMatch.HasValue)
							return SpfQualifier.TempError;

						if (isMxMatch.Value)
						{
							return mechanism.Qualifier;
						}
					}
					break;

				case SpfMechanismType.Ip4:
				case SpfMechanismType.Ip6:
					IPAddress compareAddress;
					if (IPAddress.TryParse(mechanism.Domain, out compareAddress))
					{
						if (ip.AddressFamily != compareAddress.AddressFamily)
							return SpfQualifier.None;

						if (mechanism.Prefix.HasValue)
						{
							if ((mechanism.Prefix.Value < 0) || (mechanism.Prefix.Value > (compareAddress.AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32)))
								return SpfQualifier.PermError;

							if (ip.GetNetworkAddress(mechanism.Prefix.Value).Equals(compareAddress.GetNetworkAddress(mechanism.Prefix.Value)))
							{
								return mechanism.Qualifier;
							}
						}
						else if (ip.Equals(compareAddress))
						{
							return mechanism.Qualifier;
						}
					}
					else
					{
						return SpfQualifier.PermError;
					}

					break;

				case SpfMechanismType.Ptr:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					DnsResolveResult<PtrRecord> dnsPtrResult = await ResolveDnsAsync<PtrRecord>(ip.GetReverseLookupDomain(), RecordType.Ptr, token);
					if ((dnsPtrResult == null) || ((dnsPtrResult.ReturnCode != ReturnCode.NoError) && (dnsPtrResult.ReturnCode != ReturnCode.NxDomain)))
						return SpfQualifier.TempError;

					DomainName ptrMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

					int ptrCheckedCount = 0;
					foreach (PtrRecord ptrRecord in dnsPtrResult.Records)
					{
						if (++ptrCheckedCount == 10)
							break;

						bool? isPtrMatch = await IsIpMatchAsync(ptrRecord.PointerDomainName, ip, 0, 0, token);
						if (isPtrMatch.HasValue && isPtrMatch.Value)
						{
							if (ptrRecord.PointerDomainName.Equals(ptrMechanismDomain) || (ptrRecord.PointerDomainName.IsSubDomainOf(ptrMechanismDomain)))
								return mechanism.Qualifier;
						}
					}
					break;

				case SpfMechanismType.Exists:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					if (String.IsNullOrEmpty(mechanism.Domain))
						return SpfQualifier.PermError;

					DomainName existsMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

					DnsResolveResult<ARecord> dnsAResult = await ResolveDnsAsync<ARecord>(existsMechanismDomain, RecordType.A, token);
					if ((dnsAResult == null) || ((dnsAResult.ReturnCode != ReturnCode.NoError) && (dnsAResult.ReturnCode != ReturnCode.NxDomain)))
						return SpfQualifier.TempError;

					if (dnsAResult.Records.Count(record => (record.RecordType == RecordType.A)) > 0)
					{
						return mechanism.Qualifier;
					}
					break;

				case SpfMechanismType.Include:
					if (++state.DnsLookupCount > 10)
						return SpfQualifier.PermError;

					if (String.IsNullOrEmpty(mechanism.Domain))
						return SpfQualifier.PermError;

					DomainName includeMechanismDomain = String.IsNullOrEmpty(mechanism.Domain) ? domain : await ExpandDomainAsync(mechanism.Domain, ip, domain, sender, token);

					if (includeMechanismDomain.Equals(domain))
						return SpfQualifier.PermError;

					var includeResult = await CheckHostInternalAsync(ip, includeMechanismDomain, sender, false, state, token);
					switch (includeResult.Result)
					{
						case SpfQualifier.Preplaced:
							return mechanism.Qualifier;

						case SpfQualifier.Fail:
						case SpfQualifier.SoftFail:
						case SpfQualifier.Neutral:
							return SpfQualifier.None;

						case SpfQualifier.TempError:
							return SpfQualifier.TempError;

						case SpfQualifier.PermError:
						case SpfQualifier.None:
							return SpfQualifier.PermError;
					}
					break;

				default:
					return SpfQualifier.PermError;
			}

			return SpfQualifier.None;
		}

See More Examples