int.TryParse(string, out int)

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

5492 Examples 7

19 View Source File : BotMainWindow.xaml.cs
License : GNU General Public License v3.0
Project Creator : 00000vish

private void idle1_Click(object sender, RoutedEventArgs e)
        {
            if (listView1.SelectedItem != null)
            {
                ListViewItem item = new ListViewItem();
                item = (ListViewItem)listView1.SelectedItem;
                int temp;
                int.TryParse(item.Tag.ToString(), out temp);
                SteamBotController.playGame(temp);
            }
        }

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 : RCEPControl.cs
License : MIT License
Project Creator : 0x0ade

[RCEndpoint(true, "/userinfos", "?from={first}&count={count}", "?from=0&count=100", "User Infos", "Get some basic information about ALL users.")]
        public static void UserInfos(Frontend f, HttpRequestEventArgs c) {
            using UserDataBatchContext ctx = f.Server.UserData.OpenBatch();

            string[] uids = f.Server.UserData.GetAll();

            NameValueCollection args = f.ParseQueryString(c.Request.RawUrl);
            if (!int.TryParse(args["from"], out int from) || from <= 0)
                from = 0;
            if (!int.TryParse(args["count"], out int count) || count <= 0)
                count = 100;
            if (from + count > uids.Length)
                count = uids.Length - from;

            f.RespondJSON(c, uids.Skip(from).Take(count).Select(uid => {
                BasicUserInfo info = f.Server.UserData.Load<BasicUserInfo>(uid);
                BanInfo ban = f.Server.UserData.Load<BanInfo>(uid);
                KickHistory kicks = f.Server.UserData.Load<KickHistory>(uid);
                return new {
                    UID = uid,
                    info.Name,
                    info.Discrim,
                    info.Tags,
                    Key = f.Server.UserData.GetKey(uid),
                    Ban = ban.Reason.IsNullOrEmpty() ? null : new {
                        ban.Name,
                        ban.Reason,
                        From = ban.From?.ToUnixTime() ?? 0,
                        To = ban.To?.ToUnixTime() ?? 0
                    },
                    Kicks = kicks.Log.Select(e => new {
                        e.Reason,
                        From = e.From?.ToUnixTime() ?? 0
                    }).ToArray()
                };
            }).ToArray());
        }

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

[RCEndpoint(false, "/chatlog", "?count={count}&detailed={true|false}", "?count=20&detailed=false", "Chat Log", "Basic chat log.")]
        public static void ChatLog(Frontend f, HttpRequestEventArgs c) {
            bool auth = f.IsAuthorized(c);
            NameValueCollection args = f.ParseQueryString(c.Request.RawUrl);

            if (!int.TryParse(args["count"], out int count) || count <= 0)
                count = 20;
            if (!auth && count > 100)
                count = 100;

            if (!bool.TryParse(args["detailed"], out bool detailed))
                detailed = false;

            ChatModule chat = f.Server.Get<ChatModule>();
            List<object> log = new();
            RingBuffer<DataChat?> buffer = chat.ChatBuffer;
            lock (buffer) {
                for (int i = Math.Max(-buffer.Moved, -count); i < 0; i++) {
                    DataChat? msg = buffer[i];
                    if (msg != null && (msg.Target == null || auth))
                        log.Add(detailed ? msg.ToDetailedFrontendChat() : msg.ToFrontendChat());
                }
            }

            f.RespondJSON(c, log);
        }

19 View Source File : PacketDeviceSelector.cs
License : MIT License
Project Creator : 0blu

public static ICaptureDevice AskForPacketDevice()
        {
            // Retrieve the device list from the local machine
            CaptureDeviceList devices = CaptureDeviceList.Instance;

            if (devices.Count == 0)
            {
                throw new Exception("No interfaces found! Make sure WinPcap is installed.");
            }

            // Print the list
            for (int i = 0; i != devices.Count; ++i)
            {
                ICaptureDevice device = devices[i];
                Console.Write((i + 1) + ". ");
                if (device.Description != null)
                    Console.WriteLine(" (" + device.Description + ")");
                else
                    Console.WriteLine(" (No description available)");
            }

            int deviceIndex;
            do
            {
                Console.WriteLine("Enter the interface number (1-" + devices.Count + "):");
                string deviceIndexString = Console.ReadLine();
                if (!int.TryParse(deviceIndexString, out deviceIndex) ||
                    deviceIndex < 1 || deviceIndex > devices.Count)
                {
                    deviceIndex = 0;
                }
            } while (deviceIndex == 0);

            return devices[deviceIndex - 1];
        }

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

public static MTexture GetIcon(string emote, float time) {
            Atlas atlas;
            if ((atlas = GetIconAtlas(ref emote)) == null)
                return null;

            List<string> iconPaths = new(emote.Split(' '));
            if (iconPaths.Count > 1 && int.TryParse(iconPaths[0], out int fps)) {
                iconPaths.RemoveAt(0);
            } else {
                fps = 7; // Default FPS.
            }

            List<MTexture> icons = iconPaths.SelectMany(iconPath => {
                iconPath = iconPath.Trim();
                List<MTexture> subs = atlas.orig_GetAtlreplacedubtextures(iconPath);
                if (subs.Count != 0)
                    return subs;
                if (atlas.Has(iconPath))
                    return new List<MTexture>() { atlas[iconPath] };
                if (iconPath.ToLowerInvariant() == "end")
                    return new List<MTexture>() { null };
                return new List<MTexture>();
            }).ToList();

            if (icons.Count == 0)
                return null;

            if (icons.Count == 1)
                return icons[0];

            int index = (int) Math.Floor(time * fps);

            if (index >= icons.Count - 1 && icons[icons.Count - 1] == null)
                return icons[icons.Count - 2];

            return icons[index % icons.Count];
        }

19 View Source File : XnaToFnaHelper.cs
License : zlib License
Project Creator : 0x0ade

public static void Initialize(XnaToFnaGame game) {
            Game = game;

            TextInputEXT.TextInput += KeyboardEvents.CharEntered;

            game.Window.ClientSizeChanged += SDLWindowSizeChanged;

            string maximumGamepadCountStr = Environment.GetEnvironmentVariable(
                "FNA_GAMEPAD_NUM_GAMEPADS"
            );
            if (string.IsNullOrEmpty(maximumGamepadCountStr) ||
                !int.TryParse(maximumGamepadCountStr, out MaximumGamepadCount) ||
                MaximumGamepadCount < 0) {
                MaximumGamepadCount = Enum.GetNames(typeof(PlayerIndex)).Length;
            }
            DeviceEvents.IsGamepadConnected = new bool[MaximumGamepadCount];

            PlatformHook("ApplyWindowChanges");
        }

