int.TryParse(string, System.Globalization.NumberStyles, System.IFormatProvider, out int)

Here are the examples of the csharp api int.TryParse(string, System.Globalization.NumberStyles, System.IFormatProvider, out int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3366 Examples 7

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

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;
                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, GitHubSourceProvider.ProblemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

19 View Source File : RawPriceDataParser.cs
License : MIT License
Project Creator : adainrivers

public bool TryParse(RawPriceData rawPriceData, out PriceData priceData)
        {
            PerformanceProfiler.Current?.Start("PriceDataParser.Parse");
            priceData = null;

            if (string.IsNullOrWhiteSpace(rawPriceData.ItemName) || string.IsNullOrWhiteSpace(rawPriceData.Availability) ||
                string.IsNullOrWhiteSpace(rawPriceData.Price))
            {
                PerformanceProfiler.Current?.Stop("PriceDataParser.Parse");
                return false;
            }


            var priceStr = rawPriceData.Price.Replace(",", string.Empty).Replace(".", "");

            if (priceStr == string.Empty)
            {
                PerformanceProfiler.Current?.Stop("PriceDataParser.Parse");
                return false;
            }

            var wholeStr = priceStr.Substring(0, priceStr.Length - 2);
            var fractionStr = priceStr.Substring(priceStr.Length - 2, 2);

            if (!int.TryParse(wholeStr, out var whole) || !int.TryParse(fractionStr, out var fraction))
            {
                PerformanceProfiler.Current?.Stop("PriceDataParser.Parse");
                return false;
            }

            var price = whole + (decimal)fraction / 100;

            if (!int.TryParse(rawPriceData.Availability.Trim(), out var availability))
            {
                PerformanceProfiler.Current?.Stop("PriceDataParser.Parse");
                return false;
            }

            int? gearScoreResult = null;
            if (!string.IsNullOrWhiteSpace(rawPriceData.GearScore) && int.TryParse(rawPriceData.GearScore.Trim(), out var gearScore) && gearScore >= 100)
            {
                gearScoreResult = gearScore;
            }

            var tier = RomanToInt(rawPriceData.Tier);

            var location = TerritoryFinder.GetTerritory(rawPriceData.Location);


            var item = ItemFinder.Gereplacedem(rawPriceData.ItemName, gearScoreResult, tier);
            if (item == null)
            {
                return false;
            }
            var currentTime = DateTime.UtcNow;
            priceData = new PriceData { ItemId = item.Id, ItemName = item.Name, Price = price, Availability = availability, GearScore = gearScoreResult, Tier = tier, LocationId = location?.TerritoryId, Location = location?.Name, TimeCreatedUtc = currentTime};

            PerformanceProfiler.Current?.Stop("PriceDataParser.Parse");
            return true;
        }

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

private async Task<ResultModel> CheckQuestIfComplete(PlayerEnreplacedy player, string targetStr)
        {
            var result = new ResultModel { IsSuccess = false };

            if (!string.IsNullOrEmpty(targetStr))
            {
                List<QuestTarget> questTargets = new List<QuestTarget>();
                try
                {
                    questTargets = JsonConvert.DeserializeObject<List<QuestTarget>>(targetStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestTarget:{ex}");
                }

                foreach (var questTarget in questTargets)
                {
                    var npcId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    var questId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val;
                    int.TryParse(questTarget.Attrs.FirstOrDefault(x => x.Attr == "RoomId")?.Val, out int roomId);

                    var targetEnum = (QuestTargetEnum)Enum.Parse(typeof(QuestTargetEnum), questTarget.Target, true);


                    switch (targetEnum)
                    {


                        case QuestTargetEnum.与某个Npc对话:
                            if (await _redisDb.StringGet<int>(string.Format(RedisKey.ChatWithNpc, player.Id, npcId)) != 1)
                            {
                                result.ErrorMessage = $"";
                                return result;
                            }
                            break;

                        case QuestTargetEnum.所在房间:
                            if (player.RoomId != roomId)
                            {
                                result.ErrorMessage = "";
                                return result;
                            }


                            break;

                    }
                }
            }





            result.IsSuccess = true;
            return result;
        }

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

public async Task RunAsync(RunnerActionPluginExecutionContext executionContext, CancellationToken token)
        {
            string runnerWorkspace = executionContext.GetRunnerContext("workspace");
            ArgUtil.Directory(runnerWorkspace, nameof(runnerWorkspace));
            string tempDirectory = executionContext.GetRunnerContext("temp");
            ArgUtil.Directory(tempDirectory, nameof(tempDirectory));

            var repoFullName = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Repository);
            if (string.IsNullOrEmpty(repoFullName))
            {
                repoFullName = executionContext.GetGitHubContext("repository");
            }

            var repoFullNameSplit = repoFullName.Split("/", StringSplitOptions.RemoveEmptyEntries);
            if (repoFullNameSplit.Length != 2)
            {
                throw new ArgumentOutOfRangeException(repoFullName);
            }

            string expectRepoPath;
            var path = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Path);
            if (!string.IsNullOrEmpty(path))
            {
                expectRepoPath = IOUtil.ResolvePath(runnerWorkspace, path);
                if (!expectRepoPath.StartsWith(runnerWorkspace.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar))
                {
                    throw new ArgumentException($"Input path '{path}' should resolve to a directory under '{runnerWorkspace}', current resolved path '{expectRepoPath}'.");
                }
            }
            else
            {
                // When repository doesn't has path set, default to sources directory 1/repoName
                expectRepoPath = Path.Combine(runnerWorkspace, repoFullNameSplit[1]);
            }

            var workspaceRepo = executionContext.GetGitHubContext("repository");
            // for self repository, we need to let the worker knows where it is after checkout.
            if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
            {
                var workspaceRepoPath = executionContext.GetGitHubContext("workspace");

                executionContext.Debug($"Repository requires to be placed at '{expectRepoPath}', current location is '{workspaceRepoPath}'");
                if (!string.Equals(workspaceRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), expectRepoPath.Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar), IOUtil.FilePathStringComparison))
                {
                    executionContext.Output($"Repository is current at '{workspaceRepoPath}', move to '{expectRepoPath}'.");
                    var count = 1;
                    var staging = Path.Combine(tempDirectory, $"_{count}");
                    while (Directory.Exists(staging))
                    {
                        count++;
                        staging = Path.Combine(tempDirectory, $"_{count}");
                    }

                    try
                    {
                        executionContext.Debug($"Move existing repository '{workspaceRepoPath}' to '{expectRepoPath}' via staging directory '{staging}'.");
                        IOUtil.MoveDirectory(workspaceRepoPath, expectRepoPath, staging, CancellationToken.None);
                    }
                    catch (Exception ex)
                    {
                        executionContext.Debug("Catch exception during repository move.");
                        executionContext.Debug(ex.ToString());
                        executionContext.Warning("Unable move and reuse existing repository to required location.");
                        IOUtil.DeleteDirectory(expectRepoPath, CancellationToken.None);
                    }

                    executionContext.Output($"Repository will locate at '{expectRepoPath}'.");
                }

                executionContext.Debug($"Update workspace repository location.");
                executionContext.SetRepositoryPath(repoFullName, expectRepoPath, true);
            }

            string sourceBranch;
            string sourceVersion;
            string refInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Ref);
            if (string.IsNullOrEmpty(refInput))
            {
                sourceBranch = executionContext.GetGitHubContext("ref");
                sourceVersion = executionContext.GetGitHubContext("sha");
            }
            else
            {
                sourceBranch = refInput;
                sourceVersion = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Version);  // version get removed when checkout move to repo in the graph
                if (string.IsNullOrEmpty(sourceVersion) && RegexUtility.IsMatch(sourceBranch, WellKnownRegularExpressions.SHA1))
                {
                    sourceVersion = sourceBranch;

                    // If Ref is a SHA and the repo is self, we need to use github.ref as source branch since it might be refs/pull/*
                    if (string.Equals(workspaceRepo, repoFullName, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceBranch = executionContext.GetGitHubContext("ref");
                    }
                    else
                    {
                        sourceBranch = "refs/heads/master";
                    }
                }
            }

            bool clean = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Clean), true);
            string submoduleInput = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Submodules);

            int fetchDepth = 0;
            if (!int.TryParse(executionContext.GetInput("fetch-depth"), out fetchDepth) || fetchDepth < 0)
            {
                fetchDepth = 0;
            }

            bool gitLfsSupport = StringUtil.ConvertToBoolean(executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Lfs));
            string accessToken = executionContext.GetInput(Pipelines.PipelineConstants.CheckoutTaskInputs.Token);
            if (string.IsNullOrEmpty(accessToken))
            {
                accessToken = executionContext.GetGitHubContext("token");
            }

            // register problem matcher
            string problemMatcher = @"    
{
    ""problemMatcher"": [
        {
            ""owner"": ""checkout-git"",
            ""pattern"": [
                {
                    ""regexp"": ""^fatal: (.*)$"",
                    ""message"": 1
                }
            ]
        }
    ]
}";
            string matcherFile = Path.Combine(tempDirectory, $"git_{Guid.NewGuid()}.json");
            File.WriteAllText(matcherFile, problemMatcher, new UTF8Encoding(false));
            executionContext.Output($"##[add-matcher]{matcherFile}");
            try
            {
                await new GitHubSourceProvider().GetSourceAsync(executionContext,
                                                                expectRepoPath,
                                                                repoFullName,
                                                                sourceBranch,
                                                                sourceVersion,
                                                                clean,
                                                                submoduleInput,
                                                                fetchDepth,
                                                                gitLfsSupport,
                                                                accessToken,
                                                                token);
            }
            finally
            {
                executionContext.Output("##[remove-matcher owner=checkout-git]");
            }
        }

19 View Source File : SettingForm.cs
License : MIT License
Project Creator : aabiryukov

private static bool TryParseInt(string text, out int value)
        {
            return int.TryParse(text, NumberStyles.Integer, CultureInfo.CurrentCulture, out value);
        }

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

