long.TryParse(string, out long)

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

711 Examples 7

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

public virtual ChatCMDArg Parse() {
            // TODO: Improve or rewrite. This comes from GhostNet, which adopted it from disbot (0x0ade's C# Discord bot).

            if (int.TryParse(String, out Int)) {
                Type = ChatCMDArgType.Int;
                Long = IntRangeFrom = IntRangeTo = Int;
                ULong = (ulong) Int;

            } else if (long.TryParse(String, out Long)) {
                Type = ChatCMDArgType.Long;
                ULong = (ulong) Long;

            } else if (ulong.TryParse(String, out ULong)) {
                Type = ChatCMDArgType.ULong;

            } else if (float.TryParse(String, out Float)) {
                Type = ChatCMDArgType.Float;
            }

            if (Type == ChatCMDArgType.String) {
                string[] split;
                int from, to;
                if ((split = String.Split('-')).Length == 2) {
                    if (int.TryParse(split[0].Trim(), out from) && int.TryParse(split[1].Trim(), out to)) {
                        Type = ChatCMDArgType.IntRange;
                        IntRangeFrom = from;
                        IntRangeTo = to;
                    }
                } else if ((split = String.Split('+')).Length == 2) {
                    if (int.TryParse(split[0].Trim(), out from) && int.TryParse(split[1].Trim(), out to)) {
                        Type = ChatCMDArgType.IntRange;
                        IntRangeFrom = from;
                        IntRangeTo = from + to;
                    }
                }
            }

            return this;
        }

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

public static long ToLong(this object s)
    {
        if (s == null || s == DBNull.Value)
            return 0L;

        long.TryParse(s.ToString(), out long result);
        return result;
    }

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

private void MapMetadata(object[] results, out DateTimeOffset? absoluteExpiration, out TimeSpan? slidingExpiration) {
			absoluteExpiration = null;
			slidingExpiration = null;
			if (long.TryParse(results[0]?.ToString(), out var absoluteExpirationTicks) && absoluteExpirationTicks != NotPresent) {
				absoluteExpiration = new DateTimeOffset(absoluteExpirationTicks, TimeSpan.Zero);
			}
			if (long.TryParse(results[1]?.ToString(), out var slidingExpirationTicks) && slidingExpirationTicks != NotPresent) {
				slidingExpiration = new TimeSpan(slidingExpirationTicks);
			}
		}

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

public static ConnectionStringBuilder Parse(string connectionString)
        {
            var ret = new ConnectionStringBuilder();
            if (string.IsNullOrEmpty(connectionString)) return ret;

            //支持密码中带有逗号,将原有 split(',') 改成以下处理方式
            var vs = Regex.Split(connectionString, @"\,([\w \t\r\n]+)=", RegexOptions.Multiline);
            ret.Host = vs[0].Trim();

            for (var a = 1; a < vs.Length; a += 2)
            {
                var kv = new[] { Regex.Replace(vs[a].ToLower().Trim(), @"[ \t\r\n]", ""), vs[a + 1] };
                switch (kv[0])
                {
                    case "ssl": if (kv.Length > 1 && kv[1].ToLower().Trim() == "true") ret.Ssl = true; break;
                    case "protocol": if (kv.Length > 1 && kv[1].ToUpper().Trim() == "RESP3") ret.Protocol = RedisProtocol.RESP3; break;
                    case "userid":
                    case "user": if (kv.Length > 1) ret.User = kv[1].Trim(); break;
                    case "preplacedword": if (kv.Length > 1) ret.Preplacedword = kv[1]; break;
                    case "database":
                    case "defaultdatabase": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var database) && database > 0) ret.Database = database; break;

                    case "prefix": if (kv.Length > 1) ret.Prefix = kv[1].Trim(); break;
                    case "name":
                    case "clientname": if (kv.Length > 1) ret.ClientName = kv[1].Trim(); break;
                    case "encoding": if (kv.Length > 1) ret.Encoding = Encoding.GetEncoding(kv[1].Trim()); break;

                    case "idletimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var idleTimeout) && idleTimeout > 0) ret.IdleTimeout = TimeSpan.FromMilliseconds(idleTimeout); break;
                    case "connecttimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var connectTimeout) && connectTimeout > 0) ret.ConnectTimeout = TimeSpan.FromMilliseconds(connectTimeout); break;
                    case "receivetimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var receiveTimeout) && receiveTimeout > 0) ret.ReceiveTimeout = TimeSpan.FromMilliseconds(receiveTimeout); break;
                    case "sendtimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var sendTimeout) && sendTimeout > 0) ret.SendTimeout = TimeSpan.FromMilliseconds(sendTimeout); break;

                    case "poolsize":
                    case "maxpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var maxPoolSize) && maxPoolSize > 0) ret.MaxPoolSize = maxPoolSize; break;
                    case "minpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var minPoolSize) && minPoolSize > 0) ret.MinPoolSize = minPoolSize; break;
                    case "retry": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var retry) && retry > 0) ret.Retry = retry; break;
                }
            }
            return ret;
        }

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

internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
        {
            if (valueRaw == null) return default(T);
            var type = typeof(T);
            var typename = type.ToString().TrimEnd(']');
            if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
            if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
            if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
            if (valueRaw.Length == 0) return default(T);

            string valueStr = null;
            if (type.IsValueType)
            {
                valueStr = encoding.GetString(valueRaw);
                bool isNullable = typename.StartsWith("System.Nullable`1[");
                var basename = isNullable ? typename.Substring(18) : typename;

                bool isElse = false;
                object obj = null;
                switch (basename)
                {
                    case "System.Boolean":
                        if (valueStr == "1") obj = true;
                        else if (valueStr == "0") obj = false;
                        break;
                    case "System.Byte":
                        if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
                        break;
                    case "System.Char":
                        if (valueStr.Length > 0) obj = valueStr[0];
                        break;
                    case "System.Decimal":
                        if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
                        break;
                    case "System.Double":
                        if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
                        break;
                    case "System.Single":
                        if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
                        break;
                    case "System.Int32":
                        if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
                        break;
                    case "System.Int64":
                        if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
                        break;
                    case "System.SByte":
                        if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
                        break;
                    case "System.Int16":
                        if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
                        break;
                    case "System.UInt32":
                        if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
                        break;
                    case "System.UInt64":
                        if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
                        break;
                    case "System.UInt16":
                        if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
                        break;
                    case "System.DateTime":
                        if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
                        break;
                    case "System.DateTimeOffset":
                        if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
                        break;
                    case "System.TimeSpan":
                        if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
                        break;
                    case "System.Guid":
                        if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
                        break;
                    default:
                        isElse = true;
                        break;
                }

                if (isElse == false)
                {
                    if (obj == null) return default(T);
                    return (T)obj;
                }
            }

            if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));

            if (valueStr == null) valueStr = encoding.GetString(valueRaw);
            if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
            return valueStr.ConvertTo<T>();
        }

19 View Source File : JsonReader.cs
License : MIT License
Project Creator : 404Lcc

private void ProcessNumber (string number)
        {
            if (number.IndexOf ('.') != -1 ||
                number.IndexOf ('e') != -1 ||
                number.IndexOf ('E') != -1) {

                double n_double;
                if (Double.TryParse (number, out n_double)) {
                    token = JsonToken.Double;
                    token_value = n_double;

                    return;
                }
            }

            int n_int32;
            if (Int32.TryParse (number, out n_int32)) {
                token = JsonToken.Int;
                token_value = n_int32;

                return;
            }

            long n_int64;
            if (Int64.TryParse (number, out n_int64)) {
                token = JsonToken.Long;
                token_value = n_int64;

                return;
            }

            ulong n_uint64;
            if (UInt64.TryParse(number, out n_uint64))
            {
                token = JsonToken.Long;
                token_value = n_uint64;

                return;
            }

            // Shouldn't happen, but just in case, return something
            token = JsonToken.Int;
            token_value = 0;
        }