19 View Source File : XnaToFnaHelper.cs
License : zlib License
Project Creator : 0x0ade

public static void ApplyChanges(GraphicsDeviceManager self) {
            string forceFullscreen = Environment.GetEnvironmentVariable("XNATOFNA_DISPLAY_FULLSCREEN");
            if (forceFullscreen == "0")
                self.IsFullScreen = false;
            else if (forceFullscreen == "1")
                self.IsFullScreen = true;

            int forceWidth;
            if (int.TryParse(Environment.GetEnvironmentVariable("XNATOFNA_DISPLAY_WIDTH") ?? "", out forceWidth))
                self.PreferredBackBufferWidth = forceWidth;
            int forceHeight;
            if (int.TryParse(Environment.GetEnvironmentVariable("XNATOFNA_DISPLAY_HEIGHT") ?? "", out forceHeight))
                self.PreferredBackBufferHeight = forceHeight;
            string[] forceSize = (Environment.GetEnvironmentVariable("XNATOFNA_DISPLAY_SIZE") ?? "").Split('x');
            if (forceSize.Length == 2) {
                if (int.TryParse(forceSize[0], out forceWidth))
                    self.PreferredBackBufferWidth = forceWidth;
                if (int.TryParse(forceSize[1], out forceHeight))
                    self.PreferredBackBufferHeight = forceHeight;
            }

            self.ApplyChanges();
        }

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

public static MaybeEx<int> TryParse(string argStr)
            => int.TryParse(argStr, out var result)
                ? result
                : MaybeEx<int>.Nothing();

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

public static Maybe<int> TryParse(string argStr)
            => int.TryParse(argStr, out var result)
                ? result
                : Maybe<int>.Nothing();

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

public IEnumerable<XmlElement>? EnumerateList(XmlElement node, string propertyName)
        {
            var result = this.FindElement(node, propertyName);
            if (result != null)
            {
                List<IndexXElement> buffer = new List<IndexXElement>();
                foreach (var childNode in result.ChildNodes)
                {
                    if (childNode is XmlElement childElement)
                    {
                        string indexStr = childElement.Name.Substring(propertyName.Length);
                        if (int.TryParse(indexStr, out var index))
                        {
                            buffer.Add(new IndexXElement(index, childElement));
                        }
                    }
                }

                if (buffer.Count == 0)
                {
                    return null;
                }

                buffer.Sort((x,y)=> x.Index - y.Index);
                return buffer.SelectToReadOnlyList(i => i.Element);
            }
            return null;
        }

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

public static int ToInt(this object s, bool round = false)
    {
        if (s == null || s == DBNull.Value)
            return 0;

        if (s is bool b)
            return b ? 1 : 0;

        if (int.TryParse(s.ToString(), out int result))
            return result;

        if (s.GetType().IsEnum)
        {
            return (int)s;
        }

        var f = s.ToFloat();
        return round ? Convert.ToInt32(f) : (int)f;
    }

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

private static int StringToInt(string number)
        {
            return int.TryParse(number, out var x) ? x : 0;
        }

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

internal void SetHost(string host)
        {
            if (string.IsNullOrEmpty(host?.Trim())) {
                _ip = "127.0.0.1";
                _port = 6379;
                return;
            }
            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
            {
                _ip = ipv6.Groups[1].Value.Trim();
                _port = int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379;
                return;
            }
            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
            {
                _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                _port = 6379;
                return;
            }
            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                {
                    _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                    _port = testPort2;
                    return;
                }
                _ip = host;
                _port = 6379;
                return;
            }
            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
            {
                _ip = host;
                _port = 6379;
                return;
            }
            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    _ip = testHost;
                    _port = 6379;
                    return;
                }
            }
            _ip = host;
            _port = 6379;
        }

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

public static KeyValuePair<string, int> SplitHost(string host)
        {
            if (string.IsNullOrWhiteSpace(host?.Trim()))
                return new KeyValuePair<string, int>("127.0.0.1", 6379);

            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
                return new KeyValuePair<string, int>(ipv6.Groups[1].Value.Trim(), 
                    int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379);

            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
                return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", 6379);

            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                    return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", testPort2);

                return new KeyValuePair<string, int>(host, 6379);
            }

            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
                return new KeyValuePair<string, int>(host, 6379);

            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                    return new KeyValuePair<string, int>(testHost, 6379);
            }

            return new KeyValuePair<string, int>(host, 6379);
        }

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 : ShareHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private static VmessItem ResolveStdVmess(string result)
        {
            VmessItem i = new VmessItem
            {
                configType = (int)EConfigType.Vmess,
                security = "auto"
            };

            Uri u = new Uri(result);

            i.address = u.IdnHost;
            i.port = u.Port;
            i.remarks = u.GetComponents(UriComponents.Fragment, UriFormat.Unescaped);
            var q = HttpUtility.ParseQueryString(u.Query);

            var m = StdVmessUserInfo.Match(u.UserInfo);
            if (!m.Success) return null;

            i.id = m.Groups["id"].Value;
            if (!int.TryParse(m.Groups["alterId"].Value, out int aid))
            {
                return null;
            }
            i.alterId = aid;

            if (m.Groups["streamSecurity"].Success)
            {
                i.streamSecurity = m.Groups["streamSecurity"].Value;
            }
            switch (i.streamSecurity)
            {
                case "tls":
                    // TODO tls config
                    break;
                default:
                    if (!string.IsNullOrWhiteSpace(i.streamSecurity))
                        return null;
                    break;
            }

            i.network = m.Groups["network"].Value;
            switch (i.network)
            {
                case "tcp":
                    string t1 = q["type"] ?? "none";
                    i.headerType = t1;
                    // TODO http option

                    break;
                case "kcp":
                    i.headerType = q["type"] ?? "none";
                    // TODO kcp seed
                    break;

                case "ws":
                    string p1 = q["path"] ?? "/";
                    string h1 = q["host"] ?? "";
                    i.requestHost = Utils.UrlDecode(h1);
                    i.path = p1;
                    break;

                case "http":
                case "h2":
                    i.network = "h2";
                    string p2 = q["path"] ?? "/";
                    string h2 = q["host"] ?? "";
                    i.requestHost = Utils.UrlDecode(h2);
                    i.path = p2;
                    break;

                case "quic":
                    string s = q["security"] ?? "none";
                    string k = q["key"] ?? "";
                    string t3 = q["type"] ?? "none";
                    i.headerType = t3;
                    i.requestHost = Utils.UrlDecode(s);
                    i.path = k;
                    break;

                default:
                    return null;
            }

            return i;
        }