private async Task<ResultModel> DoQuestConsume(PlayerEnreplacedy player, string consumeStr)
        {
            var result = new ResultModel
            {
                IsSuccess = false
            };
            if (!string.IsNullOrEmpty(consumeStr))
            {
                List<QuestConsume> questConsumes = new List<QuestConsume>();
                try
                {
                    questConsumes = JsonConvert.DeserializeObject<List<QuestConsume>>(consumeStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestConsume:{ex}");
                }

                foreach (var questConsume in questConsumes)
                {
                    var npcId = questConsume.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    int.TryParse(questConsume.Attrs.FirstOrDefault(x => x.Attr == "Exp")?.Val, out int exp);
                    long.TryParse(questConsume.Attrs.FirstOrDefault(x => x.Attr == "Money")?.Val, out long money);

                    var consumeEnum = (QuestConsumeEnum)Enum.Parse(typeof(QuestConsumeEnum), questConsume.Consume, true);


                    switch (consumeEnum)
                    {


                        case QuestConsumeEnum.物品:

                            //TODO 减少物品
                            return result;

                        case QuestConsumeEnum.经验:
                            player.Exp -= exp;
                            break;

                        case QuestConsumeEnum.金钱:
                            player.Money -= money;
                            break;


                    }

                }

                await _playerDomainService.Update(player);
            }

            result.IsSuccess = true;
            return await Task.FromResult(result);
        }

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

public override void Apply(TModel target)
        {
            this.Apply(
                target,
                (type, parent, current) =>
                {
                    object memberValue = null;
                    if (type.IsList())
                    {
                        var list = (IList)parent;
                        int index;
                        if (int.TryParse(current, out index) &&
                            list.Count > index)
                        {
                            memberValue = list[index];
                        }
                        else
                        {
                            // We can't insert beyond the length of the list.
                            throw new PatchOperationFailedException(PatchResources.IndexOutOfRange(this.Path));
                        }
                    }
                    else if (type.IsDictionary())
                    {
                        var fieldDictionary = ((IDictionary)parent);

                        if (!fieldDictionary.Contains(current))
                        {
                            throw new InvalidPatchFieldNameException(PatchResources.InvalidFieldName(current));
                        }
                        memberValue = fieldDictionary[current];
                    }
                    else
                    {
                        memberValue = type.GetMemberValue(current, parent);
                    }

                    var success = false;
                    if (memberValue != null)
                    {
                        if (memberValue is IList)
                        {
                            // TODO: Implement
                            throw new PatchOperationFailedException(PatchResources.TestNotImplementedForList());
                        }
                        else if (memberValue is IDictionary)
                        {
                            // TODO: Implement
                            throw new PatchOperationFailedException(PatchResources.TestNotImplementedForDictionary());
                        }
                        else if (memberValue.GetType().IsreplacedignableOrConvertibleFrom(this.Value))
                        {
                            // We convert the objects since we need the values unboxed.
                            var convertedMemberValue = ConvertUtility.ChangeType(memberValue, memberValue.GetType());
                            var convertedValue = ConvertUtility.ChangeType(this.Value, memberValue.GetType());

                            success = convertedMemberValue.Equals(convertedValue);
                        }
                        else
                        {
                            success = memberValue.Equals(this.Value);
                        }
                    }
                    else
                    {
                        success = object.Equals(memberValue, this.Value);
                    }

                    if (!success)
                    {
                        throw new TestPatchOperationFailedException(PatchResources.TestFailed(this.Path, memberValue, this.Value));
                    }
                });
        }

19 View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099

public static object FromObject(this Type targetType, object value, Encoding encoding = null)
    {
        if (targetType == typeof(object)) return value;
        if (encoding == null) encoding = Encoding.UTF8;
        var valueIsNull = value == null;
        var valueType = valueIsNull ? typeof(string) : value.GetType();
        if (valueType == targetType) return value;
        if (valueType == typeof(byte[])) //byte[] -> guid
        {
            if (targetType == typeof(Guid))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
            }
            if (targetType == typeof(Guid?))
            {
                var bytes = value as byte[];
                return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
            }
        }
        if (targetType == typeof(byte[])) //guid -> byte[]
        {
            if (valueIsNull) return null;
            if (valueType == typeof(Guid) || valueType == typeof(Guid?))
            {
                var bytes = new byte[16];
                var guidN = ((Guid)value).ToString("N");
                for (var a = 0; a < guidN.Length; a += 2)
                    bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
                return bytes;
            }
            return encoding.GetBytes(value.ToInvariantCultureToString());
        }
        else if (targetType.IsArray)
        {
            if (value is Array valueArr)
            {
                var targetElementType = targetType.GetElementType();
                var sourceArrLen = valueArr.Length;
                var target = Array.CreateInstance(targetElementType, sourceArrLen);
                for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
                return target;
            }
            //if (value is IList valueList)
            //{
            //    var targetElementType = targetType.GetElementType();
            //    var sourceArrLen = valueList.Count;
            //    var target = Array.CreateInstance(targetElementType, sourceArrLen);
            //    for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
            //    return target;
            //}
        }
        var func = _dicFromObject.GetOrAdd(targetType, tt =>
        {
            if (tt == typeof(object)) return vs => vs;
            if (tt == typeof(string)) return vs => vs;
            if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
            if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
            if (tt == typeof(bool)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                }
                return false;
            };
            if (tt == typeof(bool?)) return vs =>
            {
                if (vs == null) return false;
                switch (vs.ToLower())
                {
                    case "true":
                    case "1":
                        return true;
                    case "false":
                    case "0":
                        return false;
                }
                return null;
            };
            if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
            if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
            if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
            if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
            if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
            if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
            if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
            if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
            if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
            if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
            if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
            if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
            if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
            if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
            if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
            if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
            if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
            if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
            if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
            if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
            if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
            if (tt.NullableTypeOrThis().IsEnum)
            {
                var tttype = tt.NullableTypeOrThis();
                var ttdefval = tt.CreateInstanceGetDefaultValue();
                return vs =>
                {
                    if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
                    return Enum.Parse(tttype, vs, true);
                };
            }
            var localTargetType = targetType;
            var localValueType = valueType;
            return vs =>
            {
                if (vs == null) return null;
                throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
            };
        });
        var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
        return func(valueStr);
    }

19 View Source File : POParser.cs
License : MIT License
Project Creator : adams85

private bool TryReadPluralIndex(out int? result)
        {
            var lineLength = _line.Length;

            if (_columnIndex >= lineLength || _line[_columnIndex] != '[')
            {
                result = null;
                return true;
            }

            var startIndex = ++_columnIndex;
            char c;
            for (; _columnIndex < lineLength; _columnIndex++)
                if ((c = _line[_columnIndex]) == ']')
                {
                    var endIndex = _columnIndex++;
                    if (!int.TryParse(_line.Substring(startIndex, endIndex - startIndex), NumberStyles.Integer, CultureInfo.InvariantCulture, out int indexValue))
                    {
                        AddError(DiagnosticCodes.InvalidPluralIndex, new TextLocation(_lineIndex, startIndex - 1));
                        result = null;
                        return false;
                    }
                    result = indexValue;
                    return true;
                }
                else if (!char.IsDigit(c))
                {
                    var diagnosticCode = GetUnexpectedCharDiagnosticCode(DiagnosticCodes.InvalidPluralIndex);
                    AddError(diagnosticCode, new TextLocation(_lineIndex, diagnosticCode == DiagnosticCodes.InvalidPluralIndex ? startIndex - 1 : _columnIndex));
                    result = null;
                    return false;
                }

            AddError(DiagnosticCodes.ExpectedToken, new TextLocation(_lineIndex, lineLength), ']');
            result = null;
            return false;
        }

19 View Source File : PlyHandler.cs
License : MIT License
Project Creator : 3DBear

private static Color ParseColor(string[] xyzrgb, PlyHeader header)
        {
            int r = 255;
            int g = 255;
            int b = 255;
            int a = 255;
            if (header.RedIndex.HasValue)
                int.TryParse(xyzrgb[header.RedIndex.Value], NumberStyles.Integer, CultureInfo.InvariantCulture, out r);
            if (header.GreenIndex.HasValue)
                int.TryParse(xyzrgb[header.GreenIndex.Value], NumberStyles.Integer, CultureInfo.InvariantCulture, out g);
            if (header.BlueIndex.HasValue)
                int.TryParse(xyzrgb[header.BlueIndex.Value], NumberStyles.Integer, CultureInfo.InvariantCulture, out b);
            if (header.AlphaIndex.HasValue)
                int.TryParse(xyzrgb[header.AlphaIndex.Value], NumberStyles.Integer, CultureInfo.InvariantCulture, out a);
            return new Color(r / 255f, g / 255f, b / 255f, a / 255f);
        }

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

private static EffectArgument ParseEffectArgument(string filename, Effect effect, string operand)
        {
            var effectArgument = new EffectArgument();

            effectArgument.Type = GetEffectArgumentType(effect, operand);

            switch (effectArgument.Type)
            {
                case EffectArgumentType.Int:

                    if (!int.TryParse(operand, out effectArgument.IntVal))
                    {
                        if (effect.Quality != null && effect.Quality.StatType == StatType.Int && effect.Quality.StatIdx == (int)PropertyInt.ImbuedEffect && Enum.TryParse(operand, out ImbuedEffectType imbuedEffectType))
                            effectArgument.IntVal = (int)imbuedEffectType;
                        else if (Enum.TryParse(operand, out WieldRequirement wieldRequirement))
                            effectArgument.IntVal = (int)wieldRequirement;
                        else if (Enum.TryParse(operand, out Skill skill))
                            effectArgument.IntVal = (int)skill;
                        else
                            log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse IntVal {operand}");
                    }
                    break;

                case EffectArgumentType.Int64:

                    if (!long.TryParse(operand, out effectArgument.LongVal))
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse Int64Val {operand}");
                    }
                    break;

                case EffectArgumentType.Double:

                    if (!double.TryParse(operand, out effectArgument.DoubleVal))
                    {
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse DoubleVal {operand}");
                    }
                    break;

                case EffectArgumentType.Quality:

                    effectArgument.StatType = GetStatType(operand);

                    switch (effectArgument.StatType)
                    {
                        case StatType.Int:

                            if (Enum.TryParse(operand, out PropertyInt propInt))
                                effectArgument.StatIdx = (int)propInt;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt.{operand}");
                            break;

                        case StatType.Int64:

                            if (Enum.TryParse(operand, out PropertyInt64 propInt64))
                                effectArgument.StatIdx = (int)propInt64;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyInt64.{operand}");
                            break;

                        case StatType.Float:

                            if (Enum.TryParse(operand, out PropertyFloat propFloat))
                                effectArgument.StatIdx = (int)propFloat;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyFloat.{operand}");
                            break;

                        case StatType.Bool:

                            if (Enum.TryParse(operand, out PropertyBool propBool))
                                effectArgument.StatIdx = (int)propBool;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
                            break;

                        case StatType.DataID:

                            if (Enum.TryParse(operand, out PropertyDataId propDID))
                                effectArgument.StatIdx = (int)propDID;
                            else
                                log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse PropertyBool.{operand}");
                            break;

                        default:
                            log.Error($"MutationCache.BuildMutation({filename}) - unknown PropertyType.{operand}");
                            break;
                    }
                    break;

                case EffectArgumentType.Random:

                    var match = Regex.Match(operand, @"Random\(([\d.-]+), ([\d.-]+)\)");

                    if (!match.Success || !float.TryParse(match.Groups[1].Value, out effectArgument.MinVal) || !float.TryParse(match.Groups[2].Value, out effectArgument.MaxVal))
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");

                    break;

                case EffectArgumentType.Variable:

                    match = Regex.Match(operand, @"\[(\d+)\]");

                    if (!match.Success || !int.TryParse(match.Groups[1].Value, out effectArgument.IntVal))
                        log.Error($"MutationCache.BuildMutation({filename}) - couldn't parse {operand}");

                    break;

                default:
                    log.Error($"MutationCache.BuildMutation({filename}) - unknown EffectArgumentType from {operand}");
                    break;
            }
            return effectArgument;
        }

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