19 View Source File : Utility.Convertor.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static object Convert(string typeStr,string typeValue)
            {
                Type type = Convert(typeStr);
                if (null!=type)
                {
                    var typeObject = Reflection.New(type);
                    if (type==typeof(int))
                    {
                        int v;
                        if (int.TryParse(typeValue,out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(Int16))
                    {
                        Int16 v;
                        if (Int16.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(Int64))
                    {
                        Int64 v;
                        if (Int64.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(float))
                    {
                        float v;
                        if (float.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(double))
                    {
                        double v;
                        if (double.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(decimal))
                    {
                        decimal v;
                        if (decimal.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(char))
                    {
                        char v;
                        if (char.TryParse(typeValue, out v))
                        {
                            typeObject = v;
                        }
                    }
                    else if (type == typeof(string))
                    {
                        typeObject = typeValue;
                    }
                }
                return null;
            }

19 View Source File : SecondToStringConverter.cs
License : MIT License
Project Creator : 944095635

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var arr = (value as string)?.Split(':');
            if (arr?.Length == 2)
            {
                long hour, minute;
                if (Int64.TryParse(arr[0], out hour) && Int64.TryParse(arr[1], out minute))
                {
                    return hour * 3600 + minute * 60;
                }
            }
            return value;
        }

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

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

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

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

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

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

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

                    return false;
                }
            }
            return true;
        }

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

private static long TryGetDateInt(ViewSereplacedem viewSereplacedem)
        {
            var dateString = TryParseDateString(viewSereplacedem);
            if (string.IsNullOrEmpty(dateString))
            {
                return -1;
            }

            long dateInt = -1;
            long.TryParse(dateString, out dateInt);

            return dateInt;
        }

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

public async Task RunAsync(
            RunnerActionPluginExecutionContext context,
            CancellationToken token)
        {
            string artifactName = context.GetInput(PublishArtifactInputNames.ArtifactName, required: false);  // Back compat since we rename input `artifactName` to `name`
            if (string.IsNullOrEmpty(artifactName))
            {
                artifactName = context.GetInput(PublishArtifactInputNames.Name, required: true);
            }

            string targetPath = context.GetInput(PublishArtifactInputNames.Path, required: true);
            string defaultWorkingDirectory = context.GetGitHubContext("workspace");

            targetPath = Path.IsPathFullyQualified(targetPath) ? targetPath : Path.GetFullPath(Path.Combine(defaultWorkingDirectory, targetPath));

            if (String.IsNullOrWhiteSpace(artifactName))
            {
                throw new ArgumentException($"Artifact name can not be empty string");
            }

            if (Path.GetInvalidFileNameChars().Any(x => artifactName.Contains(x)))
            {
                throw new ArgumentException($"Artifact name is not valid: {artifactName}. It cannot contain '\\', '/', \"', ':', '<', '>', '|', '*', and '?'");
            }

            // Build ID
            string buildIdStr = context.Variables.GetValueOrDefault(SdkConstants.Variables.Build.BuildId)?.Value ?? string.Empty;
            if (!int.TryParse(buildIdStr, out int buildId))
            {
                throw new ArgumentException($"Run Id is not an Int32: {buildIdStr}");
            }

            string fullPath = Path.GetFullPath(targetPath);
            bool isFile = File.Exists(fullPath);
            bool isDir = Directory.Exists(fullPath);
            if (!isFile && !isDir)
            {
                // if local path is neither file nor folder
                throw new FileNotFoundException($"Path does not exist {targetPath}");
            }

            // Container ID
            string containerIdStr = context.Variables.GetValueOrDefault(SdkConstants.Variables.Build.ContainerId)?.Value ?? string.Empty;
            if (!long.TryParse(containerIdStr, out long containerId))
            {
                throw new ArgumentException($"Container Id is not an Int64: {containerIdStr}");
            }

            context.Output($"Uploading artifact '{artifactName}' from '{fullPath}' for run #{buildId}");

            FileContainerServer fileContainerHelper = new FileContainerServer(context.VssConnection, projectId: Guid.Empty, containerId, artifactName);
            var propertiesDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            long size = 0;

            try
            {
                size = await fileContainerHelper.CopyToContainerAsync(context, fullPath, token);

                propertiesDictionary.Add("artifactsize", size.ToString());

                context.Output($"Uploaded '{size}' bytes from '{fullPath}' to server");
            }
            // if any of the results were successful, make sure to attach them to the build
            finally
            {
                // Definition ID is a dummy value only used by HTTP client routing purposes
                int definitionId = 1;

                PipelinesServer pipelinesHelper = new PipelinesServer(context.VssConnection);

                var artifact = await pipelinesHelper.replacedociateActionsStorageArtifactAsync(
                    definitionId,
                    buildId,
                    containerId,
                    artifactName,
                    size,
                    token);

                context.Output($"replacedociated artifact {artifactName} ({artifact.ContainerId}) with run #{buildId}"); 
            }
        }

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

public long? GetLong(string name)
        {
            long val;
            if (long.TryParse(Get(name), out val))
            {
                return val;
            }

            return null;
        }

19 View Source File : MiniJson.cs
License : MIT License
Project Creator : AdamCarballo

object ParseNumber() {
				string number = NextWord;
				
				if (number.IndexOf('.') == -1) {
					long parsedInt;
					Int64.TryParse(number, out parsedInt);
					return parsedInt;
				}
				
				double parsedDouble;
				Double.TryParse(number, out parsedDouble);
				return parsedDouble;
			}

19 View Source File : BaseMessageHandler.cs
License : MIT License
Project Creator : AdemCatamak

private static T Convert(object payload)
        {
            object val = payload;
            try
            {
                Type typeT = typeof(T);
                if (typeT == typeof(short))
                {
                    if (short.TryParse(payload.ToString(), out short v))
                    {
                        val = v;
                    }
                }

                if (typeT == typeof(int))
                {
                    if (int.TryParse(payload.ToString(), out int v))
                    {
                        val = v;
                    }
                }

                if (typeT == typeof(long))
                {
                    if (long.TryParse(payload.ToString(), out long v))
                    {
                        val = v;
                    }
                }
            }
            catch
            {
                // ignore
            }

            if (val is not T t)
            {
                throw new ArgumentNotCompatibleException(payload.GetType().Name, nameof(T));
            }

            return t;
        }

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

protected static Condition GetSearchFilterConditionForAttribute(string attribute, string query, EnreplacedyMetadata enreplacedyMetadata)
		{
			var attributeMetadata = enreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attribute);

			if (attributeMetadata == null)
			{
				return null;
			}

			switch (attributeMetadata.AttributeType)
			{
				case AttributeTypeCode.String:
					return new Condition(attribute, ConditionOperator.Like, "{0}%".FormatWith(query));

				case AttributeTypeCode.Lookup:
				case AttributeTypeCode.Customer:
				case AttributeTypeCode.Picklist:
				case AttributeTypeCode.State:
				case AttributeTypeCode.Status:
				case AttributeTypeCode.Owner:
					return new Condition("{0}name".FormatWith(attribute), ConditionOperator.Like, "{0}%".FormatWith(query));

				case AttributeTypeCode.BigInt:
					long parsedLong;
					return long.TryParse(query, out parsedLong)
						? new Condition(attribute, ConditionOperator.Equal, parsedLong)
						: null;

				case AttributeTypeCode.Integer:
					int parsedInt;
					return int.TryParse(query, out parsedInt)
						? new Condition(attribute, ConditionOperator.Equal, parsedInt)
						: null;

				case AttributeTypeCode.Double:
					double parsedDouble;
					return double.TryParse(query, out parsedDouble)
						? new Condition(attribute, ConditionOperator.Equal, parsedDouble)
						: null;

				case AttributeTypeCode.Decimal:
				case AttributeTypeCode.Money:
					decimal parsedDecimal;
					return decimal.TryParse(query, out parsedDecimal)
						? new Condition(attribute, ConditionOperator.Equal, parsedDecimal)
						: null;

				case AttributeTypeCode.DateTime:
					DateTime parsedDate;
					return DateTime.TryParse(query, out parsedDate)
						? new Condition(attribute, ConditionOperator.On, parsedDate.ToString("yyyy-MM-dd"))
						: null;

				default:
					return null;
			}
		}

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

public ISharePointCollection GetFoldersAndFiles(EnreplacedyReference regarding, string sortExpression = DefaultSortExpression, int page = 1, int pageSize = DefaultPageSize, string pagingInfo = null, string folderPath = null)
		{
			var context = _dependencies.GetServiceContextForWrite();
			var website = _dependencies.GetWebsite();
			var enreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();
			var result = new SharePointResult(regarding, enreplacedyPermissionProvider, context);

			// replacedert permission to create the sharepointdoreplacedentlocation enreplacedy
			if (!result.PermissionsExist || !result.CanCreate || !result.CanAppend || !result.CanAppendTo)
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Enreplacedy Permissions to Create or Append doreplacedent locations or AppendTo the regarding enreplacedy.");
				return SharePointCollection.Empty(true);
			}

			var enreplacedyMetadata = context.GetEnreplacedyMetadata(regarding.LogicalName);
			var enreplacedy = context.CreateQuery(regarding.LogicalName).First(e => e.GetAttributeValue<Guid>(enreplacedyMetadata.PrimaryIdAttribute) == regarding.Id);

			var spConnection = new SharePointConnection(SharePointConnectionStringName);
			var spSite = context.GetSharePointSiteFromUrl(spConnection.Url);

			var location = GetDoreplacedentLocation(context, enreplacedy, enreplacedyMetadata, spSite);

			if (!enreplacedyPermissionProvider.Tryreplacedert(context, CrmEnreplacedyPermissionRight.Read, location))
			{
                ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Enreplacedy Permissions to Read doreplacedent locations.");
				return SharePointCollection.Empty(true);
			}

            ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Read SharePoint Doreplacedent Location Permission Granted.");

			var factory = new ClientFactory();

			using (var client = factory.CreateClientContext(spConnection))
			{
				// retrieve the SharePoint list and folder names for the doreplacedent location
				string listUrl, folderUrl;

				context.GetDoreplacedentLocationListAndFolder(location, out listUrl, out folderUrl);

				var sharePointFolder = client.AddOrGetExistingFolder(listUrl, folderUrl + folderPath);

				var list = client.GetListByUrl(listUrl);

				if (!sharePointFolder.IsPropertyAvailable("ServerRelativeUrl"))
				{
					client.Load(sharePointFolder, folder => folder.ServerRelativeUrl);
				}

				if (!sharePointFolder.IsPropertyAvailable("ItemCount"))
				{
					client.Load(sharePointFolder, folder => folder.ItemCount);
				}

				var camlQuery = new CamlQuery
				{
					FolderServerRelativeUrl = sharePointFolder.ServerRelativeUrl,
					ViewXml = @"
					<View>
						<Query>
							<OrderBy>
								<FieldRef {0}></FieldRef>
							</OrderBy>
							<Where></Where>
						</Query>
						<RowLimit>{1}</RowLimit>
					</View>".FormatWith(
							ConvertSortExpressionToCaml(sortExpression),
							pageSize)
				};
				if (page > 1)
				{
					camlQuery.LisreplacedemCollectionPosition = new LisreplacedemCollectionPosition { PagingInfo = pagingInfo };
				}
				var folderItems = list.Gereplacedems(camlQuery);
				client.Load(folderItems,
					items => items.LisreplacedemCollectionPosition,
					items => items.Include(
						item => item.ContentType,
						item => item["ID"],
						item => item["FileLeafRef"],
						item => item["Created"],
						item => item["Modified"],
						item => item["FileSizeDisplay"]));
				client.ExecuteQuery();

				var sharePoinreplacedems = new List<SharePoinreplacedem>();

				if (!string.IsNullOrEmpty(folderPath) && folderPath.Contains("/"))
				{
					var relativePaths = folderPath.Split('/');
					var parentFolderName = relativePaths.Length > 2 ? relativePaths.Skip(relativePaths.Length - 2).First() : "/";

					sharePoinreplacedems.Add(new SharePoinreplacedem()
					{
						Name = @"""{0}""".FormatWith(parentFolderName),
						IsFolder = true,
						FolderPath = folderPath.Substring(0, folderPath.LastIndexOf('/')),
						IsParent = true
					});
				}

				if (folderItems.Count < 1)
				{
					return new SharePointCollection(sharePoinreplacedems, null, sharePoinreplacedems.Count());
				}

				foreach (var item in folderItems)
				{
					var id = item["ID"] as int?;
					var name = item["FileLeafRef"] as string;
					var created = item["Created"] as DateTime?;
					var modified = item["Modified"] as DateTime?;

					long longFileSize;
					var fileSize = long.TryParse(item["FileSizeDisplay"] as string, out longFileSize) ? longFileSize : null as long?;

					if (string.Equals(item.ContentType.Name, "Folder", StringComparison.InvariantCultureIgnoreCase))
					{
						sharePoinreplacedems.Add(new SharePoinreplacedem
						{
							Id = id,
							Name = name,
							IsFolder = true,
							CreatedOn = created,
							ModifiedOn = modified,
							FolderPath = "{0}/{1}".FormatWith(folderPath, name)
						});
					}
					else
					{
						sharePoinreplacedems.Add(new SharePoinreplacedem
						{
							Id = id,
							Name = name,
							CreatedOn = created,
							ModifiedOn = modified,
							FileSize = fileSize,
							Url = GetAbsolutePath(website, location, name, folderPath)
						});
					}
				}

				var pageInfo = folderItems.LisreplacedemCollectionPosition != null
					? folderItems.LisreplacedemCollectionPosition.PagingInfo
					: null;

				return new SharePointCollection(sharePoinreplacedems, pageInfo, sharePointFolder.ItemCount);
			}
		}

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