19 View Source File : Machine.cs
License : MIT License
Project Creator : 3RD-Dimension

private void ParseStartup(string line)
        {     // TODO Kinda Successfull, still need to find a way to ask for it just after recieving OK message on Connection
            Match m = StartupRegex.Match(line);

            int major, minor;
            char rev;

            if (!m.Success ||
                !int.TryParse(m.Groups[1].Value, out major) ||
                !int.TryParse(m.Groups[2].Value, out minor) ||
                !char.TryParse(m.Groups[3].Value, out rev))
            {
                RaiseEvent(Info, "Could not read GRBL Version.");
                return;
            }
            // TODO Display current GRBL version in the Connection or About box
            Version v = new Version(major, minor, (int)rev);
            GRBL_Version = v.ToString();
            Console.WriteLine("GRBL Version is " + GRBL_Version);
            if (v < Constants.MinimumGrblVersion)
            {
                ReportError("Outdated version of grbl detected!");
                ReportError($"Please upgrade to at least grbl v{Constants.MinimumGrblVersion.Major}.{Constants.MinimumGrblVersion.Minor}{(char)Constants.MinimumGrblVersion.Build}");
            }

        }

19 View Source File : EventSourceReader.cs
License : MIT License
Project Creator : 3ventic

private async Task ReaderAsync()
        {
            try
            {
                if (string.Empty != LastEventId)
                {
                    if (Hc.DefaultRequestHeaders.Contains("Last-Event-Id"))
                    {
                        Hc.DefaultRequestHeaders.Remove("Last-Event-Id");
                    }
                    
                    Hc.DefaultRequestHeaders.TryAddWithoutValidation("Last-Event-Id", LastEventId);
                }
                using (HttpResponseMessage response = await Hc.GetAsync(Uri, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();
                    if (response.Headers.TryGetValues("content-type", out IEnumerable<string> ctypes) || ctypes?.Contains("text/event-stream") == false)
                    {
                        throw new ArgumentException("Specified URI does not return server-sent events");
                    }

                    Stream = await response.Content.ReadreplacedtreamAsync();
                    using (var sr = new StreamReader(Stream))
                    {
                        string evt = DefaultEventType;
                        string id = string.Empty;
                        var data = new StringBuilder(string.Empty);

                        while (true)
                        {
                            string line = await sr.ReadLineAsync();
                            if (line == string.Empty)
                            {
                                // double newline, dispatch message and reset for next
                                if (data.Length > 0)
                                {
                                    MessageReceived?.Invoke(this, new EventSourceMessageEventArgs(data.ToString().Trim(), evt, id));
                                }
                                data.Clear();
                                id = string.Empty;
                                evt = DefaultEventType;
                                continue;
                            }
                            else if (line.First() == ':')
                            {
                                // Ignore comments
                                continue;
                            }

                            int dataIndex = line.IndexOf(':');
                            string field;
                            if (dataIndex == -1)
                            {
                                dataIndex = line.Length;
                                field = line;
                            }
                            else
                            {
                                field = line.Substring(0, dataIndex);
                                dataIndex += 1;
                            }

                            string value = line.Substring(dataIndex).Trim();

                            switch (field)
                            {
                                case "event":
                                    // Set event type
                                    evt = value;
                                    break;
                                case "data":
                                    // Append a line to data using a single \n as EOL
                                    data.Append($"{value}\n");
                                    break;
                                case "retry":
                                    // Set reconnect delay for next disconnect
                                    int.TryParse(value, out ReconnectDelay);
                                    break;
                                case "id":
                                    // Set ID
                                    LastEventId = value;
                                    id = LastEventId;
                                    break;
                                default:
                                    // Ignore other fields
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Disconnect(ex);
            }
        }

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 : Machine.cs
License : MIT License
Project Creator : 3RD-Dimension

public void SetFile(IList<string> file)
        {
            if (Mode == OperatingMode.SendFile)
            {
                RaiseEvent(Info, "Can't change file while active");
                return;
            }

            bool[] pauselines = new bool[file.Count];

            for (int line = 0; line < file.Count; line++)
            {
                var matches = GCodeParser.GCodeSplitter.Matches(file[line]);

                foreach (Match m in matches)
                {
                    if (m.Groups[1].Value == "M")
                    {
                        int code = int.MinValue;

                        if (int.TryParse(m.Groups[2].Value, out code))
                        {
                            if (code == 0 || code == 1 || code == 2 || code == 30 || code == 6)
                                pauselines[line] = true;
                        }
                    }
                }
            }

            File = new ReadOnlyCollection<string>(file);
            PauseLines = new ReadOnlyCollection<bool>(pauselines);

            FilePosition = 0;

            RaiseEvent(FilePositionChanged);
        }

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

public static int GetInt(string s, int defaultValue)
        {
            return int.TryParse(s, out var value) ? value : defaultValue;
        }

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

internal static object ParseValue(Type type, string json) {
            if (type == typeof(string)) {
                if (json.Length <= 2)
                    return string.Empty;
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\\\", "\"\"").Replace("\\", string.Empty).Replace("\"\"", "\\");
            }
            if (type == typeof(int)) {
                int result;
                int.TryParse(json, out result);
                return result;
            }
            if (type == typeof(float)) {
                float result;
                float.TryParse(json, out result);
                return result;
            }
            if (type == typeof(double)) {
                double result;
                double.TryParse(json, out result);
                return result;
            }
            if (type == typeof(bool)) {
                return json.ToLower() == "true";
            }
            if (json == "null") {
                return null;
            }
            if (type.IsArray) {
                Type arrayType = type.GetElementType();
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                Array newArray = Array.CreateInstance(arrayType, elems.Count);
                for (int i = 0; i < elems.Count; i++)
                    newArray.SetValue(ParseValue(arrayType, elems[i]), i);
                splitArrayPool.Push(elems);
                return newArray;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {
                Type listType = type.GetGenericArguments()[0];
                if (json[0] != '[' || json[json.Length - 1] != ']')
                    return null;

                List<string> elems = Split(json);
                var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count });
                for (int i = 0; i < elems.Count; i++)
                    list.Add(ParseValue(listType, elems[i]));
                splitArrayPool.Push(elems);
                return list;
            }
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
                Type keyType, valueType;
                {
                    Type[] args = type.GetGenericArguments();
                    keyType = args[0];
                    valueType = args[1];
                }

                //Refuse to parse dictionary keys that aren't of type string
                if (keyType != typeof(string))
                    return null;
                //Must be a valid dictionary element
                if (json[0] != '{' || json[json.Length - 1] != '}')
                    return null;
                //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
                List<string> elems = Split(json);
                if (elems.Count % 2 != 0)
                    return null;

                var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 });
                for (int i = 0; i < elems.Count; i += 2) {
                    if (elems[i].Length <= 2)
                        continue;
                    string keyValue = elems[i].Substring(1, elems[i].Length - 2);
                    object val = ParseValue(valueType, elems[i + 1]);
                    dictionary.Add(keyValue, val);
                }
                return dictionary;
            }
            if (type == typeof(object)) {
                return ParseAnonymousValue(json);
            }
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                return ParseObject(type, json);
            }

            return null;
        }

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