public static string Login(string addr, string login, string preplacedword)
        {
            var StrIp = addr.Split(':');
            var port = Transfer.SessionClient.DefaultPort;
            if (StrIp.Length == 2)
            {
                if (!int.TryParse(StrIp[1], out port))
                {
                    return "Invalid IP adress or port";
                }
            }

            if (!IPAddress.TryParse(StrIp[0],out IPAddress ipAdres))
            {
                return "Invalid IP adress";
            }

            var endPoint = new IPEndPoint(ipAdres, port);

            return ChatProv.Login(endPoint, login, preplacedword);
        }

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

public async Task Handle(QuestTriggerEvent message, CancellationToken cancellationToken)
        {
            var player = message.Player;
            var questTriggerType = message.QuestTriggerType;

            //已经领取的所有任务
            var myQuests = (await _playerQuestDomainService.GetPlayerQuests(player.Id));
            //正在进行的任务
            var myQuestsNotComplete = myQuests.Where(x => x.Status== QuestStateEnum.已领取进行中);
            //所有未完成任务
            var quests = (await _questDomainService.GetAll()).Where(x => myQuestsNotComplete.Select(y => y.QuestId).Contains(x.Id));


            foreach(var quest in quests)
            {
                List<QuestTarget> questTargets = new List<QuestTarget>();
                try
                {
                    questTargets = JsonConvert.DeserializeObject<List<QuestTarget>>(quest.Target);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestTarget:{ex}");
                }

                if (questTargets == null || questTargets.Count == 0)
                {
                    continue;
                }

                if (!questTargets.Exists(x => x.Target == questTriggerType.ToString()))
                {
                    continue;
                }

                foreach (var questTarget in questTargets)
                {
                    var npcId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    var questId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val;
                    int.TryParse(questTarget.Attrs.FirstOrDefault(x => x.Attr == "RoomId")?.Val, out int roomId);

                    var targetEnum = (QuestTargetEnum)Enum.Parse(typeof(QuestTargetEnum), questTarget.Target, true);
                    switch (targetEnum)
                    {

                        case QuestTargetEnum.与某个Npc对话:
    
                            break;

                        case QuestTargetEnum.所在房间:
                            if (player.RoomId != roomId)
                            {
                                continue;
                            }


                            break;

                    }
                }


            }


        }

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

private Boolean MatchInteger(
            Scalar scalar,
            out NumberToken value)
        {
            // YAML 1.2 "core" schema https://yaml.org/spec/1.2/spec.html#id2804923
            var str = scalar.Value;
            if (!String.IsNullOrEmpty(str))
            {
                // Check for [0-9]+
                var firstChar = str[0];
                if (firstChar >= '0' && firstChar <= '9' &&
                    str.Skip(1).All(x => x >= '0' && x <= '9'))
                {
                    // Try parse
                    if (Double.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out var doubleValue))
                    {
                        value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, doubleValue);
                        return true;
                    }

                    // Otherwise exceeds range
                    ThrowInvalidValue(scalar, c_integerTag); // throws
                }
                // Check for (-|+)[0-9]+
                else if ((firstChar == '-' || firstChar == '+') &&
                    str.Length > 1 &&
                    str.Skip(1).All(x => x >= '0' && x <= '9'))
                {
                    // Try parse
                    if (Double.TryParse(str, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var doubleValue))
                    {
                        value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, doubleValue);
                        return true;
                    }

                    // Otherwise exceeds range
                    ThrowInvalidValue(scalar, c_integerTag); // throws
                }
                // Check for 0x[0-9a-fA-F]+
                else if (firstChar == '0' &&
                    str.Length > 2 &&
                    str[1] == 'x' &&
                    str.Skip(2).All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')))
                {
                    // Try parse
                    if (Int32.TryParse(str.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var integerValue))
                    {
                        value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, integerValue);
                        return true;
                    }

                    // Otherwise exceeds range
                    ThrowInvalidValue(scalar, c_integerTag); // throws
                }
                // Check for 0o[0-9]+
                else if (firstChar == '0' &&
                    str.Length > 2 &&
                    str[1] == 'o' &&
                    str.Skip(2).All(x => x >= '0' && x <= '7'))
                {
                    // Try parse
                    var integerValue = default(Int32);
                    try
                    {
                        integerValue = Convert.ToInt32(str.Substring(2), 8);
                    }
                    // Otherwise exceeds range
                    catch (Exception)
                    {
                        ThrowInvalidValue(scalar, c_integerTag); // throws
                    }

                    value = new NumberToken(m_fileId, scalar.Start.Line, scalar.Start.Column, integerValue);
                    return true;
                }
            }

            value = default;
            return false;
        }

19 View Source File : SegmentedControlRenderer.cs
License : MIT License
Project Creator : 1iveowl

private void SetSelectedSegment()
        {
            if (_segmentedUserControl.SegmentedControlGrid.Children
                .Where(x =>
                {
                    var btn = (RadioButton)x;

                    int.TryParse(btn.Tag.ToString(), out var i);
                    return i == Element.SelectedSegment;
                })
                .FirstOrDefault() is RadioButton checkedButton)
            {
                checkedButton.IsChecked = true;
            }

        }

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

public override void Apply(TModel target)
        {
            this.Apply(
                target,
                (type, parent, current) =>
                {
                    if (type.IsList())
                    {
                        var list = (IList)parent;
                        int index;
                        if (int.TryParse(current, out index) &&
                            list.Count > index)
                        {
                            list.RemoveAt(index);
                        }
                        else
                        {
                            // We can't remove outside the rangeof the list.
                            throw new PatchOperationFailedException(PatchResources.IndexOutOfRange(this.Path));
                        }
                    }
                    else if (type.IsDictionary())
                    {
                        ((IDictionary)parent).Remove(current);
                    }
                    else
                    {
                        type.SetMemberValue(current, parent, this.Value);
                    }
                });
        }

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