public static void Farmer_doDivorce_Postfix(ref Farmer __instance, ref string __state)
        {
            try
            {
                int points = ModEntry.Config.PointsAfterDivorce;
                points -= ModEntry.heartsLost * 250;
                if (long.TryParse(__state,out long result))
                {
                    Friendship f = __instance.team.GetFriendship(__instance.uniqueMultiplayerID,result);
                    f.Points = Math.Max(0, points);
                    f.Status = points < 1000 ? FriendshipStatus.Divorced : FriendshipStatus.Friendly;

                }
                else
                {
                    __instance.friendshipData[__state].Points = Math.Max(0, points);
                    __instance.friendshipData[__state].Status = points < 1000 ? FriendshipStatus.Divorced : FriendshipStatus.Friendly;
                    Monitor.Log($"final points {__instance.friendshipData[__state].Points}");
                }

                ModEntry.heartsLost = 0;
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(Farmer_doDivorce_Postfix)}:\n{ex}", LogLevel.Error);
            }

        }

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

public long ReadLong()
        {
            int c = SafeReadByte();
            if (c == -1)
                throw CreateResponseError("No more data");

            var s = ReadLine();

            Log("R: {0}", s);

            if (c == '-')
                throw CreateResponseError(s.StartsWith("ERR") ? s.Substring(4) : s);

            if (c == ':' || c == '$') //really strange why ZRANK needs the '$' here
            {
                long i;
                if (long.TryParse(s, out i))
                    return i;
            }

            throw CreateResponseError("Unknown reply on integer response: " + c + s);
        }

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