static object ParseAnonymousValue(string json) {
            if (json.Length == 0)
                return null;
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                List<string> elems = Split(json);
                if (elems.Count % 2 != 0)
                    return null;
                var dict = new Dictionary<string, object>(elems.Count / 2);
                for (int i = 0; i < elems.Count; i += 2)
                    dict.Add(elems[i].Substring(1, elems[i].Length - 2), ParseAnonymousValue(elems[i + 1]));
                return dict;
            }
            if (json[0] == '[' && json[json.Length - 1] == ']') {
                List<string> items = Split(json);
                var finalList = new List<object>(items.Count);
                for (int i = 0; i < items.Count; i++)
                    finalList.Add(ParseAnonymousValue(items[i]));
                return finalList;
            }
            if (json[0] == '\"' && json[json.Length - 1] == '\"') {
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\", string.Empty);
            }
            if (char.IsDigit(json[0]) || json[0] == '-') {
                if (json.Contains(".")) {
                    double result;
                    double.TryParse(json, out result);
                    return result;
                } else {
                    int result;
                    int.TryParse(json, out result);
                    return result;
                }
            }
            if (json == "true")
                return true;
            if (json == "false")
                return false;
            // handles json == "null" as well as invalid JSON
            return null;
        }

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

private static void PopulateFromSrt(TextReader reader, List<Subreplacedle> subreplacedles)
        {
            // Parse using a simple state machine:
            //   0: Parsing number
            //   1: Parsing start / end time
            //   2: Parsing text
            byte state = 0;

            float startTime = 0f,
                  endTime = 0f;

            StringBuilder text = new StringBuilder();
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                switch (state)
                {
                    case 0:
                        if (string.IsNullOrEmpty(line))
                            // No number found; continue in same state.
                            continue;

                        if (!int.TryParse(line, out int _))
                            goto Invalid;

                        // Number found; continue to next state.
                        state = 1;
                        break;

                    case 1:
                        Match m = Regex.Match(line, @"(\d+):(\d+):(\d+,\d+) *--> *(\d+):(\d+):(\d+,\d+)");

                        if (!m.Success)
                            goto Invalid;

                        startTime = int.Parse(m.Groups[1].Value) * 3600
                                  + int.Parse(m.Groups[2].Value) * 60
                                  + float.Parse(m.Groups[3].Value.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture);

                        endTime = int.Parse(m.Groups[4].Value) * 3600
                                + int.Parse(m.Groups[5].Value) * 60
                                + float.Parse(m.Groups[6].Value.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture);

                        // Subreplacedle start / end found; continue to next state.
                        state = 2;
                        break;

                    case 2:
                        if (string.IsNullOrEmpty(line))
                        {
                            // End of text; continue to next state.
                            subreplacedles.Add(new Subreplacedle(text.ToString(), startTime, endTime));

                            text.Length = 0;
                            state = 0;
                        }
                        else
                        {
                            // Continuation of text; continue in same state.
                            text.AppendLine(line);
                        }

                        break;

                    default:
                        // Shouldn't happen.
                        throw new Exception();
                }
            }

            Invalid:

            Debug.Log("[Beat Singer] Invalid subtiles file found, cancelling load...");
            subreplacedles.Clear();
        }

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 : ChineseExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public static int ConverToInt(this string str)
        {
            int.TryParse(str, out int num);
            return num;
        }

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

public static int? ToInt32(this string str)
        {
            int value;
            if (int.TryParse(str, out value))
            {
                return value;
            }
            return null;
        }

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

private async Task<bool> CheckWare(int playerId, string wareName, string number, string strRelation)
        {
            if (!int.TryParse(number, out int numberValue))
            {
                return false;
            }

            var ware = await _wareDomainService.Get(x => x.Name == wareName);
            if (ware == null)
            {
                return false;
            }

            var playerWare = await _playerWareDomainService.Get(x => x.WareId == ware.Id && x.PlayerId == playerId);
            if (playerWare == null)
            {
                return false;
            }

            var relations = GetRelations(strRelation);
            return relations.Contains(playerWare.Number.CompareTo(numberValue));
        }

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

private void btc_MessageReceived(object sender, MessageReceivedEventArgs e)
		{
			int eioMessageType;
			if (int.TryParse(e.Message.Substring(0, 1), out eioMessageType))
			{
				switch ((EngineioMessageType)eioMessageType)
				{
					case EngineioMessageType.PING:
						//replace incoming PING with PONG in incoming message and resend it.
						m_webSocket.Send(string.Format(CultureInfo.InvariantCulture, "{0}{1}", (int)EngineioMessageType.PONG, e.Message.Substring(1, e.Message.Length - 1)));
						break;
					case EngineioMessageType.PONG:
						m_pong = true;
						break;

					case EngineioMessageType.MESSAGE:
						int sioMessageType;
						if (int.TryParse(e.Message.Substring(1, 1), out sioMessageType))
						{
							switch ((SocketioMessageType)sioMessageType)
							{
								case SocketioMessageType.CONNECT:
									//Send "42["subscribe",["marketdata_cnybtc","marketdata_cnyltc","marketdata_btcltc"]]"
									m_webSocket.Send(string.Format(CultureInfo.InvariantCulture, "{0}{1}{2}", (int)EngineioMessageType.MESSAGE,
																	   (int)SocketioMessageType.EVENT,
//																	   "[\"subscribe\",[\"marketdata_cnybtc\",\"marketdata_cnyltc\",\"grouporder_cnybtc\"]]"
																	   "[\"subscribe\",[\"grouporder_cnybtc\"]]"
																	   )
																	   );

									break;

								case SocketioMessageType.EVENT:
									if (e.Message.Substring(4, 5) == "trade")//listen on "trade"
										Log.Info("[BtcChina] TRADE: " + e.Message.Substring(e.Message.IndexOf('{'), e.Message.LastIndexOf('}') - e.Message.IndexOf('{') + 1));
									else
										if (e.Message.Substring(4, 10) == "grouporder")//listen on "trade")
										{
											Log.Info("[BtcChina] grouporder event");

											var json = e.Message.Substring(e.Message.IndexOf('{'), e.Message.LastIndexOf('}') - e.Message.IndexOf('{') + 1);
											var objResponse = JsonConvert.DeserializeObject<WsGroupOrderMessage>(json);
											OnMessageGroupOrder(objResponse.GroupOrder);
										}
										else
										{
											Log.Warn("[BtcChina] Unknown message: " + e.Message.Substring(0, 100));
										}
									break;

								default:
									Log.Error("[BtcChina] error switch socket.io messagetype: " + e.Message);
									break;
							}
						}
						else
						{
							Log.Error("[BtcChina] error parse socket.io messagetype!");
						}
						break;

					default:
						Log.Error("[BtcChina] error switch engine.io messagetype");
						break;
				}
			}
			else
			{
				Log.Error("[BtcChina] error parsing engine.io messagetype!");
			}
		}

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