private async Task<ResultModel> CheckTakeCondition(PlayerEnreplacedy player, string takeConditionStr)
        {
            var result = new ResultModel { IsSuccess = false };

            if (!string.IsNullOrEmpty(takeConditionStr))
            {
                List<QuestTakeCondition> takeConditions = new List<QuestTakeCondition>();
                try
                {
                    takeConditions = JsonConvert.DeserializeObject<List<QuestTakeCondition>>(takeConditionStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert CaseIf:{ex}");
                }

                foreach (var takeCondition in takeConditions)
                {
                    var npcId = takeCondition.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    var questId = takeCondition.Attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val;
                    int.TryParse(takeCondition.Attrs.FirstOrDefault(x => x.Attr == "RoomId")?.Val, out int roomId);

                    var targetEnum = (QuestTakeConditionEnum)Enum.Parse(typeof(QuestTakeConditionEnum), takeCondition.Condition, true);


                    switch (targetEnum)
                    {


                        case QuestTakeConditionEnum.与某个Npc对话:
                            if (await _redisDb.StringGet<int>(string.Format(RedisKey.ChatWithNpc, player.Id, npcId)) != 1)
                            {
                                result.ErrorMessage = $"";
                                return result;
                            }
                            break;

                        case QuestTakeConditionEnum.完成前置任务:

                            if (await _redisDb.StringGet<int>(string.Format(RedisKey.CompleteQuest, player.Id, questId)) != 1)
                            {
                                result.ErrorMessage = $"";
                                return result;
                            }

                            break;


                    }
                }
            }




            result.IsSuccess = true;
            return result;
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void OnGoToLineButtonClick(object sender, RoutedEventArgs e) {
			// Validate
			int lineIndex;
			if ((!int.TryParse(lineNumberTextBox.Text, out lineIndex)) || (lineIndex < 1) || (lineIndex > editor.ActiveView.CurrentSnapshot.Lines.Count)) {
				MessageBox.Show(String.Format("Please enter a valid line number (1-{0}).", editor.ActiveView.CurrentSnapshot.Lines.Count));
				return;
			}

			// Set caret position (make zero-based)
			editor.ActiveView.Selection.CaretPosition = new TextPosition(lineIndex - 1, 0);
			editor.ActiveView.Scroller.ScrollLineToVisibleMiddle();

			// Focus the editor
			editor.Focus();
		}

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

private static ExpressionSyntax GenColumnMeta(ColumnContext columnContext)
        {
            ColumnModel columnModel = columnContext.ColumnModel;

            ExpressionSyntax? result = null;

            ExpressionSyntax EnsureResult(string methodName, string? g1 = null)
            {
                return string.IsNullOrEmpty(g1)
                    ? result?.MemberAccess(methodName) ??
                      SyntaxFactory.IdentifierName(nameof(ColumnMeta)).MemberAccess(methodName)
                    : result?.MemberAccessGeneric(methodName, g1) ??
                      SyntaxFactory.IdentifierName(nameof(ColumnMeta)).MemberAccessGeneric(methodName, g1);
            }

            if (columnModel.Pk.HasValue)
            {
                result = EnsureResult(nameof(ColumnMeta.PrimaryKey)).Invoke();
            }

            if (columnModel.Idenreplacedy)
            {
                result = EnsureResult(nameof(ColumnMeta.Idenreplacedy)).Invoke();
            }

            if (columnModel.DefaultValue != null)
            {
                result = EnsureResult(nameof(ColumnMeta.DefaultValue)).Invoke(GetDefaultArgument(columnModel.DefaultValue.Value));
            }

            if (columnModel.Fk != null)
            {
                foreach (var columnRef in columnModel.Fk)
                {
                    if(!columnContext.Tables.TryGetValue(columnRef.Table, out var tableModel))
                    {
                        throw new SqExpressCodeGenException($"Could not find table model for: \"{columnRef.Table}\"");
                    }

                    var fkColumnModel = tableModel.Columns.FirstOrDefault(c => c.DbName.Equals(columnRef));
                    if (fkColumnModel == null)
                    {
                        throw new SqExpressCodeGenException($"Could not find column model for: \"{columnRef}\"");
                    }

                    var lambda = SyntaxFactory.SimpleLambdaExpression(FuncParameter("t"), MemberAccess("t", fkColumnModel.Name));

                    result = EnsureResult(nameof(ColumnMeta.ForeignKey), tableModel.Name).Invoke(lambda);
                }
            }

            return result ?? NullLiteral();

            static ExpressionSyntax GetDefaultArgument(DefaultValue defaultValue)
            {
                ExpressionSyntax arg;
                switch (defaultValue.Type)
                {
                    case DefaultValueType.Raw:
                        var rawValue = defaultValue.RawValue ??
                                       throw new SqExpressCodeGenException("String raw value cannot be null");
                        arg = SyntaxFactory.IdentifierName(nameof(SqQueryBuilder))
                            .MemberAccess(nameof(SqQueryBuilder.UnsafeValue))
                            .Invoke(LiteralExpr(rawValue));
                        break;
                    case DefaultValueType.Null:
                        arg = SyntaxFactory.IdentifierName(nameof(SqQueryBuilder))
                            .MemberAccess(nameof(SqQueryBuilder.Null));
                        break;
                    case DefaultValueType.Integer:
                        var valueRawValue = defaultValue.RawValue ??
                                            throw new SqExpressCodeGenException("Integer raw value cannot be null");
                        if (!int.TryParse(valueRawValue, out var intLiteral))
                        {
                            throw new SqExpressCodeGenException("Integer literal has invalid format: " + valueRawValue);
                        }

                        arg = LiteralExpr(intLiteral);
                        break;
                    case DefaultValueType.String:
                        var valueStringValue = defaultValue.RawValue ??
                                               throw new SqExpressCodeGenException("Integer raw value cannot be null");
                        arg = LiteralExpr(valueStringValue);
                        break;
                    case DefaultValueType.GetUtcDate:
                        arg = SyntaxFactory.IdentifierName(nameof(SqQueryBuilder))
                            .MemberAccess(nameof(SqQueryBuilder.GetUtcDate))
                            .Invoke();
                        break;
                    default:
                        throw new SqExpressCodeGenException("Unknown default value type: " + defaultValue.Type);
                }

                return arg;
            }
        }

19 View Source File : POComment.cs
License : MIT License
Project Creator : adams85

public static bool TryParse(string value, out POSourceReference result)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            var index = value.LastIndexOf(':');
            if (index >= 0 && int.TryParse(value.Substring(index + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out int line))
                value = value.Remove(index);
            else
                line = default(int);

            var length = value.Length;
            if (length > 0 && value[0] == '"')
                if (length > 1 && value[length - 1] == '"')
                    value = value.Substring(1, length - 2);
                else
                {
                    result = default(POSourceReference);
                    return false;
                }

            result = new POSourceReference(value, line);
            return true;
        }

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

private async Task<WareEffectAttr> Computed(int playerId)
        {
            var wareEffectAttr = new WareEffectAttr();
            var playerWares = await _playerWareDomainService.GetAll(playerId);

            var ids = playerWares.Where(x => x.Status == WareStatusEnum.装备).Select(x => x.WareId).ToList();

            var wareQuery = await _wareDomainService.GetAll();
            var wares = wareQuery.Where(x => ids.Contains(x.Id));
            foreach (var item in wares)
            {
                var effects = JsonConvert.DeserializeObject<List<WareEffect>>(item.Effect);
                foreach (var effect in effects)
                {
                    foreach(var attr in effect.Attrs)
                    {
                        int.TryParse(attr.Val,out int val);

                        switch (attr.Attr)
                        {
                            case "Atk":
                                wareEffectAttr.Atk += val;
                                break;

                            case "Def":
                                wareEffectAttr.Def += val;
                                break;
                        }
                    }
                }
            }

            return wareEffectAttr;
        }

19 View Source File : ProCamsLensDataTable.cs
License : Apache License 2.0
Project Creator : A7ocin

public void LoadLensData()
	{
		_filmFormats = new List<FilmFormatData>();
		
		// Load in the data from Resources/CinemaSuite_LensData.txt
		Textreplacedet textreplacedet = (Textreplacedet)(Resources.Load("CinemaSuite_LensData", typeof(Textreplacedet)));
		if(textreplacedet == null)
		{
			Debug.LogError("File 'CinemaSuite_LensData.txt' is not found in Resources folder. Unable to load lens data.");
			return;
		}
		
		FilmFormatData currentFormat = null;
		
		string[] lines = textreplacedet.text.Split("\n"[0]);
		int numLines = lines.Length;
		for(int i = 0; i < numLines; ++i)
		{
			//Debug.Log("Line: " + i + "= " + lines[i]);
			
			string line = lines[i].Trim();
			if(line.StartsWith("#"))
			{
				continue;	
			}
			
			int length = line.Length;
			
			if(currentFormat == null)
			{
				// Look for "Name="
				if(line.StartsWith("Name="))
				{
					// New section

					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						string name = line.Substring(index).Trim();
						if(name.Length != 0)
						{
							// Create new film format with valid name
							currentFormat = new FilmFormatData();
							currentFormat._formatName = name;
						}
					}
				}
				else if(length != 0)
				{
					Debug.LogError("Invalid data at line: " + i);
				}
			}
			else
			{
				// Look for film format section entries
				
				if(length == 0)
				{
					// End of section
					_filmFormats.Add(currentFormat);
					//Debug.Log ("Added film format " + currentFormat._formatName);
					currentFormat = null;
				}
				else if(line.StartsWith("Aspect="))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						string strAspect = line.Substring(index).Trim();
						int colon = strAspect.IndexOf(":");
						if(colon > 0 && colon < length)
						{
							string first = strAspect.Substring(0, colon).Trim();
							string second = strAspect.Substring(colon + 1).Trim();
							float w = 0;
							float h = 0;
							
							if(!float.TryParse(first, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out w) || w <= 0)
							{
								Debug.LogError("Invalid number: " + first + " at line " + (i + 1));
								return;
							}
							if(!float.TryParse(second, System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out h) || h <= 0)
							{
								Debug.LogError("Invalid number: " + second + " at line " + (i + 1));
								return;
							}
							currentFormat._aspect = w / h;
							//Debug.Log ("Aspect: " + currentFormat._aspect);
						}
					}
				}
				else if(line.StartsWith("ScreenSize"))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						// ScreenSize=DI,1024
						string[] strSizes = line.Substring(index).Split(","[0]);
						if(strSizes == null || strSizes.Length != 2)
						{
							Debug.LogError("Invalid screen size entry at line " + (i + 1));
							return;
						}
						
						string sizeName = strSizes[0].Trim();
						int sizeValue = 0;
						if(!int.TryParse(strSizes[1].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out sizeValue) || sizeValue <= 0)
						{
							Debug.LogError("Invalid screen size at line " + (i + 1));
							return;
						}
						currentFormat._screenSizes.Add(new ScreenSize(sizeName, sizeValue));
						//Debug.Log ("Screensize: " + sizeName + ", " + sizeValue);
					}
				}
				else if(line.StartsWith("FocalLength"))
				{
					int index = line.IndexOf("=") + 1;
					if(index < length)
					{
						// FocalLength=Cooke S4/i - T2,12mm,4.980,00.000,00.000
						string[] strData = line.Substring(index).Split(","[0]);
						if(strData == null || strData.Length != 5)
						{
							Debug.LogError("Invalid data for focal length at line " + (i + 1));
							return;
						}
						
						string lensKit = strData[0].Trim();
						if(lensKit.Length == 0)
						{
							Debug.LogError("Invalid lens kit name at line " + (i + 1));
							return;
						}
						
						int focal = 0;
						if(!int.TryParse(strData[1].TrimEnd('m'), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out focal) || focal <= 0)
						{
							Debug.LogError("Invalid focal length at line " + (i + 1));
							return;
						}
						
						float nodal = 0;
						if(!float.TryParse(strData[2].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out nodal) || nodal < 0)
						{
							Debug.LogError("Invalid nodal offset at line " + (i + 1));
							return;
						}
						
						float realFOV = 0;
						if(!float.TryParse(strData[3].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out realFOV) || realFOV <= 0)
						{
							Debug.LogError("Invalid real FOV at line " + (i + 1));
							return;
						}
						
						float unityFOV = 0;
						if(!float.TryParse(strData[4].Trim(), System.Globalization.NumberStyles.Number, System.Globalization.CultureInfo.InvariantCulture, out unityFOV) || unityFOV <= 0)
						{
							Debug.LogError("Invalid Unity FOV at line " + (i + 1));
							return;
						}
						
						currentFormat.AddFocalLengthData(lensKit, focal, nodal, realFOV, unityFOV);
						//Debug.Log ("Focal Data: " + lensKit + ", " + focal + ", " + nodal + ", " + realFOV + ", " + unityFOV);
					}
				}
			}
		}
	}

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

private void SetStringParameter(string name, string value, bool coerceParameterType)
        {
            Validate.IsNotNull(name, nameof(name));
            Validate.IsNotNull(value, nameof(value));
            VerifyNotDisposed();

            if (coerceParameterType)
            {
                // Some encoders expect the method that is called to match the parameter type.
                // Attempting to set a Boolean or Integer parameter as a string will cause an invalid parameter error.
                if (this.encoderParameterTypes.Value.TryGetValue(name, out var type))
                {
                    switch (type)
                    {
                        case HeifEncoderParameterType.Boolean:
                            if (TryConvertStringToBoolean(value, out bool boolValue))
                            {
                                SetBooleanParameter(name, boolValue);
                            }
                            else
                            {
                                throw new HeifException(string.Format(CultureInfo.CurrentCulture,
                                                                      Resources.CoerceStringValueToBooleanFailedFormat,
                                                                      nameof(value)));
                            }
                            return;
                        case HeifEncoderParameterType.Integer:
                            if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int intValue))
                            {
                                SetIntegerParameter(name, intValue);
                            }
                            else
                            {
                                throw new HeifException(string.Format(CultureInfo.CurrentCulture,
                                                                      Resources.CoerceStringValueToIntegerFailedFormat,
                                                                      nameof(value)));
                            }
                            return;
                        case HeifEncoderParameterType.String:
                            // The parameter is the correct type.
                            break;
                        default:
                            throw new HeifException($"Unknown { nameof(HeifEncoderParameterType) }: { type }.");
                    }
                }
            }

            var error = LibHeifNative.heif_encoder_set_parameter_string(this.encoder, name, value);
            error.ThrowIfError();
        }

19 View Source File : config.cs
License : MIT License
Project Creator : aaaddress1

private void button1_Click(object sender, EventArgs e)
        {
            var gwPathInput = this.gwPathTB.Text;
            if (!new DirectoryInfo(gwPathInput).Exists)
            {
                MessageBox.Show(string.Format("MinGW path \"{0}\" not found!", gwPathInput));
                return;
            }
            if (!new FileInfo(Path.Combine(gwPathInput, "gcc.exe")).Exists)
            {
                MessageBox.Show(string.Format("MinGW compiler \"{0}\" not found!", Path.Combine(gwPathInput, "gcc.exe")));
                return;
            }
            if (!new FileInfo(Path.Combine(gwPathInput, "ld.exe")).Exists)
            {
                MessageBox.Show(string.Format("MinGW linker \"{0}\" not found!", Path.Combine(gwPathInput, "ld.exe")));
                return;
            }

            int p = 0;
            if (!int.TryParse(this.obfusPcntTB.Text, out p))
            {
                MessageBox.Show(string.Format("Obfuscate % \"{0}\" not found!", this.obfusPcntTB.Text));
                return;
            }
            Properties.Settings.Default.gwPath = this.gwPathTB.Text;
            Properties.Settings.Default.linkArg = this.lkArgTB.Text;
            Properties.Settings.Default.clArg = this.clArgTB.Text;
            Properties.Settings.Default.obfusPcnt = p;
            Properties.Settings.Default.cnfseCode = this.cnfOrgJunk.Checked;
            Properties.Settings.Default.insrtJunk = this.insrtJunkCB.Checked;
            Properties.Settings.Default.clnAftCompile = this.clnComplieCB.Checked;
            Properties.Settings.Default.Save();
            MessageBox.Show("save config successfully!");
            this.Close();
        }