public long ToLong(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                AddMessage(name, "值不能为空");
                Failed = true;
                return 0;
            }
            long vl;
            if (!long.TryParse(GetValue(name), out vl))
            {
                AddMessage(name, "值无法转为数字");
                Failed = true;
                return 0;
            }
            return vl;
        }

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

public long ToLong(string name, long def)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                return def;
            }
            long vl;
            if (!long.TryParse(GetValue(name), out vl))
            {
                AddMessage(name, "值无法转为数字");
                Failed = true;
                return 0;
            }
            return vl;
        }

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

public long? ToNullLong(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                return null;
            }
            long vl;
            if (!long.TryParse(GetValue(name), out vl))
            {
                AddMessage(name, "值无法转为数字");
                Failed = true;
                return null;
            }
            return vl;
        }

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

public long GetLong(string key, long def)
        {
            if (key == null)
            {
                return def;
            }
            var value = this[key];
            if (string.IsNullOrWhiteSpace(value))
            {
                return def;
            }
            return !long.TryParse(value, out var vl) ? def : vl;
        }

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

public static long GetAppSettingLong(string key, long def)
        {
            string value = ConfigurationManager.AppSettings[key];
            if (string.IsNullOrWhiteSpace(value))
            {
                return def;
            }
            long.TryParse(value, out def);
            return def;
        }

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

public long ToLong(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name)))
            {
                AddMessage(name, "值不能为空");
                Failed = true;
                return 0;
            }

            if (!long.TryParse(GetValue(name), out var vl))
            {
                AddMessage(name, "值无法转为数字");
                Failed = true;
                return 0;
            }

            return vl;
        }

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

public long ToLong(string name, long def)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name))) return def;
            if (!long.TryParse(GetValue(name), out var vl))
            {
                AddMessage(name, "值无法转为数字");
                Failed = true;
                return 0;
            }

            return vl;
        }

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

public long? ToNullLong(string name)
        {
            if (string.IsNullOrWhiteSpace(GetValue(name))) return null;
            if (!long.TryParse(GetValue(name), out var vl))
            {
                AddMessage(name, "值无法转为数字");
                Failed = true;
                return null;
            }

            return vl;
        }

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

public ApiResult Pause(string id)
        {
            if (!long.TryParse(id, out var pid) || !Plans.TryGetValue(pid, out var plan))
                return ApiResult.Error(ErrorCode.LogicalError, "参数错误");
            var result = CallCommand("pause", $"msg:{plan.station}:{plan.plan_id:x}");
            if (result.State != ZeroOperatorStateType.Ok)
            {
                return ApiResult.Error(ErrorCode.LogicalError, "参数错误");
            }
            return ApiResult.Succees();
        }

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

public ApiResult Reset(string id)
        {
            if (!long.TryParse(id, out var pid) || !Plans.TryGetValue(pid, out var plan))
                return ApiResult.Error(ErrorCode.LogicalError, "参数错误");
            var result = CallCommand("reset", $"msg:{plan.station}:{plan.plan_id:x}");
            if (result.State != ZeroOperatorStateType.Ok)
            {
                return ApiResult.Error(ErrorCode.LogicalError, "参数错误");
            }
            return ApiResult.Succees();
        }

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

public ApiResult Close(string id)
        {
            if (!long.TryParse(id, out var pid) || !Plans.TryGetValue(pid, out var plan))
                return ApiResult.Error(ErrorCode.LogicalError, "参数错误");
            var result = CallCommand("close", $"msg:{plan.station}:{plan.plan_id:x}");
            if (result.State != ZeroOperatorStateType.Ok)
            {
                return ApiResult.Error(ErrorCode.LogicalError, "参数错误");
            }
            return ApiResult.Succees();
        }

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

public ApiResult Remove(string id)
        {
            if (!long.TryParse(id, out var pid) || !Plans.TryGetValue(pid, out var plan))
                return ApiResult.Error(ErrorCode.LogicalError, "参数错误");
            var result = CallCommand("remove", $"msg:{plan.station}:{plan.plan_id:x}");
            if (result.State != ZeroOperatorStateType.Ok)
            {
                return ApiResult.Error(ErrorCode.LogicalError, "参数错误");
            }
            return ApiResult.Succees();
        }

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