public static IPEndPoint TryParseStringToIp(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                return null;
            }

            int port;
            var lastIndex = value.IndexOf(":");
            if (lastIndex > 0)
            {
                var strPort = value.Substring(lastIndex + 1);
                if (!int.TryParse(strPort, out port) || port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
                {
                    return null;
                }
            }
            else
            {
                port = Transfer.SessionClient.DefaultPort;
            }

            lastIndex = lastIndex > 0 ? lastIndex : value.Length;
            var ipString = value.Substring(0, lastIndex);

            if (!IPAddress.TryParse(ipString, out IPAddress ip))
            {
                return null;
            }

            return new IPEndPoint(ip, port);
        }

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

public bool Validate()
        {
            if (!int.TryParse(Input_DelaySaveGame, out int delaySaveGame)
                || delaySaveGame < 5
                ) return false;

            return true;
        }

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

private static Grants GetGrantsByStr(string value)
        {
            if (int.TryParse(value, out int res) && Enum.IsDefined(typeof(Grants), res))
            {
                return (Grants)res;
            }

            if (Enum.TryParse<Grants>(value, out Grants newGrants))
            {
                return newGrants;
            }

            return Grants.NoPermissions;
        }

19 View Source File : DateAndSizeRollingFileAppender.cs
License : MIT License
Project Creator : Abc-Arbitrage

private int FindLastRollingFileNumber(string directory)
        {
            var fileNumber = 0;
            var root = FilenameRoot + ".";
            var extension = FilenameExtension.Length == 0 ? "" : "." + FilenameExtension;
            foreach (var filename in Directory.EnumerateFiles(directory).Select(f => f.ToUpper()))
            {
                if (filename.StartsWith(root, StringComparison.OrdinalIgnoreCase) && filename.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
                {
                    var rootLength = root.Length;
                    var extensionLength = extension.Length;
                    if (filename.Length - rootLength - extensionLength > 0 && int.TryParse(filename.Substring(rootLength, filename.Length - rootLength - extensionLength), out var tempNumber))
                        fileNumber = Math.Max(fileNumber, tempNumber);
                }
            }

            return fileNumber;
        }

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

static int? ParseFontSize(IXmlLineInfo lineInfo, string size)
		{
			int value;
			return int.TryParse(size, out value)
				? value
				: (int?)null;
		}

19 View Source File : OVRScreenshotWizard.cs
License : MIT License
Project Creator : absurd-joy

void OnWizardCreate()
	{
		if ( !replacedetDatabase.IsValidFolder( cubeMapFolder ) )
		{
			if (!CreatereplacedetPath(cubeMapFolder))
			{
				Debug.LogError( "Created path failed: " + cubeMapFolder );
				return;
			}
		}

		bool existingCamera = true;
		bool existingCameraStateSave = true;
		Camera camera = renderFrom.GetComponent<Camera>();
		if (camera == null)
		{
			camera = renderFrom.AddComponent<Camera>();
			camera.farClipPlane = 10000f;
			existingCamera = false;
		}
		else
		{
			existingCameraStateSave = camera.enabled;
			camera.enabled = true;
		}
		// find the last screenshot saved
		if (cubeMapFolder[cubeMapFolder.Length-1] != '/')
		{
			cubeMapFolder += "/";
		}
		int idx = 0;
		string[] fileNames = Directory.GetFiles(cubeMapFolder);
		foreach(string fileName in fileNames)
		{
			if (!fileName.ToLower().EndsWith(".cubemap"))
			{
				continue;
			}
			string temp = fileName.Replace(cubeMapFolder + "vr_screenshot_", string.Empty);
			temp = temp.Replace(".cubemap", string.Empty);
			int tempIdx = 0;
			if (int.TryParse( temp, out tempIdx ))
			{
				if (tempIdx > idx)
				{
					idx = tempIdx;
				}
			}
		}
		string pathName = string.Format("{0}vr_screenshot_{1}.cubemap", cubeMapFolder, (++idx).ToString("d2"));
		Cubemap cubemap = new Cubemap(size, TextureFormat.RGB24, false);

		// render into cubemap
		if ((camera != null) && (cubemap != null))
		{
			// set up cubemap defaults
			OVRCubemapCapture.RenderIntoCubemap(camera, cubemap);
			if (existingCamera)
			{
				camera.enabled = existingCameraStateSave;
			}
			else
			{
				DestroyImmediate(camera);
			}
			// generate a regular texture as well?
			if ( ( saveMode == SaveMode.SaveCubemapScreenshot ) || ( saveMode == SaveMode.SaveBoth ) )
			{
				GenerateTexture(cubemap, pathName);
			}

			if ( ( saveMode == SaveMode.SaveUnityCubemap ) || ( saveMode == SaveMode.SaveBoth ) )
			{
				Debug.Log( "Saving: " + pathName );
				// by default the unity cubemap isn't saved
				replacedetDatabase.Createreplacedet( cubemap, pathName );
				// reimport as necessary
				replacedetDatabase.Savereplacedets();
				// select it in the project tree so developers can find it
				EditorGUIUtility.PingObject( cubemap );
				Selection.activeObject = cubemap;
			}
			replacedetDatabase.Refresh();
		}
	}

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

[CommandHandler("bestow", AccessLevel.Advocate, CommandHandlerFlag.RequiresWorld, 2,
            "Sets a character's Advocate Level.",
            "<name> <level>\nAdvocates can bestow any level less than their own.")]
        public static void HandleBestow(Session session, params string[] parameters)
        {
            var charName = string.Join(" ", parameters).Trim();

            var level = parameters[parameters.Length - 1];

            if (!int.TryParse(level, out var advocateLevel) || advocateLevel < 1 || advocateLevel > 7)
            {
                session.Network.EnqueueSend(new GameMessageSystemChat($"{level} is not a valid advocate level.", ChatMessageType.Broadcast));
                return;
            }

            var advocateName = charName.TrimEnd((" " + level).ToCharArray());

            var playerToFind = PlayerManager.FindByName(advocateName);

            if (playerToFind != null)
            {
                if (playerToFind is Player player)
                {
                    //if (!Advocate.IsAdvocate(player))
                    //{
                    //    session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not an Advocate.", ChatMessageType.Broadcast));
                    //    return;
                    //}

                    if (player.IsPK || PropertyManager.GetBool("pk_server").Item)
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} in a Player Killer and cannot be an Advocate.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (session.Player.AdvocateLevel <= player.AdvocateLevel)
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot change {playerToFind.Name}'s Advocate status because they are equal to or out rank you.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (advocateLevel >= session.Player.AdvocateLevel && !session.Player.IsAdmin)
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot bestow {playerToFind.Name}'s Advocate rank to {advocateLevel} because that is equal to or higher than your rank.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (advocateLevel == player.AdvocateLevel)
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name}'s Advocate rank is already at level {advocateLevel}.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (!Advocate.CanAcceptAdvocateItems(player, advocateLevel))
                    {
                        session.Network.EnqueueSend(new GameMessageSystemChat($"You cannot change {playerToFind.Name}'s Advocate status because they do not have capacity for the advocate items.", ChatMessageType.Broadcast));
                        return;
                    }

                    if (Advocate.Bestow(player, advocateLevel))
                        session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is now an Advocate, level {advocateLevel}.", ChatMessageType.Broadcast));
                    else
                        session.Network.EnqueueSend(new GameMessageSystemChat($"Advocate bestowal of {playerToFind.Name} failed.", ChatMessageType.Broadcast));
                }
                else
                    session.Network.EnqueueSend(new GameMessageSystemChat($"{playerToFind.Name} is not online. Cannot complete bestowal process.", ChatMessageType.Broadcast));
            }
            else
                session.Network.EnqueueSend(new GameMessageSystemChat($"{advocateName} was not found in the database.", ChatMessageType.Broadcast));
        }

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