19 View Source File : Modifier_Identification.cs
License : MIT License
Project Creator : 5minlab

internal static Modifier_Identification Current(BuildTargetGroup targetGroup) {
            int versionCode = 0;
            if(targetGroup == BuildTargetGroup.Android) {
                versionCode = PlayerSettings.Android.bundleVersionCode;

            } else if(targetGroup == BuildTargetGroup.iOS) {
                if(!int.TryParse(PlayerSettings.iOS.buildNumber, out versionCode)) {
                    versionCode = 0;
                }
            }

            return new Modifier_Identification(targetGroup)
            {
                packageName = PlayerSettings.GetApplicationIdentifier(targetGroup),
                versionName = PlayerSettings.bundleVersion,
                versionCode = versionCode,
            };
        }

19 View Source File : DellFanManagementGuiForm.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private void CheckConsistencyModeOptionsConsistency()
        {
            bool result = false;

            if (consistencyModeLowerTemperatureThresholdTextBox.Text != _core.LowerTemperatureThreshold.ToString() ||
                consistencyModeUpperTemperatureThresholdTextBox.Text != _core.UpperTemperatureThreshold.ToString() ||
                consistencyModeRpmThresholdTextBox.Text != _core.RpmThreshold.ToString())
            {
                // Configuration doesn't match.  Check for flip-flop.
                bool success = int.TryParse(consistencyModeLowerTemperatureThresholdTextBox.Text, out int lowerTemperatureThreshold);
                if (success)
                {
                    success = int.TryParse(consistencyModeUpperTemperatureThresholdTextBox.Text, out int upperTemperatureThreshold);
                    if (success)
                    {
                        if (upperTemperatureThreshold >= lowerTemperatureThreshold)
                        {
                            // Looks good, we can enable the button.
                            result = true;
                        }
                    }
                }
            }

            consistencyModeApplyChangesButton.Enabled = result;
        }

19 View Source File : DellFanManagementGuiForm.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley

private void WriteConsistencyModeConfiguration()
        {
            bool success = int.TryParse(consistencyModeLowerTemperatureThresholdTextBox.Text, out int lowerTemperatureThreshold);
            if (success)
            {
                success = int.TryParse(consistencyModeUpperTemperatureThresholdTextBox.Text, out int upperTemperatureThreshold);
                if (success)
                {
                    success = int.TryParse(consistencyModeRpmThresholdTextBox.Text, out int rpmThreshold);
                    if (success)
                    {
                        _core.WriteConsistencyModeConfiguration(lowerTemperatureThreshold, upperTemperatureThreshold, rpmThreshold);

                        _configurationStore.SetOption(ConfigurationOption.ConsistencyModeLowerTemperatureThreshold, lowerTemperatureThreshold);
                        _configurationStore.SetOption(ConfigurationOption.ConsistencyModeUpperTemperatureThreshold, upperTemperatureThreshold);
                        _configurationStore.SetOption(ConfigurationOption.ConsistencyModeRpmThreshold, rpmThreshold);

                        CheckConsistencyModeOptionsConsistency();
                    }
                }
            }
        }

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

private async Task DoCommand(PlayerEnreplacedy player, NpcEnreplacedy npc, int scriptId, string command, List<CaseAttribute> attrs, string input)
        {
            var replacedle = attrs.FirstOrDefault(x => x.Attr == "replacedle")?.Val;
            var message = attrs.FirstOrDefault(x => x.Attr == "Message")?.Val;
            var tips = attrs.FirstOrDefault(x => x.Attr == "Tips")?.Val;
            int.TryParse(attrs.FirstOrDefault(x => x.Attr == "CommandId")?.Val, out int commandId);
            int.TryParse(attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val, out int questId);



            var key = $"commandIds_{player.Id}_{npc.Id}_{scriptId}";
            var commandIds = await _redisDb.StringGet<List<int>>(key) ?? new List<int>();
            if (commandId > 0 && !commandIds.Contains(commandId))
            {
                commandIds.Add(commandId);
            }

            await _redisDb.StringSet(key, commandIds);

            var commandEnum = (CommandTypeEnum)Enum.Parse(typeof(CommandTypeEnum), command, true);

            //await _bus.RaiseEvent(new DomainNotification($"command= {command}"));
            switch (commandEnum)
            {
                case CommandTypeEnum.播放对话:
                    await _mudProvider.ShowMessage(player.Id, $"{npc.Name}:{message}", MessageTypeEnum.聊天);
                    break;

                case CommandTypeEnum.对话选项:
                    await _mudProvider.ShowMessage(player.Id, $" → <a href='javascript:;' clreplaced='chat' npcId='{npc.Id}' scriptId='{scriptId}' commandId='{commandId}'>{replacedle}</a><br />", MessageTypeEnum.指令);
                    break;

                case CommandTypeEnum.输入选项:
                    await _mudProvider.ShowMessage(player.Id, $" → <a href = 'javascript:;'>{tips}</a>  <input type = 'text' name='input' style='width:120px;margin-left:10px;' />  <button type = 'button' clreplaced='input' style='padding:1px 3px;' npcId='{npc.Id}'  scriptId='{scriptId}'  commandId='{commandId}'> 确定 </button><br />", MessageTypeEnum.指令);
                    break;

                case CommandTypeEnum.跳转到分支:
                    await DoScript(player, npc, scriptId, commandId);
                    break;


                case CommandTypeEnum.领取任务:
                    await TakeQuest(player, questId);
                    break;

                case CommandTypeEnum.完成任务:
                    await ComplateQuest(player, questId);
                    break;
            }
        }

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

private static void CheckForWorldDatabaseUpdate()
        {
            log.Info($"Automatic World Database Update started...");
            try
            {
                var worldDb = new Database.WorldDatabase();
                var currentVersion = worldDb.GetVersion();
                log.Info($"Current World Database version: Base - {currentVersion.BaseVersion} | Patch - {currentVersion.PatchVersion}");

                var url = "https://api.github.com/repos/ACEmulator/ACE-World-16PY-Patches/releases";
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.UserAgent = "ACE.Server";

                var response = request.GetResponse();
                var reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);
                var html = reader.ReadToEnd();
                reader.Close();
                response.Close();

                dynamic json = JsonConvert.DeserializeObject(html);
                string tag = json[0].tag_name;
                string dbURL = json[0].replacedets[0].browser_download_url;
                string dbFileName = json[0].replacedets[0].name;

                if (currentVersion.PatchVersion != tag)
                {
                    var patchVersionSplit = currentVersion.PatchVersion.Split(".");
                    var tagSplit = tag.Split(".");

                    int.TryParse(patchVersionSplit[0], out var patchMajor);
                    int.TryParse(patchVersionSplit[1], out var patchMinor);
                    int.TryParse(patchVersionSplit[2], out var patchBuild);

                    int.TryParse(tagSplit[0], out var tagMajor);
                    int.TryParse(tagSplit[1], out var tagMinor);
                    int.TryParse(tagSplit[2], out var tagBuild);

                    if (tagMajor > patchMajor || tagMinor > patchMinor || (tagBuild > patchBuild && patchBuild != 0))
                    {
                        log.Info($"Latest patch version is {tag} -- Update Required!");
                        UpdateToLatestWorldDatabase(dbURL, dbFileName);
                        var newVersion = worldDb.GetVersion();
                        log.Info($"Updated World Database version: Base - {newVersion.BaseVersion} | Patch - {newVersion.PatchVersion}");
                    }
                    else
                    {
                        log.Info($"Latest patch version is {tag} -- No Update Required!");
                    }
                }
                else
                {
                    log.Info($"Latest patch version is {tag} -- No Update Required!");
                }
            }
            catch (Exception ex)
            {
                log.Info($"Unable to continue with Automatic World Database Update due to the following error: {ex}");
            }
            log.Info($"Automatic World Database Update complete.");
        }

19 View Source File : MainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

private async void CreateClientsButton_Click(object sender, RoutedEventArgs e)
        {
            DeviceExpander.IsExpanded = true;

            string BaseName = NewClientName.Text;
            int CountOfMachines = (Int32.TryParse(NumberOfClients.Text, out int unUsed)) ? Int32.Parse(NumberOfClients.Text) : 1;
            int BeginningWith = (!StartingNumber.Text.Length.Equals(0)) ? Int32.Parse(StartingNumber.Text) : 0;
            List<String> DeviceList = new List<string>();
            int current = 0;
            object lockCurrent = new object();
            var progress = new Progress<int>(_ => IdCounter++) as IProgress<int>;

            for (int i = BeginningWith; i <= CountOfMachines; i++)
            {
                string ThisClient = BaseName + i;
                DeviceList.Add(ThisClient);
            }

            var myTask = Task.Run(() =>
            {
                Parallel.For(0, DeviceList.Count,
                    new ParallelOptions { MaxDegreeOfParallelism = MaxThreads },
                    (ii, loopState) =>
                    {
                        int thisCurrent = 0;
                        lock (lockCurrent)
                        {
                            thisCurrent = current;
                            current++;
                        }
                        string device = DeviceList[thisCurrent];
                        Device ThisDevice = new Device() { Name = device, Status = "Starting...", ImageSource = "Images\\step01.png", ProcessProgress = 10 };
                        Devices.Add(ThisDevice);
                        int thisIndex = Devices.IndexOf(ThisDevice);
                        RegisterClient(thisIndex);

                        progress.Report(0);
                    });
            });

            await myTask;
        }

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