protected long GetLongArg(string name, long def = -1)
        {
            var value = GetArgValue(name);
            if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null")
            {
                return def;
            }
            return long.TryParse(value, out var num) ? num : def;
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private long VersionNum(string data)
        {
            string[] separate = data.Split(new char[] { '.' }, 4);
            separate[1] = separate[1].PadLeft(4, '0');
            separate[2] = separate[2].PadLeft(4, '0');

            if (separate.Length == 4)
                separate[3] = separate[3].PadLeft(4, '0');
            else
                separate[2] = separate[2].PadRight(8, '0');

            long result;
            long.TryParse(separate[0] + separate[1] + separate[2] + (separate.Length == 4 ? separate[3] : ""), out result);

            return result;
        }

19 View Source File : MainForm.cs
License : GNU General Public License v3.0
Project Creator : AgentRev

private long VersionNum(string data)
        {
            string[] separate = data.Split(new char[] { '.' }, 4);
            separate[1] = separate[1].PadLeft(4, '0');
            separate[2] = separate[2].PadLeft(4, '0');
            if (separate.Length == 4) separate[3] = separate[3].PadLeft(4, '0');
            else separate[2] = separate[2].PadRight(8, '0');

            long result;
            long.TryParse(separate[0] + separate[1] + separate[2] + (separate.Length == 4 ? separate[3] : ""), out result);

            return result;
        }

19 View Source File : NumericValidationRule.cs
License : Apache License 2.0
Project Creator : AKruimink

public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var strValue = Convert.ToString(value);

            if (string.IsNullOrEmpty(strValue))
            {
                if (AllowNull)
                {
                    return new ValidationResult(true, null);
                }
                return new ValidationResult(false, $"Value cannot be converted to string");
            }

            var canConvert = (ValidationType?.Name) switch
            {
                nameof(Boolean) => bool.TryParse(strValue, out var boolValue),
                nameof(Double) => double.TryParse(strValue, out var doubleValue),
                nameof(Int32) => int.TryParse(strValue, out var intValue),
                nameof(Int64) => long.TryParse(strValue, out var longValue),
                _ => throw new InvalidCastException($"{ValidationType?.Name} is not a supported type"),
            };

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

private static bool CheckIDCard18(string id)
        {
            if (!long.TryParse(id.Remove(17), out var n) || n < Math.Pow(10, 16) || !long.TryParse(id.Replace('x', '0').Replace('X', '0'), out _))
            {
                return false;//数字验证
            }

            if (AddressCode.IndexOf(id.Remove(2)) == -1)
            {
                return false;//省份验证

            }
            var birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            if (!DateTime.TryParse(birth, out _))
            {
                return false;//生日验证
            }

            var varifyCodes = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            var wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            var ai = id.Remove(17).ToCharArray();
            var sum = 0;
            for (var i = 0; i < 17; i++)
            {
                sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
            }

            Math.DivRem(sum, 11, out int y);
            if (varifyCodes[y] != id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }

            return true;//符合GB11643-1999标准
        }

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

private static bool CheckIDCard15(string id)
        {
            if (!long.TryParse(id, out var n) || n < Math.Pow(10, 14))
            {
                return false;//数字验证
            }

            if (AddressCode.IndexOf(id.Remove(2)) == -1)
            {
                return false;//省份验证
            }

            var birth = id.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            if (!DateTime.TryParse(birth, out var _))
            {
                return false;//生日验证
            }

            return true;//符合15位身份证标准
        }

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

static object TryParseGraphAttr(string s)
		{
			object value = null;
			int vi;
			long vl;
			float vf;
			double vd;
			bool vb;

			if (int.TryParse(s, out vi))
				value = vi;
			else if (long.TryParse(s, out vl))
				value = vl;
			else if (float.TryParse(s, out vf))
				value = vf;
			else if (double.TryParse(s, out vd))
				value = vd;
			else if (bool.TryParse(s, out vb))
				value = vb;
			
			return value;
		}

19 View Source File : Response.cs
License : MIT License
Project Creator : alen-smajic

public static Response FromWebResponse(IAsyncRequest request, HttpWebResponse apiResponse, Exception apiEx) {

			Response response = new Response();
			response.Request = request;

			if (null != apiEx) {
				response.AddException(apiEx);
			}

			// timeout: API response is null
			if (null == apiResponse) {
				response.AddException(new Exception("No Reponse."));
			} else {
				// https://www.mapbox.com/api-doreplacedentation/#rate-limit-headers
				if (null != apiResponse.Headers) {
					response.Headers = new Dictionary<string, string>();
					for (int i = 0; i < apiResponse.Headers.Count; i++) {
						// TODO: implement .Net Core / UWP implementation
						string key = apiResponse.Headers.Keys[i];
						string val = apiResponse.Headers[i];
						response.Headers.Add(key, val);
						if (key.Equals("X-Rate-Limit-Interval", StringComparison.InvariantCultureIgnoreCase)) {
							int limitInterval;
							if (int.TryParse(val, out limitInterval)) { response.XRateLimitInterval = limitInterval; }
						} else if (key.Equals("X-Rate-Limit-Limit", StringComparison.InvariantCultureIgnoreCase)) {
							long limitLimit;
							if (long.TryParse(val, out limitLimit)) { response.XRateLimitLimit = limitLimit; }
						} else if (key.Equals("X-Rate-Limit-Reset", StringComparison.InvariantCultureIgnoreCase)) {
							double unixTimestamp;
							if (double.TryParse(val, out unixTimestamp)) {
								response.XRateLimitReset = UnixTimestampUtils.From(unixTimestamp);
							}
						} else if (key.Equals("Content-Type", StringComparison.InvariantCultureIgnoreCase)) {
							response.ContentType = val;
						}
					}
				}

				if (apiResponse.StatusCode != HttpStatusCode.OK) {
					response.AddException(new Exception(string.Format("{0}: {1}", apiResponse.StatusCode, apiResponse.StatusDescription)));
				}
				int statusCode = (int)apiResponse.StatusCode;
				response.StatusCode = statusCode;
				if (429 == statusCode) {
					response.AddException(new Exception("Rate limit hit"));
				}

				if (null != apiResponse) {
					using (Stream responseStream = apiResponse.GetResponseStream()) {
						byte[] buffer = new byte[0x1000];
						int bytesRead;
						using (MemoryStream ms = new MemoryStream()) {
							while (0 != (bytesRead = responseStream.Read(buffer, 0, buffer.Length))) {
								ms.Write(buffer, 0, bytesRead);
							}
							response.Data = ms.ToArray();
						}
					}
					apiResponse.Close();
				}
			}

			return response;
		}

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

private static string BytesToString(string byteCount)
        {
            if (long.TryParse(byteCount, out var bytes))
            {
                return BytesToString(bytes);
            }
            else
            {
                return string.Empty;
            }
        }

19 View Source File : AppUserService.cs
License : MIT License
Project Creator : alexyakunin

private async Task<string> NormalizeName(AppDbContext dbContext, string name, long userId, CancellationToken cancellationToken = default)
        {
            // Normalizing name
            var sb = StringBuilderEx.Acquire();
            foreach (var c in name) {
                if (char.IsLetterOrDigit(c) || c == '_' || c == '-')
                    sb.Append(c);
                else if (sb.Length == 0 || char.IsLetterOrDigit(sb[^1]))
                    sb.Append('_');
            }
            name = sb.ToStringAndRelease();
            if (name.Length < 4 || !char.IsLetter(name[0]))
                name = "user-" + name;

            // Finding the number @ the tail
            var numberStartIndex = name.Length;
            for (; numberStartIndex >= 1; numberStartIndex--) {
                if (!char.IsNumber(name[numberStartIndex - 1]))
                    break;
            }

            // Iterating through these tail numbers to get the unique user name
            var namePrefix = name.Substring(0, numberStartIndex);
            var nameSuffix = name.Substring(numberStartIndex);
            var nextNumber = long.TryParse(nameSuffix, out var number) ? number + 1 : 1;
            while (true) {
                var isNameUsed = await dbContext.Users.AsQueryable()
                    .AnyAsync(u => u.Name == name && u.Id != userId, cancellationToken);
                if (!isNameUsed)
                    break;
                name = namePrefix + nextNumber++;
            }
            return name;
        }

19 View Source File : MessageParser.cs
License : MIT License
Project Creator : alexyakunin

public virtual async Task<GameMessage> Parse(string text, CancellationToken cancellationToken = default)
        {
            List<MessageFragment> fragments = new();
            var startIndex = 0;

            void AddPlainText(int length) {
                if (length < 0)
                    startIndex -= length;
                fragments.Add(new PlainText(text.Substring(startIndex, length)));
                startIndex += length;
            }

            bool StartsWith(string start) => text.replacedpan(startIndex).StartsWith(start);

            bool TryParseDirective(string directive, out string value) {
                value = "";
                if (!StartsWith(directive))
                    return false;
                if (startIndex + directive.Length + 2 >= text.Length || text[startIndex + directive.Length] != '[') {
                    AddPlainText(directive.Length);
                    return false;
                }
                var valueStartIndex = startIndex + directive.Length + 1;
                var rightBracketIndex = text.IndexOf(']', valueStartIndex);
                if (rightBracketIndex < 0) {
                    AddPlainText(directive.Length);
                    return false;
                }
                value = text.Substring(valueStartIndex, rightBracketIndex - valueStartIndex);
                startIndex = rightBracketIndex + 1;
                return true;
            }

            while (startIndex < text.Length) {
                if (text[startIndex] != '@') {
                    var endIndex = text.IndexOf('@', startIndex);
                    if (endIndex < 0)
                        endIndex = text.Length;
                    AddPlainText(endIndex - startIndex);
                    continue;
                }
                if (StartsWith("@@")) {
                    fragments.Add(new PlainText("@"));
                    startIndex += 2;
                    continue;
                }

                var directiveStartIndex = startIndex;
                if (TryParseDirective("@user", out var userIdText)) {
                    if (!long.TryParse(userIdText, out var userId)) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    var user = await AppUsers.TryGet(userId, cancellationToken);
                    if (user == null) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    fragments.Add(new UserMention(user));
                    continue;
                }
                if (TryParseDirective("@score", out var scoreText)) {
                    var scoreParts = scoreText.Split(",");
                    if (scoreParts.Length != 2) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    var gameId = scoreParts[0].Trim();
                    if (string.IsNullOrEmpty(gameId)) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    if (!long.TryParse(scoreParts[1].Trim(), out var score)) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    var game = await Games.TryGet(gameId, cancellationToken);
                    if (game == null) {
                        AddPlainText(directiveStartIndex - startIndex);
                        continue;
                    }
                    fragments.Add(new GameScoreMention(game, score));
                    continue;
                }
                if (StartsWith("@")) {
                    var name = UserNameService.ParseName(text, startIndex + 1);
                    if (string.IsNullOrEmpty(name)) {
                        AddPlainText(1);
                        continue;
                    }
                    var user = await AppUsers.TryGetByName(name, cancellationToken);
                    if (user == null) {
                        AddPlainText(name.Length + 1);
                        continue;
                    }
                    fragments.Add(new UserMention(user));
                    startIndex += name.Length + 1;
                    continue;
                }
            }

            List<MessageFragment> optimizedFragments = new();
            MessageFragment? lastFragment = null;
            foreach (var fragment in fragments) {
                if (fragment is PlainText pt && lastFragment is PlainText lpt) {
                    lastFragment = new PlainText(lpt.Text + pt.Text);
                    optimizedFragments.RemoveAt(optimizedFragments.Count - 1);
                }
                else
                    lastFragment = fragment;
                optimizedFragments.Add(lastFragment);
            }

            return new GameMessage() {
                Text = text,
                Fragments = optimizedFragments.ToImmutableList()
            };
        }

19 View Source File : VMMap.cs
License : GNU Lesser General Public License v3.0
Project Creator : Alois-xx

internal void MapDataFromLine(VMMapData lret, string line)
        {
            string[] parts = SplitLine(line);
            if (parts.Length >= 11)
            {
                string name = parts[0];
                if (RowMapper.TryGetValue(parts[0], out Action<long, long, long, VMMapData> mapper))
                {
                    if( parts[1] == "") // Page table data can sometimes be empty
                    {
                        return;
                    }
                    long reserved = long.Parse(parts[1]);
                    long.TryParse(parts[2], out long committed);
                    long.TryParse(parts[10], out long largestBlock);
                    mapper(reserved, committed, largestBlock, lret);
                }
            }
        }

19 View Source File : ObjectExtensions.cs
License : MIT License
Project Creator : alonsoalon

public static long ToLong(this object s)
        {
            if (s == null || s == DBNull.Value)
                return 0L;

            long.TryParse(s.ToString(), out long result);
            return result;
        }

19 View Source File : StringExtension.cs
License : MIT License
Project Creator : AlphaYu

public static long? ToLong(this string @this)
        {
            bool status = long.TryParse(@this, out long result);

            if (status)
                return result;
            else
                return null;
        }

19 View Source File : LongConvert.cs
License : MIT License
Project Creator : amolines

protected override long ToConvert(string value)
        {
            if (!long.TryParse(value,out   var result))
            {
                throw new InvalidCastConvertException(value, typeof(long));
            }
            return result;
        }

19 View Source File : CheckForUpdates.cs
License : Apache License 2.0
Project Creator : AmpScm

public static void MaybePerformUpdateCheck(IAnkhServiceProvider context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (_checkedOnce)
                return;

            _checkedOnce = true;

            IAnkhConfigurationService config = context.GetService<IAnkhConfigurationService>();
            using (RegistryKey rk = config.OpenUserInstanceKey("UpdateCheck"))
            {
                int interval = 24 * 6; // 6 days
                object value = rk.GetValue("Interval");

                if (value is int)
                {
                    interval = (int)value;

                    if (interval <= 0)
                        return;
                }

                TimeSpan ts = TimeSpan.FromHours(interval);

                value = rk.GetValue("LastVersion");

                if (IsDevVersion() || (value is string && (string)value == GetCurrentVersion(context).ToString()))
                {
                    value = rk.GetValue("LastCheck");
                    long lv;
                    if (value is string && long.TryParse((string)value, out lv))
                    {
                        DateTime lc = new DateTime(lv, DateTimeKind.Utc);

                        if ((lc + ts) > DateTime.UtcNow)
                            return;

                        // TODO: Check the number of fails to increase the check interval
                    }
                }
            }

            context.GetService<IAnkhScheduler>().Schedule(new TimeSpan(0, 0, 20), AnkhCommand.CheckForUpdates);
        }

19 View Source File : AnkhIssueService.cs
License : Apache License 2.0
Project Creator : AmpScm

public void OpenRevision(string revisionText)
        {
            if (string.IsNullOrEmpty(revisionText))
                throw new ArgumentNullException("revisionText");

            long rev;

            IssueRepository repository = CurrentIssueRepository;
            if (repository != null
                && repository.CanNavigateToRevision
                && long.TryParse(revisionText, out rev))
            {
                try
                {
                    repository.NavigateToRevision(rev);
                    return;
                }
                catch { } // connector code
            }

            IAnkhWebBrowser web = GetService<IAnkhWebBrowser>();
            if (web != null)
            {
                Uri uri = CommitSettings.GetRevisionUri(revisionText);
                if (uri != null && !uri.IsFile && !uri.IsUnc)
                    web.Navigate(uri);
            }
        }

19 View Source File : ExternalsPropertyEditor.cs
License : Apache License 2.0
Project Creator : AmpScm

private void externalGrid_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
        {
            DataGridViewRow r = externalGrid.Rows[e.RowIndex];
            string url = r.Cells[0].Value as string;
            string target = r.Cells[4].Value as string;
            string rev = r.Cells[2].Value as string;

            if (r.IsNewRow &&
                string.IsNullOrEmpty(url) &&
                string.IsNullOrEmpty(target) &&
                string.IsNullOrEmpty(rev))
                return;

            long v = 0;
            if (string.IsNullOrEmpty(url))
            {
                e.Cancel = true;
                MessageBox.Show(this, "Url is not set", "Property Editor", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else if (string.IsNullOrEmpty(target))
            {
                e.Cancel = true;
                MessageBox.Show(this, "Target is not set", "Property Editor", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            }
            else if (!string.IsNullOrEmpty(rev) && !long.TryParse(rev, out v))
            {
                e.Cancel = true;
                MessageBox.Show(this, "Revision is not valid", "Property Editor", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

            if (e.Cancel)
                return;

            SvnExternalItem ei;
            if (!TryCreateItemFromRow(r, out ei))
            {
                e.Cancel = true;
                MessageBox.Show(this, "External definition generates invalid definition", "Property Editor", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            r.Tag = ei;
        }

19 View Source File : PwnedPasswordsClient.cs
License : MIT License
Project Creator : andrewlock

internal static async Task<long> Contains(HttpContent content, string sha1Suffix)
        {
            using (var streamReader = new StreamReader(await content.ReadreplacedtreamAsync()))
            {
                while (!streamReader.EndOfStream)
                {
                    var line = await streamReader.ReadLineAsync();
                    var segments = line.Split(':');
                    if (segments.Length == 2
                        && string.Equals(segments[0], sha1Suffix, StringComparison.OrdinalIgnoreCase)
                        && long.TryParse(segments[1], out var count))
                    {
                        return count;
                    }
                }
            }

            return 0;

        }

19 View Source File : HttpListenerRequest.cs
License : MIT License
Project Creator : andruzzzhka

internal void AddHeader (string headerField)
    {
      var start = headerField[0];
      if (start == ' ' || start == '\t') {
        _context.ErrorMessage = "Invalid header field";
        return;
      }

      var colon = headerField.IndexOf (':');
      if (colon < 1) {
        _context.ErrorMessage = "Invalid header field";
        return;
      }

      var name = headerField.Substring (0, colon).Trim ();
      if (name.Length == 0 || !name.IsToken ()) {
        _context.ErrorMessage = "Invalid header name";
        return;
      }

      var val = colon < headerField.Length - 1
                ? headerField.Substring (colon + 1).Trim ()
                : String.Empty;

      _headers.InternalSet (name, val, false);

      var lower = name.ToLower (CultureInfo.InvariantCulture);
      if (lower == "host") {
        if (_userHostName != null) {
          _context.ErrorMessage = "Invalid Host header";
          return;
        }

        if (val.Length == 0) {
          _context.ErrorMessage = "Invalid Host header";
          return;
        }

        _userHostName = val;
        return;
      }

      if (lower == "content-length") {
        if (_contentLength > -1) {
          _context.ErrorMessage = "Invalid Content-Length header";
          return;
        }

        long len;
        if (!Int64.TryParse (val, out len)) {
          _context.ErrorMessage = "Invalid Content-Length header";
          return;
        }

        if (len < 0) {
          _context.ErrorMessage = "Invalid Content-Length header";
          return;
        }

        _contentLength = len;
        return;
      }
    }

See More Examples