[CommandHandler("databaseperftest", AccessLevel.Developer, CommandHandlerFlag.None, 0, "Test server/database performance.", "biotasPerTest\n" + "optional parameter biotasPerTest if omitted 1000")]
        public static void HandleDatabasePerfTest(Session session, params string[] parameters)
        {
            int biotasPerTest = DatabasePerfTest.DefaultBiotasTestCount;

            if (parameters?.Length > 0)
                int.TryParse(parameters[0], out biotasPerTest);

            var processor = new DatabasePerfTest();
            processor.RunAsync(session, biotasPerTest);
        }

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

[CommandHandler("database-shard-cache-pbrt", AccessLevel.Developer, CommandHandlerFlag.None, 0, "Shard Database, Player Biota Cache - Retention Time (in minutes)")]
        public static void HandleDatabaseShardCachePBRT(Session session, params string[] parameters)
        {
            if (!(DatabaseManager.Shard.BaseDatabase is ShardDatabaseWithCaching shardDatabaseWithCaching))
            {
                CommandHandlerHelper.WriteOutputInfo(session, "DatabaseManager is not using ShardDatabaseWithCaching");

                return;
            }

            if (parameters == null || parameters.Length == 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Shard Database, Player Biota Cache - Retention Time {shardDatabaseWithCaching.PlayerBiotaRetentionTime.TotalMinutes:N0} m");

                return;
            }

            if (!int.TryParse(parameters[0], out var value) || value < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, "Unable to parse argument. Specify retention time in integer minutes.");

                return;
            }

            shardDatabaseWithCaching.PlayerBiotaRetentionTime = TimeSpan.FromMinutes(value);

            CommandHandlerHelper.WriteOutputInfo(session, $"Shard Database, Player Biota Cache - Retention Time {shardDatabaseWithCaching.PlayerBiotaRetentionTime.TotalMinutes:N0} m");
        }

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

[CommandHandler("database-shard-cache-npbrt", AccessLevel.Developer, CommandHandlerFlag.None, 0, "Shard Database, Non-Player Biota Cache - Retention Time (in minutes)")]
        public static void HandleDatabaseShardCacheNPBRT(Session session, params string[] parameters)
        {
            if (!(DatabaseManager.Shard.BaseDatabase is ShardDatabaseWithCaching shardDatabaseWithCaching))
            {
                CommandHandlerHelper.WriteOutputInfo(session, "DatabaseManager is not using ShardDatabaseWithCaching");

                return;
            }

            if (parameters == null || parameters.Length == 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, $"Shard Database, Non-Player Biota Cache - Retention Time {shardDatabaseWithCaching.NonPlayerBiotaRetentionTime.TotalMinutes:N0} m");

                return;
            }

            if (!int.TryParse(parameters[0], out var value) || value < 0)
            {
                CommandHandlerHelper.WriteOutputInfo(session, "Unable to parse argument. Specify retention time in integer minutes.");

                return;
            }

            shardDatabaseWithCaching.NonPlayerBiotaRetentionTime = TimeSpan.FromMinutes(value);

            CommandHandlerHelper.WriteOutputInfo(session, $"Shard Database, Non-Player Biota Cache - Retention Time {shardDatabaseWithCaching.NonPlayerBiotaRetentionTime.TotalMinutes:N0} m");
        }

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