private DTWebApi.Issue ConvertToIssue(IssueMatch match)
        {
            // Validate the message
            if (string.IsNullOrWhiteSpace(match.Message))
            {
                _executionContext.Debug("Skipping logging an issue for the matched line because the message is empty.");
                return null;
            }

            // Validate the severity
            DTWebApi.IssueType issueType;
            if (string.IsNullOrEmpty(match.Severity) || string.Equals(match.Severity, "error", StringComparison.OrdinalIgnoreCase))
            {
                issueType = DTWebApi.IssueType.Error;
            }
            else if (string.Equals(match.Severity, "warning", StringComparison.OrdinalIgnoreCase))
            {
                issueType = DTWebApi.IssueType.Warning;
            }
            else if (string.Equals(match.Severity, "notice", StringComparison.OrdinalIgnoreCase))
            {
                issueType = DTWebApi.IssueType.Notice;
            }
            else
            {
                _executionContext.Debug($"Skipped logging an issue for the matched line because the severity '{match.Severity}' is not supported.");
                return null;
            }

            var issue = new DTWebApi.Issue
            {
                Message = match.Message,
                Type = issueType,
            };

            // Line
            if (!string.IsNullOrEmpty(match.Line))
            {
                if (int.TryParse(match.Line, NumberStyles.None, CultureInfo.InvariantCulture, out var line))
                {
                    issue.Data["line"] = line.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    _executionContext.Debug($"Unable to parse line number '{match.Line}'");
                }
            }

            // Column
            if (!string.IsNullOrEmpty(match.Column))
            {
                if (int.TryParse(match.Column, NumberStyles.None, CultureInfo.InvariantCulture, out var column))
                {
                    issue.Data["col"] = column.ToString(CultureInfo.InvariantCulture);
                }
                else
                {
                    _executionContext.Debug($"Unable to parse column number '{match.Column}'");
                }
            }

            // Code
            if (!string.IsNullOrWhiteSpace(match.Code))
            {
                issue.Data["code"] = match.Code.Trim();
            }

            // File
            try
            {
                if (!string.IsNullOrWhiteSpace(match.File))
                {
                    var file = match.File;
                    var translate = _container != null;

                    // Root using fromPath
                    if (!string.IsNullOrWhiteSpace(match.FromPath) && !Path.IsPathFullyQualified(file))
                    {
                        var fromDirectory = Path.GetDirectoryName(match.FromPath);
                        if (!string.IsNullOrWhiteSpace(fromDirectory))
                        {
                            file = Path.Combine(fromDirectory, file);
                        }
                    }

                    // Root using workspace
                    if (!Path.IsPathFullyQualified(file))
                    {
                        var workspace = _executionContext.GetGitHubContext("workspace");
                        ArgUtil.NotNullOrEmpty(workspace, "workspace");

                        file = Path.Combine(workspace, file);
                        translate = false;
                    }

                    // Remove relative pathing and normalize slashes
                    file = Path.GetFullPath(file);

                    // Translate to host
                    if (translate)
                    {
                        file = _container.TranslateToHostPath(file);
                        file = Path.GetFullPath(file);
                    }

                    // Check whether the file exists
                    if (File.Exists(file))
                    {
                        // Check whether the file is under the workflow repository
                        var repositoryPath = GetRepositoryPath(file);
                        if (!string.IsNullOrEmpty(repositoryPath))
                        {
                            // Get the relative file path
                            var relativePath = file.Substring(repositoryPath.Length).TrimStart(Path.DirectorySeparatorChar);

                            // Prefer `/` on all platforms
                            issue.Data["file"] = relativePath.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
                        }
                        else
                        {
                            _executionContext.Debug($"Dropping file value '{file}'. Path is not under the workflow repo.");
                        }
                    }
                    else
                    {
                        _executionContext.Debug($"Dropping file value '{file}'. Path does not exist");
                    }
                }
            }
            catch (Exception ex)
            {
                _executionContext.Debug($"Dropping file value '{match.File}' and fromPath value '{match.FromPath}'. Exception during validation: {ex.ToString()}");
            }

            return issue;
        }

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

private async Task<ResultModel> TakeQuestReward(PlayerEnreplacedy player, string rewardStr)
        {
            var result = new ResultModel
            {
                IsSuccess = false
            };
            if (!string.IsNullOrEmpty(rewardStr))
            {
                List<QuestReward> questRewards = new List<QuestReward>();
                try
                {
                    questRewards = JsonConvert.DeserializeObject<List<QuestReward>>(rewardStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestReward:{ex}");
                }

                foreach (var questReward in questRewards)
                {
                    int.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val, out int npcId);
                    int.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "Exp")?.Val, out int exp);
                    long.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "Money")?.Val, out long money);
                    int.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "WareId")?.Val, out int wareId);
                    int.TryParse(questReward.Attrs.FirstOrDefault(x => x.Attr == "Number")?.Val, out int number);

                    var rewardEnum = (QuestRewardEnum)Enum.Parse(typeof(QuestRewardEnum), questReward.Reward, true);


                    switch (rewardEnum)
                    {


                        case QuestRewardEnum.物品:
                            var ware = await _wareDomainService.Get(wareId);
                            if (ware != null)
                            {
                                await _mudProvider.ShowMessage(player.Id, $"获得 {number}{ware.Unit}[{ware.Name}]");
                            }
                            // 添加物品

                            break;

                        case QuestRewardEnum.经验:
                            player.Exp += exp;
                            await _mudProvider.ShowMessage(player.Id, $"获得经验 +{exp}");
                            break;

                        case QuestRewardEnum.金钱:
                            player.Money += money;
                            await _mudProvider.ShowMessage(player.Id, $"获得 +{money.ToMoney()}");
                            break;


                    }

                }

                await _playerDomainService.Update(player);
            }

            result.IsSuccess = true;
            return await Task.FromResult(result);
        }

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

internal static Double ParseNumber(String str)
        {
            // Trim
            str = str?.Trim() ?? String.Empty;

            // Empty
            if (String.IsNullOrEmpty(str))
            {
                return 0d;
            }
            // Try parse
            else if (Double.TryParse(str, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out var value))
            {
                return value;
            }
            // Check for 0x[0-9a-fA-F]+
            else if (str[0] == '0' &&
                str.Length > 2 &&
                str[1] == 'x' &&
                str.Skip(2).All(x => (x >= '0' && x <= '9') || (x >= 'a' && x <= 'f') || (x >= 'A' && x <= 'F')))
            {
                // Try parse
                if (Int32.TryParse(str.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out var integer))
                {
                    return (Double)integer;
                }

                // Otherwise exceeds range
            }
            // Check for 0o[0-9]+
            else if (str[0] == '0' &&
                str.Length > 2 &&
                str[1] == 'o' &&
                str.Skip(2).All(x => x >= '0' && x <= '7'))
            {
                // Try parse
                var integer = default(Int32?);
                try
                {
                    integer = Convert.ToInt32(str.Substring(2), 8);
                }
                // Otherwise exceeds range
                catch (Exception)
                {
                }

                // Success
                if (integer != null)
                {
                    return (Double)integer.Value;
                }
            }
            // Infinity
            else if (String.Equals(str, ExpressionConstants.Infinity, StringComparison.Ordinal))
            {
                return Double.PositiveInfinity;
            }
            // -Infinity
            else if (String.Equals(str, ExpressionConstants.NegativeInfinity, StringComparison.Ordinal))
            {
                return Double.NegativeInfinity;
            }

            // Otherwise NaN
            return Double.NaN;
        }

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

public override ExprLiteral FromString(string? value) =>
            value == null
                ? SqQueryBuilder.Literal((int?)null)
                : int.TryParse(value, out var result)
                    ? SqQueryBuilder.Literal(result)
                    : throw new SqExpressException($"Could not parse '{value}' as int for column '{this.ColumnName.Name}'.");

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

public override void Apply(TModel target)
        {
            this.Apply(
                target,
                (type, parent, current) =>
                {
                    // Empty current means replace the whole object.
                    if (string.IsNullOrEmpty(current))
                    {
                        parent = this.Value;
                    }
                    else if (type.IsList())
                    {
                        var list = (IList)parent;
                        if (current == EndOfIndex)
                        {
                            list.Add(this.Value);
                        }
                        else
                        {
                            int index;
                            // When index == list.Count it's the same
                            // as doing an index append to the end.
                            if (int.TryParse(current, out index) &&
                                list.Count >= index)
                            {
                                list.Insert(index, this.Value);
                            }
                            else
                            {
                                // We can't insert beyond the length of the list.
                                throw new PatchOperationFailedException(PatchResources.IndexOutOfRange(this.Path));
                            }
                        }
                    }
                    else if (type.IsDictionary())
                    {
                        ((IDictionary)parent)[current] = this.Value;
                    }
                    else
                    {
                        type.SetMemberValue(current, parent, this.Value);
                    }
                });
        }

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

private async Task<WareModel> Computed(WareEnreplacedy ware, PlayerWareEnreplacedy playerWare)
        {
            var wareModel = _mapper.Map<WareModel>(ware);
            wareModel.PlayerWareId = playerWare.Id;
            wareModel.Number = playerWare.Number;
            wareModel.Status = playerWare.Status;

            var wareEffectAttr = new WareEffectAttr();
            var effects = JsonConvert.DeserializeObject<List<WareEffect>>(ware.Effect);
            foreach (var effect in effects)
            {
                foreach (var attr in effect.Attrs)
                {
                    int.TryParse(attr.Val, out int val);

                    switch (attr.Attr)
                    {
                        case "Atk":
                            wareEffectAttr.Atk += val;
                            break;

                        case "Def":
                            wareEffectAttr.Def += val;
                            break;

                        case "Hp":
                            wareEffectAttr.Hp += val;
                            break;

                        case "Mp":
                            wareEffectAttr.Mp += val;
                            break;
                    }
                }
            }

            wareModel.WareEffect = wareEffectAttr;

            return await Task.FromResult(wareModel);
        }

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

public override void Apply(TModel target)
        {
            this.Apply(
                target,
                (type, parent, current) =>
                {
                    if (type.IsList())
                    {
                        var list = (IList)parent;
                        int index;
                        if (int.TryParse(current, out index) &&
                            list.Count > index)
                        {
                            list[index] = this.Value;
                        }
                        else
                        {
                            throw new PatchOperationFailedException(PatchResources.CannotReplaceNonExistantValue(this.Path));
                        }
                    }
                    else if (type.IsDictionary())
                    {
                        var dictionary = (IDictionary)parent;
                        if (!dictionary.Contains(current))
                        {
                            throw new InvalidPatchFieldNameException(PatchResources.InvalidFieldName(current));
                        }

                        dictionary[current] = this.Value;
                    }
                    else
                    {
                        if (type.GetMemberValue(current, parent) == null)
                        {
                            throw new PatchOperationFailedException(PatchResources.CannotReplaceNonExistantValue(this.Path));
                        }

                        type.SetMemberValue(current, parent, this.Value);
                    }
                });
        }

19 View Source File : Restful.cs
License : MIT License
Project Creator : 2881099

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string restfulRequestPath, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(restfulRequestPath.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				using (var db = new FreeContext(fsql)) {
					var dbset = db.Set<object>();
					dbset.AsType(enreplacedyType);

					switch (req.Method.ToLower()) {
						case "get":
							if (remUrl.Length == 1) {
								int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
								int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
								if (getpage <= 0) getpage = 1;
								if (getlimit <= 0) getlimit = 20;
								long getlistTotal = 0;

								var getselect = fsql.Select<object>().AsType(enreplacedyType);
								if (getpage == 1) getlistTotal = await getselect.CountAsync();
								var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
								var gethashlists = new Dictionary<string, object>[getlist.Count];
								var gethashlistsIndex = 0;
								foreach (var getlisreplacedem in getlist) {
									var gethashlist = new Dictionary<string, object>();
									foreach (var getcol in tb.ColumnsByCs) {
										gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
									}
									gethashlists[gethashlistsIndex++] = gethashlist;
								}
								if (getpage == 1) {
									await Utils.Jsonp(context, new { code = 0, message = "Success", data = gethashlists, totalCount = getlistTotal });
									return true;
								}
								await Utils.Jsonp(context, new { code = 0, message = "Success", data = gethashlists });
								return true;
							}
							if (remUrl.Length - 1 != tb.Primarys.Length) throw new Exception($"UseFreeAdminLtePreview 查询,参数数目与主键不匹配,应该相同");
							var gereplacedem = Activator.CreateInstance(enreplacedyType);
							var getindex = 1;
							foreach (var getpk in tb.Primarys)
								fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, remUrl[getindex++]);
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							var gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}
							await Utils.Jsonp(context, new { code = 0, message = "Success", data = gethash });
							return true;
						case "post":
							var postbodyraw = await Utils.GetBodyRawText(req);
							var postjsonitem = Newtonsoft.Json.JsonConvert.DeserializeObject(postbodyraw, enreplacedyType);
							await dbset.AddAsync(postjsonitem);
							await db.SaveChangesAsync();
							await Utils.Jsonp(context, new { code = 0, message = "Success", data = postjsonitem });
							return true;
						case "put":
							if (remUrl.Length - 1 != tb.Primarys.Length) throw new Exception($"UseFreeAdminLtePreview 更新错误,参数数目与主键不匹配,应该相同");
							var putbodyraw = await Utils.GetBodyRawText(req);
							var putjsonitem = Newtonsoft.Json.JsonConvert.DeserializeObject(putbodyraw, enreplacedyType);
							var putindex = 1;
							foreach (var putpk in tb.Primarys)
								fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, putjsonitem, putpk.CsName, remUrl[putindex++]);
							await dbset.UpdateAsync(putjsonitem);
							await db.SaveChangesAsync();
							await Utils.Jsonp(context, new { code = 0, message = "Success" });
							return true;
						case "delete":
							if (remUrl.Length - 1 != tb.Primarys.Length) throw new Exception($"UseFreeAdminLtePreview 删除错误,参数数目与主键不匹配,应该相同");
							var delitem = Activator.CreateInstance(enreplacedyType);
							var delindex = 1;
							foreach (var delpk in tb.Primarys)
								fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, remUrl[delindex++]);
							dbset.Remove(delitem);
							await db.SaveChangesAsync();
							await Utils.Jsonp(context, new { code = 0, message = "Success" });
							return true;
					}
				}
			}
			return false;
		}