[CommandHandler("testlootgen", AccessLevel.Admin, CommandHandlerFlag.ConsoleInvoke, 1, "Generates Loot for testing LootFactories.  Do testlootgen -info for examples.", "<number of items> <loot tier> <melee, missile, caster, armor, pet, aetheria (optional)>")]
        public static void TestLootGenerator(Session session, params string[] parameters)
        {
            if (parameters[0] == "-info")
            {
                Console.WriteLine($"Usage: \n" +
                                $"<number of items> <loot tier> <(optional)display table - melee, missile, caster, jewelry, armor, cloak, pet, aetheria> \n" +
                                $" Example: The following command will generate 1000 items in Tier 7 that shows the melee table\n" +
                                $"testlootgen 1000 7 melee \n" +
                                $" Example: The following command will generate 1000 items in Tier 6 that just shows a summary \n" +
                                $"testlootgen 1000 6 \n");
                return;
            }

            if (!int.TryParse(parameters[0], out int numItems))
            {
                Console.WriteLine("Number of items is not an integer");
                return;
            }

            if (!int.TryParse(parameters[1], out int tier))
            {
                Console.WriteLine("Tier is not an integer");
                return;
            }

            if (tier < 1 || tier > 8)
            {
                Console.WriteLine($"Tier must be 1-8.  You entered tier {tier}, which does not exist!");
                return;
            }

            var logStats = false;
            var displayTable = "";

            if (parameters.Length > 2)
            {
                switch (parameters[2].ToLower())
                {
                    case "melee":
                    case "missile":
                    case "caster":
                    case "jewelry":
                    case "armor":
                    case "pet":
                    case "aetheria":
                    case "all":
                    case "cloak":
                        displayTable = parameters[2].ToLower();
                        break;

                    case "-log":
                        logStats = true;
                        break;

                    default:
                        Console.WriteLine("Invalid Table Option.  Available Tables to show are melee, missile, caster, jewelry, armor, cloak, pet, aetheria or all.");
                        return;
                }
            }

            if (parameters.Length > 3)
            {
                var logParam = parameters[3].ToLower();

                if (logParam == "-log")
                    logStats = true;
                else
                {
                    Console.WriteLine("Invalid Option.  To log a file, use option -log");
                    return;
                }
            }

            var results = LootGenerationFactory_Test.TestLootGen(numItems, tier, logStats, displayTable);

            Console.WriteLine(results);
        }

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

[CommandHandler("testlootgencorpse", AccessLevel.Admin, CommandHandlerFlag.ConsoleInvoke, 1, "Generates Corpses for testing LootFactories", "<DID> <number corpses> <display table - melee, missile, caster, armor, pet, aetheria>")]
        public static void TestLootGeneratorCorpse(Session session, params string[] parameters)
        {
            if (parameters[0] == "-info")
            {
                Console.WriteLine($"Usage: \n" +
                                $"<DID> <number corpses> <(optional)display table - melee, missile, caster, jewelry, armor, pet, aetheria> \n" +
                                $" Example: The following command will generate 50 corpses generated from DeathTreasure DID 998 that shows the caster table\n" +
                                $"testlootgencorpse 998 50 caster \n" +
                                $" Example: The following command will generate 75 corpses generated from DeathTreasure DID 452 that just shows a summary \n" +
                                $"testlootgencorpse 452 75 \n");
                return;
            }

            if (parameters.Length < 2)
            {
                Console.WriteLine($" LootFactory Simulator \n ---------------------\n Need to specify number of coprses\n");
                return;
            }

            if (!uint.TryParse(parameters[0], out uint monsterDID))
            {
                Console.WriteLine($" LootFactory Simulator \n ---------------------\n DID specified is not an integer \n");
                return;
            }

            if (!int.TryParse(parameters[1], out int numItems))
            {
                Console.WriteLine($" LootFactory Simulator \n ---------------------\n Invalid Parameter - Must be a number \n");
                return;
            }

            var logStats = false;
            var displayTable = "";

            if (parameters.Length > 2)
            {
                switch (parameters[2].ToLower())
                {
                    case "melee":
                    case "missile":
                    case "caster":
                    case "jewelry":
                    case "armor":
                    case "pet":
                    case "aetheria":
                    case "all":
                    case "cloak":
                        displayTable = parameters[2].ToLower();
                        break;

                    case "-log":
                        logStats = true;
                        break;

                    default:
                        Console.WriteLine("Invalid Table Option.  Available Tables to show are melee, missile, caster, jewelry, armor, cloak, pet, aetheria or all.");
                        return;
                }
            }

            if (parameters.Length > 3)
            {
                var logParam = parameters[3].ToLower();

                if (logParam == "-log")
                    logStats = true;
                else
                {
                    Console.WriteLine("Invalid Option.  To log a file, use option -log");
                    return;
                }
            }
            var results = LootGenerationFactory_Test.TestLootGenMonster(monsterDID, numItems, logStats, displayTable);

            Console.WriteLine(results);
        }

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

public static void HandleHouseSelect(Session session, bool confirmed, params string[] parameters)
        {
            if (!int.TryParse(parameters[0], out var houseIdx))
                return;

            // ensure current multihouse owner
            if (!session.Player.IsMultiHouseOwner(false))
            {
                log.Warn($"{session.Player.Name} tried to /house-select {houseIdx}, but they are not currently a multi-house owner!");
                return;
            }

            // get house info for this index
            var multihouses = session.Player.GetMultiHouses();

            if (houseIdx < 1 || houseIdx > multihouses.Count)
            {
                session.Network.EnqueueSend(new GameMessageSystemChat($"Please enter a number between 1 and {multihouses.Count}.", ChatMessageType.Broadcast));
                return;
            }

            var keepHouse = multihouses[houseIdx - 1];

            // show confirmation popup
            if (!confirmed)
            {
                var houseType = $"{keepHouse.HouseType}".ToLower();
                var loc = HouseManager.GetCoords(keepHouse.SlumLord.Location);

                var msg = $"Are you sure you want to keep the {houseType} at\n{loc}?";
                if (!session.Player.ConfirmationManager.EnqueueSend(new Confirmation_Custom(session.Player.Guid, () => HandleHouseSelect(session, true, parameters)), msg))
                    session.Player.SendWeenieError(WeenieError.ConfirmationInProgress);
                return;
            }

            // house to keep confirmed, abandon the other houses
            var abandonHouses = new List<House>(multihouses);
            abandonHouses.RemoveAt(houseIdx - 1);

            foreach (var abandonHouse in abandonHouses)
            {
                var house = session.Player.GetHouse(abandonHouse.Guid.Full);

                HouseManager.HandleEviction(house, house.HouseOwner ?? 0, true);
            }

            // set player properties for house to keep
            var player = PlayerManager.FindByGuid(keepHouse.HouseOwner ?? 0, out bool isOnline);
            if (player == null)
            {
                log.Error($"{session.Player.Name}.HandleHouseSelect({houseIdx}) - couldn't find HouseOwner {keepHouse.HouseOwner} for {keepHouse.Name} ({keepHouse.Guid})");
                return;
            }

            player.HouseId = keepHouse.HouseId;
            player.HouseInstance = keepHouse.Guid.Full;

            player.SaveBiotaToDatabase();

            // update house panel for current player
            var actionChain = new ActionChain();
            actionChain.AddDelaySeconds(3.0f);  // wait for slumlord inventory biotas above to save
            actionChain.AddAction(session.Player, session.Player.HandleActionQueryHouse);
            actionChain.EnqueueChain();

            Console.WriteLine("OK");
        }

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

public static ChanceTable<int> ParseChanceTable_Int(string[] lines, int startLine)
        {
            var chanceTable = new ChanceTable<int>();

            for (var i = startLine + 1; i < lines.Length; i++)
            {
                var line = lines[i].Trim();

                if (line.Length < 2)
                    continue;

                if (line.Length == 2)
                    break;

                if (line.StartsWith("//"))
                    continue;

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

                if (!match.Success || !int.TryParse(match.Groups[1].Value, out var val) || !float.TryParse(match.Groups[2].Value, out var chance))
                {
                    Console.WriteLine($"Couldn't parse {line}");
                    continue;
                }
                chanceTable.Add((val, chance));
            }

            return chanceTable;
        }

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

public bool HasQuestCompletes(string questName)
        {
            if (Debug) Console.WriteLine($"{Name}.QuestManager.HasQuestCompletes({questName})");

            if (!questName.Contains("@"))
                return HasQuest(questName);

            var pieces = questName.Split('@');
            if (pieces.Length != 2)
            {
                Console.WriteLine($"{Name}.QuestManager.HasQuestCompletes({questName}): error parsing quest name");
                return false;
            }
            var name = pieces[0];
            if (!Int32.TryParse(pieces[1], out var numCompletes))
            {
                Console.WriteLine($"{Name}.QuestManager.HasQuestCompletes({questName}): unknown quest format");
                return HasQuest(questName);
            }
            var quest = GetQuest(name);
            if (quest == null)
                return false;

            var success = quest.NumTimesCompleted == numCompletes;     // minimum or exact?
            if (Debug) Console.WriteLine(success);
            return success;
        }

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 : FeatureDefinitionFactory.cs
License : Microsoft Public License
Project Creator : achimismaili

public static FeatureDefinition GetFaultyDefinition(
             string uniqueIdentifier,
             Scope scope,
             Version version
            )
        {
            if (string.IsNullOrEmpty(uniqueIdentifier))
            {
                return null;
            }


            Guid featureId;
            int compatibilityLevel;
            string sandBoxedSolutionLocation;


            var splittedId = uniqueIdentifier.Split(Common.Constants.MagicStrings.GuidSeparator);

            if (splittedId.Length >= 1)
            {
                var featureIdreplacedtring = splittedId[0];

                if (!Guid.TryParse(featureIdreplacedtring, out featureId))
                {
                    return null;
                }
            }
            else
            {
                return null;
            }

            if (splittedId.Length >= 2)
            {
                var compatibilityLevelreplacedtring = splittedId[1];

                if (!Int32.TryParse(compatibilityLevelreplacedtring, out compatibilityLevel))
                {
                    compatibilityLevel = Common.Constants.Labels.FaultyFeatureCompatibilityLevel;
                }
            }
            else
            {
                compatibilityLevel = Common.Constants.Labels.FaultyFeatureCompatibilityLevel;
            }

            if (splittedId.Length >= 3)
            {
                sandBoxedSolutionLocation = splittedId[2];
            }
            else
            {
                sandBoxedSolutionLocation = null;
            }

            var featureDefinition = new FeatureDefinition(
                featureId,
                compatibilityLevel,
                Common.Constants.Labels.FaultyFeatureDescription,
                Common.Constants.Labels.FaultyFeatureName,
                false,
                Common.Constants.Labels.FaultyFeatureName,
                null,
                scope,
                Common.Constants.Labels.FaultyFeatureName,
                Guid.Empty,
                Common.Constants.Labels.FaultyFeatureUiVersion,
                version,
                sandBoxedSolutionLocation
                );

            return featureDefinition;
        }

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

public static void SetParameterValue(Parameter param, string value)
        {
            if (param.StorageType == StorageType.Double) {
                double d = 0;
                if (double.TryParse(value, out d)) {
                    param.Set(d);
                }
            } else if (param.StorageType == StorageType.Integer) {
                int i = 0;
                if (int.TryParse(value, out i))
                {
                    param.Set(i);
                }
            } else {
                param.Set(value);
            }
        }

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

[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Because this hack only works this way...")]  
        public static void RenumberByPicks(UIDoreplacedent uidoc, Doreplacedent doc, UIApplication app)
        {
            if (uidoc == null || app == null) {
                return;
            }

            IList<Reference> refList = new List<Reference>();
            try {
                while (true) {
                    refList.Add(uidoc.Selection.PickObject(ObjectType.Element, "Select elements in order to be renumbered. ESC when finished."));
                }
            } catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }

            if (refList.Count == 0) {
                return;
            }

            using (var t = new Transaction(doc, "Renumber")) {
                t.Start();
                int incAmount = IncrementSettings.Default.IncrementValue;
                string startValue = string.Empty;
                string startText = string.Empty;
                Reference firstRef = refList[0];
                Parameter firstParam = GetParameterForReference(doc, firstRef);
                if (firstParam == null) {
                        return;
                } else
                {
                    startText = firstParam.replacedtring();
                    startValue = GetSourceNumberreplacedtring(startText);
                }

                if (int.TryParse(startValue, out int StartValueAsInt))
                {
                    int aggregateInc = IncrementSettings.Default.OffsetValue;
                    foreach (Reference r in refList)
                    {
                        if (r == null)
                        {
                            continue;
                        }
                        Parameter param = GetParameterForReference(doc, r);
                        if (param == null)
                        {
                            continue;
                        }
                        app.DialogBoxShowing += DismissDuplicateQuestion;

                        if (IncrementSettings.Default.UseDestinationSearchPattern)
                        {
                            SetParameterToValue(
                               param,
                               GetDestinationNumberreplacedtring(param.replacedtring(), IncrementString(startValue, aggregateInc, IncrementSettings.Default.KeepLeadingZeros)));
                        }
                        else
                        {
                            SetParameterToValue(
                                param,
                                GetDestinationNumberreplacedtring(startText, IncrementString(startValue, aggregateInc, IncrementSettings.Default.KeepLeadingZeros)));
                        }

                        aggregateInc += incAmount;
                    }
                }
                t.Commit();
            }
        }

See More Examples