19 View Source File : NumericValueComparer.cs
License : MIT License
Project Creator : Actipro

public override int Compare(IDataModel x, IDataModel y) {
			var xValue = 0;
			var yValue = 1;

			int.TryParse(x.DisplayName, out xValue);
			int.TryParse(y.DisplayName, out yValue);

			return xValue.CompareTo(yValue) * (this.SortDescending ? -1 : 1);
		}

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

private async Task<bool> CheckIf(PlayerEnreplacedy player, string condition, List<CaseAttribute> attrs, string input)
        {
            var field = attrs.FirstOrDefault(x => x.Attr == "Field")?.Val;
            var relation = attrs.FirstOrDefault(x => x.Attr == "Relation")?.Val;
            var value = attrs.FirstOrDefault(x => x.Attr == "Value")?.Val;
            var wareName = attrs.FirstOrDefault(x => x.Attr == "WareName")?.Val;
            var number = attrs.FirstOrDefault(x => x.Attr == "Number")?.Val;
            int.TryParse(attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val, out int questId);

            if (string.IsNullOrEmpty(condition))
            {
                return true;
            }

            if (!Enum.TryParse(condition, true, out ConditionTypeEnum conditionEnum))
            {
                return true;
            }


            switch (conditionEnum)
            {
                case ConditionTypeEnum.角色属性:
                    if (!CheckField(player, field, value, relation))
                    {
                        return false;
                    }
                    break;

                case ConditionTypeEnum.是否拥有物品:
                    if (!await CheckWare(player.Id, wareName, number, relation))
                    {
                        return false;
                    }

                    break;

                case ConditionTypeEnum.是否领取任务:

                    var playerQuest = await _playerQuestDomainService.Get(x => x.QuestId == questId && x.PlayerId == player.Id);
                    if (playerQuest == null)
                    {
                        return false;
                    }
                    break;

                case ConditionTypeEnum.是否完成任务:

                    break;

                case ConditionTypeEnum.活动记录:

                    break;
            }

            return true;
        }

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

private BankIdSupportedDeviceOsVersion GetDeviceOsVersion(ClientInfo clientInfo)
        {
            var hasMajor = int.TryParse(clientInfo.OS.Major, out var major);
            var hasMinor = int.TryParse(clientInfo.OS.Minor, out var minor);
            var hasPatch = int.TryParse(clientInfo.OS.Patch, out var patch);

            return (hasMajor, hasMinor, hasPatch) switch
            {
                (true, true, true) => new BankIdSupportedDeviceOsVersion(major, minor, patch),
                (true, true, false) => new BankIdSupportedDeviceOsVersion(major, minor),
                (true, false, false) => new BankIdSupportedDeviceOsVersion(major),
                _ => BankIdSupportedDeviceOsVersion.Empty
            };

19 View Source File : frmMain.cs
License : GNU General Public License v3.0
Project Creator : 0x00000FF

private void btnForce_Click(object sender, EventArgs e)
        {
            uint outvar;
            int tryval;

            if(!int.TryParse(Inputs.Text, out tryval) || tryval < 0 || tryval > 99999999)
            {
                Inputs.Text = "NOT VALID VALUE!";
                return;
            }

            byte[] overscore = BitConverter.GetBytes(tryval);

            if (handle != 0)
            {
                var _try = WriteProcessMemory(handle, ScorePtr, overscore, 4, out outvar);
                if (!_try)
                {
                    MessageBox.Show("Failed to modify memory. try again.");
                    return;
                }
            }
        }

19 View Source File : POParser.cs
License : MIT License
Project Creator : adams85

private void ParsePluralForms(string line, string value)
        {
            Match match;
            if (value.Length > 0 &&
                (match = Regex.Match(value, @"^nplurals\s*=\s*(\d+);\s*plural\s*=\s*([^;]+);$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)).Success &&
                int.TryParse(match.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int pluralFormCount) &&
                pluralFormCount > 0 &&
                _catalog.TrySetPluralFormSelector(match.Groups[2].Value))
                _catalog.PluralFormCount = pluralFormCount;
            else
                AddWarning(DiagnosticCodes.InvalidHeaderValue, line);
        }

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

private async Task<ResultModel> CheckQuestConsume(PlayerEnreplacedy player, string consumeStr)
        {
            var result = new ResultModel
            {
                IsSuccess = false
            };
            if (!string.IsNullOrEmpty(consumeStr))
            {
                List<QuestConsume> questConsumes = new List<QuestConsume>();
                try
                {
                    questConsumes = JsonConvert.DeserializeObject<List<QuestConsume>>(consumeStr);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestConsume:{ex}");
                }

                foreach (var questConsume in questConsumes)
                {
                    var npcId = questConsume.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    int.TryParse(questConsume.Attrs.FirstOrDefault(x => x.Attr == "Exp")?.Val, out int exp);
                    long.TryParse(questConsume.Attrs.FirstOrDefault(x => x.Attr == "Money")?.Val, out long money);

                    var consumeEnum = (QuestConsumeEnum)Enum.Parse(typeof(QuestConsumeEnum), questConsume.Consume, true);


                    switch (consumeEnum)
                    {


                        case QuestConsumeEnum.物品:

                            //TODO
                            result.ErrorMessage = $"完成任务需要消耗物品";
                            return result;

                        case QuestConsumeEnum.经验:
                            if (player.Exp < exp)
                            {
                                result.ErrorMessage = $"完成任务需要消耗经验 {exp}";
                                return result;
                            }
                            break;

                        case QuestConsumeEnum.金钱:
                            if (player.Money < money)
                            {
                                result.ErrorMessage = $"完成任务需要消耗 {money.ToMoney()}";
                                return result;
                            }

                            break;


                    }

                }
            }

            result.IsSuccess = true;
            return await Task.FromResult(result);
        }

19 View Source File : Admin.cs
License : MIT License
Project Creator : 2881099

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				var tpl = _tpl.Value;

				switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
					case null:
						//首页
						if (true) {
							MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);

							//ManyToOne/OneToOne
							var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
								}
							}

							int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
							int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
							if (getpage <= 0) getpage = 1;
							if (getlimit <= 0) getlimit = 20;

							var getselect = fsql.Select<object>().AsType(enreplacedyType);
							foreach (var getlistF in getlistFilter) {
								var qv = req.Query[getlistF.Item3].ToArray();
								if (qv.Any()) {
									switch (getlistF.Item1.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											if (true) {
												var midType = getlistF.Item1.RefMiddleEnreplacedyType;
												var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
												var midISelect = typeof(ISelect<>).MakeGenericType(midType);

												var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
												var expParam = Expression.Parameter(typeof(object), "a");
												var midParam = Expression.Parameter(midType, "mdtp");

												var anyMethod = midISelect.GetMethod("Any");
												var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
												var expLambad = Expression.Lambda<Func<object, bool>>(
													Expression.Call(
														Expression.Call(
															Expression.Call(
																Expression.Constant(fsql),
																typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
															),
															midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
															Expression.Lambda(
																typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
																Expression.AndAlso(
																	Expression.Equal(
																		Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
																	),
																	Expression.Call(
																		Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
																		Expression.NewArrayInit(
																			getlistF.Item1.MiddleColumns[1].CsType,
																			selectExp
																		),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
																	)
																),
																midParam
															)
														),
														anyMethod,
														Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
													),
													expParam);

												getselect.Where(expLambad);
											}
											continue;
									}
								}
							}

							var getlistTotal = await getselect.CountAsync();
							var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
							var gethashlists = new Dictionary<string, object>[getlist.Count];
							var gethashlistsIndex = 0;
							foreach (var getlisreplacedem in getlist) {
								var gethashlist = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
								}
								gethashlists[gethashlistsIndex++] = gethashlist;
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["getlist"] = gethashlists;
							options["getlistTotal"] = getlistTotal;
							options["getlistFilter"] = getlistFilter;
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
							await res.WriteAsync(str);
						}
						return true;
					case "add":
					case "edit":
						//编辑页
						object gereplacedem = null;
						Dictionary<string, object> gethash = null;
						if (req.Query.Any()) {
							gereplacedem = Activator.CreateInstance(enreplacedyType);
							foreach (var getpk in tb.Primarys) {
								var reqv = req.Query[getpk.CsName].ToArray();
								if (reqv.Any())
									fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
							}
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							if (gereplacedem != null) {
								gethash = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
								}
							}
						}

						if (req.Method.ToLower() == "get") {
							MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);

							//ManyToOne/OneToOne
							var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							var getlistManyed = new Dictionary<string, IEnumerable<string>>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));

										if (gereplacedem != null) {
											var midType = tbref.RefMiddleEnreplacedyType;
											var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
											var manyed = await fsql.Select<object>().AsType(midType)
												.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
												.ToListAsync();
											getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
										}
										continue;
								}
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["gethash"] = gethash;
							options["getlistFilter"] = getlistFilter;
							options["getlistManyed"] = getlistManyed;
							options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
							await res.WriteAsync(str);

						} else {
							if (gereplacedem == null) {
								gereplacedem = Activator.CreateInstance(enreplacedyType);
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
								}
							}
							var manySave = new List<(TableRef, object[], List<object>)>();
							if (req.Form.Any()) {
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);

									var reqv = req.Form[getcol.CsName].ToArray();
									if (reqv.Any())
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
								}
								//ManyToMany
								foreach (var prop in tb.Properties) {
									if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
									var tbref = tb.GetTableRef(prop.Key, false);
									if (tbref == null) continue;
									switch (tbref.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											var midType = tbref.RefMiddleEnreplacedyType;
											var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);

											var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
											var reqvIndex = 0;
											var manyVals = new object[reqv.Length];
											foreach (var rv in reqv) {
												var miditem = Activator.CreateInstance(midType);
												foreach (var getcol in tb.Columns.Values) {
													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);

													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
												}
												//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
												fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
												manyVals[reqvIndex++] = miditem;
											}
											var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
											manySave.Add((tbref, manyVals, molds));
											continue;
									}
								}
							}


							using (var db = fsql.CreateDbContext()) {

								var dbset = db.Set<object>();
								dbset.AsType(enreplacedyType);

								await dbset.AddOrUpdateAsync(gereplacedem);

								foreach (var ms in manySave) {
									var midType = ms.Item1.RefMiddleEnreplacedyType;
									var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));

									var manyset = db.Set<object>();
									manyset.AsType(midType);
									
									foreach (var msVal in ms.Item2) {
										fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
										await manyset.AddOrUpdateAsync(msVal);
										moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
									}
									manyset.RemoveRange(moldsDic.Values);
								}

								await db.SaveChangesAsync();
							}
							gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
						}
						return true;
					case "del":
						if (req.Method.ToLower() == "post") {

							var delitems = new List<object>();
							var reqv = new List<string[]>();
							foreach(var delpk in tb.Primarys) {
								var reqvs = req.Form[delpk.CsName].ToArray();
								if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
								reqv.Add(reqvs);
							}
							if (reqv[0].Length == 0) return true;

							using (var ctx = fsql.CreateDbContext()) {
								var dbset = ctx.Set<object>();
								dbset.AsType(enreplacedyType);

								for (var a = 0; a < reqv[0].Length; a++) {
									object delitem = Activator.CreateInstance(enreplacedyType);
									var delpkindex = 0;
									foreach (var delpk in tb.Primarys)
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
									dbset.Remove(delitem);
								}
								await ctx.SaveChangesAsync();
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
							return true;
						}
						break;
				}
			}
			return false;
		}

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

public override void ParseAndRun(ChatCMDEnv env) {
            CelesteNetPlayerSession? session = env.Session;
            if (session == null)
                return;

            Channels channels = env.Server.Channels;

            Channel? c;

            if (int.TryParse(env.Text, out int page) ||
                string.IsNullOrWhiteSpace(env.Text)) {

                if (channels.All.Count == 0) {
                    env.Send($"No channels. See {Chat.Settings.CommandPrefix}{ID} on how to create one.");
                    return;
                }

                const int pageSize = 8;

                StringBuilder builder = new();

                page--;
                int pages = (int) Math.Ceiling(channels.All.Count / (float) pageSize);
                if (page < 0 || pages <= page)
                    throw new Exception("Page out of range.");

                if (page == 0)
                    builder
                        .Append("You're in ")
                        .Append(session.Channel.Name)
                        .AppendLine();

                for (int i = page * pageSize; i < (page + 1) * pageSize && i < channels.All.Count; i++) {
                    c = channels.All[i];
                    builder
                        .Append(c.PublicName)
                        .Append(" - ")
                        .Append(c.Players.Count)
                        .Append(" players")
                        .AppendLine();
                }

                builder
                    .Append("Page ")
                    .Append(page + 1)
                    .Append("/")
                    .Append(pages);

                env.Send(builder.ToString().Trim());

                return;
            }

            Tuple<Channel, Channel> tuple = channels.Move(session, env.Text);
            if (tuple.Item1 == tuple.Item2) {
                env.Send($"Already in {tuple.Item2.Name}");
            } else {
                env.Send($"Moved to {tuple.Item2.Name}");
            }
        }

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

public override ExprLiteral FromString(string? value) =>
            value == null
                ? throw new SqExpressException($"Value cannot be null for '{this.ColumnName.Name}' non nullable column")
                : int.TryParse(value, out var result)
                    ? SqQueryBuilder.Literal(result)
                    : throw new SqExpressException($"Could not parse '{value}' as int for column '{this.ColumnName.Name}'.");

19 View Source File : CommandLineParser.cs
License : MIT License
Project Creator : 0xd4d

public static JitDasmOptions Parse(string[] args) {
			if (args.Length == 0)
				throw new ShowCommandLineHelpException();

			var options = new JitDasmOptions();
			for (int i = 0; i < args.Length; i++) {
				var arg = args[i];
				var next = i + 1 < args.Length ? args[i + 1] : null;
				switch (arg) {
				case "-h":
				case "--help":
					throw new ShowCommandLineHelpException();

				case "-p":
				case "--pid":
					if (next is null)
						throw new CommandLineParserException("Missing pid value");
					if (!int.TryParse(next, out options.Pid))
						throw new CommandLineParserException($"Invalid pid: {next}");
					try {
						using (var process = Process.GetProcessById(options.Pid))
							VerifyProcess(process);
					}
					catch (ArgumentException) {
						throw new CommandLineParserException($"Process does not exist, pid = {options.Pid}");
					}
					i++;
					break;

				case "-pn":
				case "--process":
					if (next is null)
						throw new CommandLineParserException("Missing process name");
					Process[]? processes = null;
					try {
						processes = Process.GetProcessesByName(next);
						if (processes.Length == 0)
							throw new CommandLineParserException($"Could not find process '{next}'");
						if (processes.Length > 1)
							throw new CommandLineParserException($"Found more than one process with name '{next}'");
						options.Pid = processes[0].Id;
						VerifyProcess(processes[0]);
					}
					finally {
						if (!(processes is null)) {
							foreach (var p in processes)
								p.Dispose();
						}
					}
					i++;
					break;

				case "-m":
				case "--module":
					if (next is null)
						throw new CommandLineParserException("Missing module name");
					options.ModuleName = next;
					i++;
					break;

				case "-l":
				case "--load":
					if (next is null)
						throw new CommandLineParserException("Missing module filename");
					if (!File.Exists(next))
						throw new CommandLineParserException($"Could not find module {next}");
					options.LoadModule = Path.GetFullPath(next);
					i++;
					break;

				case "--no-run-cctor":
					options.RunClreplacedConstructors = false;
					break;

				case "-s":
				case "--search":
					if (next is null)
						throw new CommandLineParserException("Missing replacedembly search path");
					foreach (var path in next.Split(new[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries)) {
						if (Directory.Exists(path))
							options.replacedemblySearchPaths.Add(path);
					}
					i++;
					break;

				case "--diffable":
					options.Diffable = true;
					break;

				case "--no-addr":
					options.ShowAddresses = false;
					break;

				case "--no-bytes":
					options.ShowHexBytes = false;
					break;

				case "--no-source":
					options.ShowSourceCode = false;
					break;

				case "--heap-search":
					options.HeapSearch = true;
					break;

				case "--filename-format":
					if (next is null)
						throw new CommandLineParserException("Missing filename format");
					switch (next) {
					case "name":
						options.FilenameFormat = FilenameFormat.MemberName;
						break;
					case "tokname":
						options.FilenameFormat = FilenameFormat.TokenMemberName;
						break;
					case "token":
						options.FilenameFormat = FilenameFormat.Token;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename format: {next}");
					}
					i++;
					break;

				case "-f":
				case "--file":
					if (next is null)
						throw new CommandLineParserException("Missing filename kind");
					switch (next) {
					case "stdout":
						options.FileOutputKind = FileOutputKind.Stdout;
						break;
					case "file":
						options.FileOutputKind = FileOutputKind.OneFile;
						break;
					case "type":
						options.FileOutputKind = FileOutputKind.OneFilePerType;
						break;
					case "method":
						options.FileOutputKind = FileOutputKind.OneFilePerMethod;
						break;
					default:
						throw new CommandLineParserException($"Unknown filename kind: {next}");
					}
					i++;
					break;

				case "-d":
				case "--disasm":
					if (next is null)
						throw new CommandLineParserException("Missing disreplacedembler kind");
					switch (next) {
					case "masm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Masm;
						break;
					case "nasm":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Nasm;
						break;
					case "gas":
					case "att":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Gas;
						break;
					case "intel":
						options.DisreplacedemblerOutputKind = DisreplacedemblerOutputKind.Intel;
						break;
					default:
						throw new CommandLineParserException($"Unknown disreplacedembler kind: {next}");
					}
					i++;
					break;

				case "-o":
				case "--output":
					if (next is null)
						throw new CommandLineParserException("Missing output file/dir");
					options.OutputDir = next;
					i++;
					break;

				case "--type":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--type-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing type name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.TypeFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.TypeFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				case "--method":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.TokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.NameFilter.Add(elem);
					}
					i++;
					break;

				case "--method-exclude":
					if (next is null)
						throw new CommandLineParserException("Missing method name filter");
					foreach (var elem in next.Split(typeTokSep, StringSplitOptions.RemoveEmptyEntries)) {
						if (TryParseToken(elem, out uint tokenLo, out uint tokenHi))
							options.MethodFilter.ExcludeTokensFilter.Add(tokenLo, tokenHi);
						else
							options.MethodFilter.ExcludeNameFilter.Add(elem);
					}
					i++;
					break;

				default:
					throw new CommandLineParserException($"Unknown option: {arg}");
				}
			}

			if (!string2.IsNullOrEmpty(options.LoadModule)) {
				using (var process = Process.GetCurrentProcess())
					options.Pid = process.Id;
				options.ModuleName = options.LoadModule;
			}

			if (string.IsNullOrEmpty(options.ModuleName))
				throw new CommandLineParserException("Missing module name");
			if (options.Pid == 0)
				throw new CommandLineParserException("Missing process id or name");
			if (options.FileOutputKind != FileOutputKind.Stdout && string.IsNullOrEmpty(options.OutputDir))
				throw new CommandLineParserException("Missing output file/dir");
			return options;
		}

19 View Source File : Console.cs
License : MIT License
Project Creator : 5minlab

[Route("^/console/fetch$")]
        public static void FetchLog(RequestContext context) {
            // 로그를 어디부터 이어서 받을지 정할수 있도록
            // 매번 전체 로그를 보낼 필요는 없을것이다
            var last = context.Request.QueryString.Get("last");
            int lastId = 0;
            if (!int.TryParse(last, out lastId)) {
                lastId = 0;
            }

            // 필요한것만 내려주도록
            jsonBuilder.Clear();
            foreach (var r in Instance.m_output) {
                if (r.uid > lastId) {
                    jsonBuilder.Add(r);
                }
            }
            var sb = new StringBuilder();
            jsonBuilder.AppendJson(sb);
            var json = sb.ToString();
            context.Response.WriteString(json, "application/json");
        }

19 View Source File : NumberOrNullConverter.cs
License : Microsoft Public License
Project Creator : AArnott

public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
	{
		// Converts a string to an int?
		string? str = (string?)value;
		if (string.IsNullOrEmpty(str))
		{
			return null;
		}

		if (int.TryParse(str, NumberStyles.Integer, culture, out int result))
		{
			return result;
		}

		return value;
	}

See More Examples