string.Substring(int, int)

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

21090 Examples 7

19 View Source File : RequestObject.cs
License : MIT License
Project Creator : 0ffffffffh

private void Parse(string data)
        {
            string key,value, tagEnd;

            int beg=-1, end=0;

            beg = data.IndexOf("<", beg+1);

            while (beg != -1)
            {
                end = data.IndexOf(">", beg);

                if (end == -1)
                    break;

                beg++;

                key = data.Substring(beg, end - beg);

                tagEnd = string.Format("</{0}>", key);

                beg = end + 1;

                end = data.IndexOf(tagEnd, beg);

                if (end == -1)
                    break;

                value = data.Substring(beg, end - beg);

                items.Add(key.ToLower(), NormalizeValue(value));

                beg = data.IndexOf("<", end + 1);
            }

        }

19 View Source File : Entry.cs
License : MIT License
Project Creator : 0ffffffffh

public void FixForMultipleLineFeeds()
        {
            int index=0;

            while (index != -1)
            {
                index = Content.IndexOf("\r\n", index);

                if (index != -1)
                {
                    Content = Content.Remove(index, 2);

                    while (index + 2 < Content.Length)
                    {
                        if (Content.Substring(index, 2) == "\r\n")
                        {
                            Content = Content.Remove(index, 2).Insert(index, "<br/>");
                            index += 5;
                        }
                        else
                        {
                            Content = Content.Insert(index, "\r\n");
                            index += 2;
                            break;
                        }

                    }

                    if (index + 2 > Content.Length)
                        break;

                }
            }
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        y -= height;

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

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

public void Start<T>(DataHandshakeClient<T> handshake) where T : DataHandshakeClient<T> {
            Logger.Log(LogLevel.INF, "playersession", $"Startup #{ID} {Con}");
            using (Server.ConLock.W())
                Server.Sessions.Add(this);
            Server.PlayersByCon[Con] = this;
            Server.PlayersByID[ID] = this;

            if (Server.UserData.TryLoad(UID, out BanInfo ban) && !ban.Reason.IsNullOrEmpty()) {
                Con.Send(new DataDisconnectReason { Text = string.Format(Server.Settings.MessageIPBan, ban.Reason) });
                Con.Send(new DataInternalDisconnect());
                return;
            }

            string name = handshake.Name;
            if (name.StartsWith("#")) {
                string uid = Server.UserData.GetUID(name.Substring(1));
                if (uid.IsNullOrEmpty()) {
                    Con.Send(new DataDisconnectReason { Text = Server.Settings.MessageInvalidUserKey });
                    Con.Send(new DataInternalDisconnect());
                    return;
                }
                UID = uid;

                if (!Server.UserData.TryLoad(uid, out BasicUserInfo userinfo)) {
                    Con.Send(new DataDisconnectReason { Text = Server.Settings.MessageUserInfoMissing });
                    Con.Send(new DataInternalDisconnect());
                    return;
                }

                name = userinfo.Name.Sanitize(IllegalNameChars, true);
                if (name.Length > Server.Settings.MaxNameLength)
                    name = name.Substring(0, Server.Settings.MaxNameLength);
                if (name.IsNullOrEmpty())
                    name = "Ghost";

                if (Server.UserData.TryLoad(UID, out ban) && !ban.Reason.IsNullOrEmpty()) {
                    Con.Send(new DataDisconnectReason { Text = string.Format(Server.Settings.MessageBan, name, ban.Reason) });
                    Con.Send(new DataInternalDisconnect());
                    return;
                }

            } else {
                if (Server.Settings.AuthOnly) {
                    Con.Send(new DataDisconnectReason { Text = Server.Settings.MessageAuthOnly });
                    Con.Send(new DataInternalDisconnect());
                    return;
                }

                name = name.Sanitize(IllegalNameChars);
                if (name.Length > Server.Settings.MaxGuestNameLength)
                    name = name.Substring(0, Server.Settings.MaxGuestNameLength);
                if (name.IsNullOrEmpty())
                    name = "Guest";
            }

            if (name.Length > Server.Settings.MaxNameLength)
                name = name.Substring(0, Server.Settings.MaxNameLength);

            string nameSpace = name;
            name = name.Replace(" ", "");
            string fullNameSpace = nameSpace;
            string fullName = name;

            using (Server.ConLock.R()) {
                int i = 1;
                while (true) {
                    bool conflict = false;
                    foreach (CelesteNetPlayerSession other in Server.Sessions)
                        if (conflict = other.PlayerInfo?.FullName == fullName)
                            break;
                    if (!conflict)
                        break;
                    i++;
                    fullNameSpace = $"{nameSpace}#{i}";
                    fullName = $"{name}#{i}";
                }
            }

            string displayName = fullNameSpace;

            using (Stream? avatar = Server.UserData.ReadFile(UID, "avatar.png")) {
                if (avatar != null) {
                    AvatarEmoji = new() {
                        ID = $"celestenet_avatar_{ID}_",
                        Data = avatar.ToBytes()
                    };
                    displayName = $":{AvatarEmoji.ID}: {fullNameSpace}";
                }
            }

            DataPlayerInfo playerInfo = new() {
                ID = ID,
                Name = name,
                FullName = fullName,
                DisplayName = displayName
            };
            playerInfo.Meta = playerInfo.GenerateMeta(Server.Data);
            Server.Data.SetRef(playerInfo);

            Logger.Log(LogLevel.INF, "playersession", playerInfo.ToString());

            Con.Send(new DataHandshakeServer {
                PlayerInfo = playerInfo
            });
            Con.Send(AvatarEmoji);

            DataInternalBlob? blobPlayerInfo = DataInternalBlob.For(Server.Data, playerInfo);
            DataInternalBlob? blobAvatarEmoji = DataInternalBlob.For(Server.Data, AvatarEmoji);

            using (Server.ConLock.R())
                foreach (CelesteNetPlayerSession other in Server.Sessions) {
                    if (other == this)
                        continue;

                    DataPlayerInfo? otherInfo = other.PlayerInfo;
                    if (otherInfo == null)
                        continue;

                    other.Con.Send(blobPlayerInfo);
                    other.Con.Send(blobAvatarEmoji);

                    Con.Send(otherInfo);
                    Con.Send(other.AvatarEmoji);

                    foreach (DataType bound in Server.Data.GetBoundRefs(otherInfo))
                        if (!bound.Is<MetaPlayerPrivateState>(Server.Data) || other.Channel.ID == 0)
                            Con.Send(bound);
                }

            ResendPlayerStates();

            Server.InvokeOnSessionStart(this);
        }

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

public Tuple<Channel, Channel> Move(CelesteNetPlayerSession session, string name) {
            name = name.Sanitize();
            if (name.Length > Server.Settings.MaxChannelNameLength)
                name = name.Substring(0, Server.Settings.MaxChannelNameLength);
            if (name == NamePrivate)
                throw new Exception("Invalid private channel name.");

            lock (All) {
                Channel prev = session.Channel;

                Channel c;

                if (ByName.TryGetValue(name, out Channel? existing)) {
                    c = existing;
                    if (prev == c)
                        return Tuple.Create(c, c);

                } else {
                    c = new(this, name, NextID++);
                }

                prev.Remove(session);

                if (session.PlayerInfo != null)
                    c.Add(session);

                DataInternalBlob move = new(Server.Data, new DataChannelMove {
                    Player = session.PlayerInfo
                });
                session.Con.Send(move);
                using (prev.Lock.R())
                    foreach (CelesteNetPlayerSession other in prev.Players)
                        other.Con.Send(move);

                BroadcastList();

                session.ResendPlayerStates();

                if (!Server.UserData.GetKey(session.UID).IsNullOrEmpty()) {
                    Server.UserData.Save(session.UID, new LastChannelUserInfo {
                        Name = name
                    });
                }

                return Tuple.Create(prev, c);
            }
        }

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

public override string Create(string uid) {
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);
                string key = GetKey(uid);
                if (!key.IsNullOrEmpty())
                    return key;

                string keyFull;
                do {
                    keyFull = Guid.NewGuid().ToString().Replace("-", "");
                    key = keyFull.Substring(0, 16);
                } while (global.UIDs.ContainsKey(key));
                global.UIDs[key] = uid;

                Save(uid, new PrivateUserInfo {
                    Key = key,
                    KeyFull = keyFull
                });

                SaveRaw(GlobalPath, global);

                return key;
            }
        }

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

public NameValueCollection ParseQueryString(string url) {
            NameValueCollection nvc = new();

            int indexOfSplit = url.IndexOf('?');
            if (indexOfSplit == -1)
                return nvc;
            url = url.Substring(indexOfSplit + 1);

            string[] args = url.Split('&');
            foreach (string arg in args) {
                indexOfSplit = arg.IndexOf('=');
                if (indexOfSplit == -1)
                    continue;
                nvc[arg.Substring(0, indexOfSplit)] = arg.Substring(indexOfSplit + 1);
            }

            return nvc;
        }

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

public override string Create(string uid) {
            lock (GlobalLock) {
                string key = GetKey(uid);
                if (!key.IsNullOrEmpty())
                    return key;

                string keyFull;
                do {
                    keyFull = Guid.NewGuid().ToString().Replace("-", "");
                    key = keyFull.Substring(0, 16);
                } while (!GetUID(key).IsNullOrEmpty());

                using MiniCommand mini = new(this) {
                    SqliteOpenMode.ReadWrite,
                    @"
                        REPLACE INTO meta (uid, key, keyfull, registered)
                        VALUES ($uid, $key, $keyfull, 1);
                    ",
                    { "$uid", uid },
                    { "$key", key },
                    { "$keyfull", keyFull },
                };
                mini.Run();

                return key;
            }
        }

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

public void OnTextInput(char c) {
            if (!Active)
                return;

            if (c == (char) 13) {
                // Enter - send.
                // Handled in Update.

            } else if (c == (char) 8 && _CursorIndex > 0) {
                // Backspace - trim.
                if (Typing.Length > 0) {
                    int trim = 1;

                    // extra CursorIndex check since at index=1 using trim=1 is fine
                    if (_ControlHeld && _CursorIndex > 1) {
                        // adjust Ctrl+Backspace for having a space right before cursor
                        int _adjustedCursor = CursorIndex;
                        if (Typing[_CursorIndex - 1] == ' ')
                            _adjustedCursor--;
                        int prevWord = Typing.LastIndexOf(" ", _adjustedCursor - 1);
                        // if control is held and a space is found, trim from cursor back to space
                        if (prevWord >= 0)
                            trim = _adjustedCursor - prevWord;
                        // otherwise trim whole input back from cursor as it is one word
                        else
                            trim = _adjustedCursor;
                    }
                    // remove <trim> amount of characters before cursor
                    Typing = Typing.Remove(_CursorIndex - trim, trim);
                    _CursorIndex -= trim;
                }
                _RepeatIndex = 0;
                _Time = 0;
            } else if (c == (char) 127 && CursorIndex < Typing.Length) {
                // Delete - remove character after cursor.
                if (_ControlHeld && Typing[_CursorIndex] != ' ') {
                    int nextWord = Typing.IndexOf(" ", _CursorIndex);
                    // if control is held and a space is found, remove from cursor to space
                    if (nextWord >= 0) {
                        // include the found space in removal
                        nextWord++;
                        Typing = Typing.Remove(_CursorIndex, nextWord - _CursorIndex);
                    } else {
                        // otherwise remove everything after cursor
                        Typing = Typing.Substring(0, _CursorIndex);
                    }
                } else {
                    // just remove single char
                    Typing = Typing.Remove(_CursorIndex, 1);
                }
                _RepeatIndex = 0;
                _Time = 0;
            } else if (!char.IsControl(c)) {
                if (CursorIndex == Typing.Length) {
                    // Any other character - append.
                    Typing += c;
                } else {
                    // insert into string if cursor is not at the end
                    Typing = Typing.Insert(_CursorIndex, c.ToString());
                }
                _CursorIndex++;
                _RepeatIndex = 0;
                _Time = 0;
            }
        }

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

private static void HandleRequest(HttpListenerContext c) {
            Logger.Log(LogLevel.VVV, "rc", $"Requested: {c.Request.RawUrl}");

            string url = c.Request.RawUrl;
            int indexOfSplit = url.IndexOf('?');
            if (indexOfSplit != -1)
                url = url.Substring(0, indexOfSplit);

            RCEndPoint endpoint =
                EndPoints.FirstOrDefault(ep => ep.Path == c.Request.RawUrl) ??
                EndPoints.FirstOrDefault(ep => ep.Path == url) ??
                EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == c.Request.RawUrl.ToLowerInvariant()) ??
                EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == url.ToLowerInvariant()) ??
                EndPoints.FirstOrDefault(ep => ep.Path == "/404");
            endpoint.Handle(c);
        }

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

public void ReadTeapot(out string[] features, out uint token) {
            features = Dummy<string>.EmptyArray;
            token = 0;
            using StreamReader reader = new(TCPReaderStream, Encoding.UTF8, false, 1024, true);
            for (string line; !string.IsNullOrWhiteSpace(line = reader?.ReadLine() ?? "");) {
                if (line.StartsWith(CelesteNetUtils.HTTPTeapotConFeatures)) {
                    features = line.Substring(CelesteNetUtils.HTTPTeapotConFeatures.Length).Trim().Split(CelesteNetUtils.ConnectionFeatureSeparators);
                }
                if (line.StartsWith(CelesteNetUtils.HTTPTeapotConToken)) {
                    token = uint.Parse(line.Substring(CelesteNetUtils.HTTPTeapotConToken.Length).Trim());
                }
            }
        }

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

internal static ModuleDefinition GenerateCecilModule(replacedemblyName name) {
            replacedemblyName UnwrapName(replacedemblyName other) {
                int underscore = other.Name.LastIndexOf('_');
                if (underscore == -1)
                    return other;

                other.Name = other.Name.Substring(0, underscore);
                return other;
            }

            // Terraria ships with some dependencies as embedded resources.
            string resourceName = name.Name + ".dll";
            resourceName = Array.Find(typeof(Program).replacedembly.GetManifestResourceNames(), element => element.EndsWith(resourceName));
            if (resourceName != null) {
                using (Stream stream = typeof(Program).replacedembly.GetManifestResourceStream(resourceName))
                    // Read immediately, as the stream isn't open forever.
                    return ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate));
            }

            // Mod .dlls exist in the mod's .tmod containers.
            string nameStr = name.ToString();
            foreach (Mod mod in ModLoader.LoadedMods) {
                if (mod.Code == null || mod.File == null)
                    continue;

                // Check if it's the main replacedembly.
                if (mod.Code.GetName().ToString() == nameStr) {
                    // Let's unwrap the name and cache it for all DMDs as well.
                    // tModLoader changes the replacedembly name to allow mod updates, which breaks replacedembly.Load
                    ReflectionHelper.replacedemblyCache[UnwrapName(mod.Code.GetName()).ToString()] = mod.Code;

                    using (MemoryStream stream = new MemoryStream(mod.File.GetMainreplacedembly()))
                        // Read immediately, as the stream isn't open forever.
                        return ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate));
                }

                // Check if the replacedembly is possibly included in the .tmod
                if (!mod.Code.GetReferencedreplacedemblies().Any(other => UnwrapName(other).ToString() == nameStr))
                    continue;

                // Try to load lib/Name.dll
                byte[] data;
                if ((data = mod.File.GetFile($"lib/{name.Name}.dll")) != null)
                    using (MemoryStream stream = new MemoryStream(data))
                        // Read immediately, as the stream isn't open forever.
                        return ModuleDefinition.ReadModule(stream, new ReaderParameters(ReadingMode.Immediate));
            }

            return null;
        }

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

public static NameValueCollection ParseQueryString(string url) {
            NameValueCollection nvc = new();

            int indexOfSplit = url.IndexOf('?');
            if (indexOfSplit == -1)
                return nvc;
            url = url.Substring(indexOfSplit + 1);

            string[] args = url.Split('&');
            foreach (string arg in args) {
                indexOfSplit = arg.IndexOf('=');
                if (indexOfSplit == -1)
                    continue;
                nvc[arg.Substring(0, indexOfSplit)] = arg.Substring(indexOfSplit + 1);
            }

            return nvc;
        }

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

public virtual ChatCMDArg Parse(string raw, int index, int length) {
            RawText = raw;
            String = raw.Substring(index, length);
            Index = index;

            return Parse();
        }

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

private void HandleRequest(HttpRequestEventArgs c) {
            Logger.Log(LogLevel.VVV, "frontend", $"{c.Request.RemoteEndPoint} requested: {c.Request.RawUrl}");

            string url = c.Request.RawUrl;
            int indexOfSplit = url.IndexOf('?');
            if (indexOfSplit != -1)
                url = url.Substring(0, indexOfSplit);

            RCEndpoint? endpoint =
                EndPoints.FirstOrDefault(ep => ep.Path == c.Request.RawUrl) ??
                EndPoints.FirstOrDefault(ep => ep.Path == url) ??
                EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == c.Request.RawUrl.ToLowerInvariant()) ??
                EndPoints.FirstOrDefault(ep => ep.Path.ToLowerInvariant() == url.ToLowerInvariant());

            if (endpoint == null) {
                RespondContent(c, "frontend/" + url.Substring(1));
                return;
            }

            c.Response.Headers.Set("Cache-Control", "no-store, max-age=0, s-maxage=0, no-cache, no-transform");

            if (endpoint.Auth && !IsAuthorized(c)) {
                c.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                RespondJSON(c, new {
                    Error = "Unauthorized."
                });
                return;
            }

            endpoint.Handle(this, c);
        }

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

public void ScanPath(string path) {
            if (Directory.Exists(path)) {
                // Use the directory as "dependency directory" and scan in it.
                if (Directories.Contains(path))
                    // No need to scan the dir if the dir is scanned...
                    return;

                RestoreBackup(path);

                Log($"[ScanPath] Scanning directory {path}");
                Directories.Add(path);
                replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added

                // Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
                string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
                if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
                    Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
                    File.Copy(Thisreplacedembly.Location, xtfPath, true);

                    string dbExt = null;
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
                        dbExt = "pdb";
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
                        dbExt = "mdb";
                    if (dbExt != null)
                        File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);

                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
                    else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);

                }

                ScanPaths(Directory.GetFiles(path));
                return;
            }

            if (File.Exists(path + ".xex")) {
                if (!ExtractedXEX.Contains(path)) {
                    // Remove the original file - let XnaToFna unpack and handle it later.
                    File.Delete(path);
                } else {
                    // XnaToFna will handle the .xex instead.
                }
                return;
            }

            if (path.EndsWith(".xex")) {
                string pathTarget = path.Substring(0, path.Length - 4);
                if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
                    return;

                using (Stream streamXEX = File.OpenRead(path))
                using (BinaryReader reader = new BinaryReader(streamXEX))
                using (Stream streamRAW = File.OpenWrite(pathTarget)) {
                    XEXImageData data = new XEXImageData(reader);

                    int offset = 0;
                    int size = data.m_memorySize;

                    // Check if this file is a PE containing an embedded PE.
                    if (data.m_memorySize > 0x10000) { // One default segment alignment.
                        using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
                        using (BinaryReader mem = new BinaryReader(streamMEM)) {
                            if (mem.ReadUInt32() != 0x00905A4D) // MZ
                                goto WriteRaw;
                            // This is horrible.
                            streamMEM.Seek(0x00000280, SeekOrigin.Begin);
                            if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
                                goto WriteRaw;
                            streamMEM.Seek(0x00000288, SeekOrigin.Begin);
                            mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
                            offset = mem.ReadInt32(); // Virtual offset.
                            // mem.ReadInt32(); // Raw size; Still incorrect.
                            // Let's just write everything...
                            size = data.m_memorySize - offset;
                        }
                    }

                    WriteRaw:
                    streamRAW.Write(data.m_memoryData, offset, size);
                }

                path = pathTarget;
                ExtractedXEX.Add(pathTarget);
            } else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
                return;

            // Check if .dll is CLR replacedembly
            replacedemblyName name;
            try {
                name = replacedemblyName.GetreplacedemblyName(path);
            } catch {
                return;
            }

            ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
            // Don't ReadWrite if the module being read is XnaToFna or a relink target.
            bool isReadWrite =
#if !CECIL0_9
            modReaderParams.ReadWrite =
#endif
                path != Thisreplacedembly.Location &&
                !Mappings.Exists(mappings => name.Name == mappings.Target);
            // Only read debug info if it exists
            if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
                modReaderParams.ReadSymbols = false;
            Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
            ModuleDefinition mod;
            try {
                mod = MonoModExt.ReadModule(path, modReaderParams);
            } catch (Exception e) {
                Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
                return;
            }
            bool add = !isReadWrite || name.Name == ThisreplacedemblyName;

            if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
                // Mono.Cecil can't handle mixed mode replacedemblies.
                Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
                if (MixedDeps == MixedDepAction.Stub) {
                    ModulesToStub.Add(mod);
                    add = true;
                } else {
                    if (MixedDeps == MixedDepAction.Remove) {
                        RemoveDeps.Add(name.Name);
                    }
#if !CECIL0_9
                    mod.Dispose();
#endif
                    return;
                }
            }

            if (add && !isReadWrite) { // XNA replacement
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (name.Name == mapping.Target) {
                        mapping.IsActive = true;
                        mapping.Module = mod;
                        foreach (string from in mapping.Sources) {
                            Log($"[ScanPath] Mapping {from} -> {name.Name}");
                            Modder.RelinkModuleMap[from] = mod;
                        }
                    }
            } else if (!add) {
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
                        add = true;
                        Log($"[ScanPath] XnaToFna-ing {name.Name}");
                        goto BreakMappings;
                    }
            }
            BreakMappings:

            if (add) {
                Modules.Add(mod);
                ModulePaths[mod] = path;
            } else {
#if !CECIL0_9
                mod.Dispose();
#endif
            }

        }

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

public OpCode ShortToLongOp(OpCode op) {
            string name = Enum.GetName(typeof(Code), op.Code);
            if (!name.EndsWith("_S"))
                return op;
            return (OpCode?) typeof(OpCodes).GetField(name.Substring(0, name.Length - 2))?.GetValue(null) ?? op;
        }

19 View Source File : ImageGridMetadata.cs
License : MIT License
Project Creator : 0xC0000054

private static uint GetPropertyValue(string haystack, string propertyName)
        {
            string needle = propertyName + "=\"";

            int valueStartIndex = haystack.IndexOf(needle, StringComparison.Ordinal) + needle.Length;
            int valueEndIndex = haystack.IndexOf('"', valueStartIndex);

            string propertyValue = haystack.Substring(valueStartIndex, valueEndIndex - valueStartIndex);

            return uint.Parse(propertyValue, CultureInfo.InvariantCulture);
        }

19 View Source File : CICPSerializer.cs
License : MIT License
Project Creator : 0xC0000054

private static ushort GetPropertyValue(string haystack, string propertyName)
        {
            string needle = propertyName + "=\"";

            int valueStartIndex = haystack.IndexOf(needle, StringComparison.Ordinal) + needle.Length;
            int valueEndIndex = haystack.IndexOf('"', valueStartIndex);

            string propertyValue = haystack.Substring(valueStartIndex, valueEndIndex - valueStartIndex);

            return ushort.Parse(propertyValue, CultureInfo.InvariantCulture);
        }

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

[Test]
        public void BasicTest()
        {
            TestFileSystem fileSystem = new TestFileSystem();

            fileSystem.AddFile("A\\table1.cs", TestTable1Text);

            var generated = ExistingCodeExplorer
                .EnumerateTableDescriptorsModelAttributes("A", fileSystem)
                .ParseAttribute(true)
                .Createreplacedysis()
                .Select(meta=> ModelClreplacedGenerator.Generate(meta, "Org", "", true, fileSystem, out _).SyntaxTree)
                .ToList();

            var trees = new List<SyntaxTree>();

            foreach (var syntaxTree in generated)
            {
                trees.Add(CSharpSyntaxTree.ParseText(syntaxTree.ToString()));
            }

            trees.Add(CSharpSyntaxTree.ParseText(TestTable1Text));

            var compilation = CSharpCompilation.Create("SqModels",
                trees,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable)); 

            compilation = compilation.AddReferences(
                MetadataReference.CreateFromFile(replacedembly.Load("netstandard, Version=2.0.0.0").Location),
                MetadataReference.CreateFromFile(typeof(object).replacedembly.GetreplacedemblyLocation()),
                MetadataReference.CreateFromFile(replacedembly
                    .Load("System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
                    .Location),
                MetadataReference.CreateFromFile(typeof(SqQueryBuilder).replacedembly.GetreplacedemblyLocation()));

            MemoryStream ms = new MemoryStream();

            var emitResult = compilation.Emit(ms);
            if (!emitResult.Success)
            {
                Diagnostic first = emitResult.Diagnostics.First();

                var sourceCode = first.Location.SourceTree?.ToString();
                var s = sourceCode?.Substring(first.Location.SourceSpan.Start, first.Location.SourceSpan.Length);
                Console.WriteLine(sourceCode);
                replacedert.Fail(first.GetMessage()+ (string.IsNullOrEmpty(s)?null:$" \"{s}\""));
            }

            var replacedembly = replacedembly.Load(ms.ToArray());

            var allTypes = replacedembly.GetTypes();

            replacedert.AreEqual(21, allTypes.Length);
        }

19 View Source File : RawFileType.cs
License : MIT License
Project Creator : 0xC0000054

private static string RemoveCommentsAndWhiteSpace(string line)
        {
            int commentIndex = line.IndexOf(";", StringComparison.Ordinal);
            if (commentIndex >= 0)
            {
                return line.Substring(0, commentIndex).Trim();
            }
            else
            {
                return line.Trim();
            }
        }

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

static bool TryParseToken(string value, out uint tokenLo, out uint tokenHi) {
			int index = value.IndexOf('-');
			if (index >= 0) {
				var lo = value.Substring(0, index);
				var hi = value.Substring(index + 1);
				if (TryParseToken(lo, out tokenLo) && TryParseToken(hi, out tokenHi))
					return true;
			}
			else {
				if (TryParseToken(value, out tokenLo)) {
					tokenHi = tokenLo;
					return true;
				}
			}

			tokenLo = 0;
			tokenHi = 0;
			return false;
		}

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

public string GetFilename(uint token, string name) {
			string candidate;
			switch (filenameFormat) {
			case FilenameFormat.MemberName:
				candidate = name;
				break;

			case FilenameFormat.TokenMemberName:
				candidate = token.ToString("X8") + "_" + name;
				break;

			case FilenameFormat.Token:
				candidate = token.ToString("X8");
				break;

			default:
				throw new ArgumentOutOfRangeException(nameof(filenameFormat));
			}

			if (candidate == string.Empty)
				candidate = "<UNKNOWN>";
			candidate = ReplaceInvalidFilenameChars(candidate);
			if (candidate.Length > MAX_NAME_LEN)
				candidate = candidate.Substring(0, MAX_NAME_LEN) + "-";
			if (!usedFilenames.Add(candidate)) {
				for (int i = 1; i < int.MaxValue; i++) {
					var newCand = candidate + "_" + i.ToString();
					if (usedFilenames.Add(newCand)) {
						candidate = newCand;
						break;
					}
				}
			}
			return Path.Combine(outputDir, candidate + extension);
		}

19 View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Usage();
                return;
            }

            var arguments = new Dictionary<string, string>();
            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
            }

            string username = "";
            string preplacedword = "";

            if (arguments.ContainsKey("username"))
            {
                if (!arguments.ContainsKey("preplacedword"))
                {
                    Usage();
                    return;
                }
                else
                {
                    username = arguments["username"];
                    preplacedword = arguments["preplacedword"];
                }
            }
            if (arguments.ContainsKey("preplacedword") && !arguments.ContainsKey("username"))
            {
                Usage();
                return;
            }
            if (arguments.ContainsKey("computername"))
            {
                string[] computerNames = arguments["computername"].Split(',');
                string eventName = "Debug";
                string location = "local";
                string droplocation = @"C:\Windows\Temp";
                string wnamespace = "root\\CIMv2";
                string filename = string.Empty;
                string valuename = string.Empty;
                string keypath = string.Empty;
                string clreplacedname = string.Empty;
                foreach (string computerName in computerNames)
                {
                    if (arguments.ContainsKey("eventname"))
                    {
                        eventName = arguments["eventname"];
                    }
                    if (arguments.ContainsKey("location"))
                    {
                        location = arguments["location"];
                    }
                    if (arguments.ContainsKey("droplocation"))
                    {
                        droplocation = arguments["droplocation"];
                    }
                    if (arguments.ContainsKey("filename"))
                    {
                        filename = arguments["filename"];
                    }
                    if (arguments.ContainsKey("clreplacedname"))
                    {
                        clreplacedname = arguments["clreplacedname"];
                    }
                    if (arguments.ContainsKey("keypath"))
                    {
                        keypath = arguments["keypath"];
                    }
                    if (arguments.ContainsKey("valuename"))
                    {
                        valuename = arguments["valuename"];
                    }
                    if (arguments.ContainsKey("wminamespace"))
                    {
                        wnamespace = arguments["wminamespace"];
                    }

                    if (arguments.ContainsKey("writetype"))
                    {
                        if (arguments["writetype"].ToLower() == "wmi")
                        {
                            GetFileContent(location, droplocation, filename, "flat");
                            WriteToFileWMI(computerName, eventName, username, preplacedword);
                        }
                        else if (arguments["writetype"].ToLower() == "smb")
                        {
                            WriteToFileSMB(computerName, droplocation, filename, location);
                        }
                        else if(arguments["writetype"].ToLower() == "registry")
                        {
                            if (valuename == string.Empty)
                            {
                                Console.WriteLine("[-] Valuename is required");
                                return;
                            }
                            GetFileContent(location, droplocation, filename, "nonflat");
                            WriteToRegKey(computerName, username, preplacedword, keypath, valuename);
                        }
                        else if (arguments["writetype"].ToLower() == "wmiclreplaced")
                        {
                            GetFileContent(location, droplocation, filename, "nonflat");
                            WriteToWMIClreplaced(computerName, username, preplacedword, wnamespace, clreplacedname);
                        }
                        else if (arguments["writetype"].ToLower() == "removewmiclreplaced")
                        {
                            RemoveWMIClreplaced(computerName, username, preplacedword, wnamespace, clreplacedname);
                        }
                        else if (arguments["writetype"].ToLower() == "removeregkey")
                        {
                            RemoveRegValue(computerName, username, preplacedword, keypath, valuename);
                        }
                        else
                        {
                            Usage();
                            return;
                        }
                    }
                    else
                    {
                        Usage();
                    }
                }
            }
            else
            {
                Usage();
                return;
            }
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void Main(string[] args)
        {
            AppDomain.CurrentDomain.replacedemblyResolve += (sender, argtwo) => {
                replacedembly thisreplacedembly = replacedembly.GetEntryreplacedembly();
                String resourceName = string.Format("SharpRDP.{0}.dll.bin",
                    new replacedemblyName(argtwo.Name).Name);
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                using (var rs = replacedembly.GetManifestResourceStream(resourceName))
                using (var zs = new DeflateStream(rs, CompressionMode.Decompress))
                using (var ms = new MemoryStream())
                {
                    zs.CopyTo(ms);
                    return replacedembly.Load(ms.ToArray());
                }
            };

            var arguments = new Dictionary<string, string>();
            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
            }

            string username = string.Empty;
            string domain = string.Empty;
            string preplacedword = string.Empty;
            string command = string.Empty;
            string execElevated = string.Empty;
            string execw = "";
            bool connectdrive = false;
            bool takeover = false;
            bool nla = false;
            
            if (arguments.ContainsKey("username"))
            {
                if (!arguments.ContainsKey("preplacedword"))
                {
                    Console.WriteLine("[X] Error: A preplacedword is required");
                    return;
                }
                else
                {
                    if (arguments["username"].Contains("\\"))
                    {
                        string[] tmp = arguments["username"].Split('\\');
                        domain = tmp[0];
                        username = tmp[1];
                    }
                    else
                    {
                        domain = ".";
                        username = arguments["username"];
                    }
                    preplacedword = arguments["preplacedword"];
                }
            }

            if (arguments.ContainsKey("preplacedword") && !arguments.ContainsKey("username"))
            {
                Console.WriteLine("[X] Error: A username is required");
                return;
            }
            if ((arguments.ContainsKey("computername")) && (arguments.ContainsKey("command")))
            {
                Client rdpconn = new Client();
                command = arguments["command"];
                if (arguments.ContainsKey("exec"))
                {
                    if (arguments["exec"].ToLower() == "cmd")
                    {
                        execw = "cmd";
                    }
                    else if (arguments["exec"].ToLower() == "powershell" || arguments["exec"].ToLower() == "ps")
                    {
                        execw = "powershell";
                    }
                }
                if (arguments.ContainsKey("elevated"))
                {
                    if(arguments["elevated"].ToLower() == "true" || arguments["elevated"].ToLower() == "win+r" || arguments["elevated"].ToLower() == "winr")
                    {
                        execElevated = "winr";
                    }
                    else if(arguments["elevated"].ToLower() == "taskmgr" || arguments["elevated"].ToLower() == "taskmanager")
                    {
                        execElevated = "taskmgr";
                    }
                    else
                    {
                        execElevated = string.Empty;
                    }
                }
                if (arguments.ContainsKey("connectdrive"))
                {
                    if(arguments["connectdrive"].ToLower() == "true")
                    {
                        connectdrive = true;
                    }
                }
                if (arguments.ContainsKey("takeover"))
                {
                    if (arguments["takeover"].ToLower() == "true")
                    {
                        takeover = true;
                    }
                }
                if (arguments.ContainsKey("nla"))
                {
                    if (arguments["nla"].ToLower() == "true")
                    {
                        nla = true;
                    }
                }
                string[] computerNames = arguments["computername"].Split(',');
                foreach (string server in computerNames)
                {
                    rdpconn.CreateRdpConnection(server, username, domain, preplacedword, command, execw, execElevated, connectdrive, takeover, nla);
                }
            }
            else
            {
                HowTo();
                return;
            }

        }

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

static string MakeClrmdTypeName(string name) {
			if (name.Length > 0 && char.IsDigit(name[name.Length - 1])) {
				int index = name.LastIndexOf('`');
				if (index >= 0)
					return name.Substring(0, index);
			}
			return name;
		}

19 View Source File : SQLite.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3

public bool ReadTable(string TableName)
        {
            int index = -1;
            int length = this.master_table_entries.Length - 1;
            for (int i = 0; i <= length; i++)
            {
                if (this.master_table_entries[i].item_name.ToLower().CompareTo(TableName.ToLower()) == 0)
                {
                    index = i;
                    break;
                }
            }
            if (index == -1)
            {
                return false;
            }
            string[] strArray = this.master_table_entries[index].sql_statement.Substring(this.master_table_entries[index].sql_statement.IndexOf("(") + 1).Split(new char[] { ',' });
            int num6 = strArray.Length - 1;
            for (int j = 0; j <= num6; j++)
            {
                strArray[j] = (strArray[j]).TrimStart();
                int num4 = strArray[j].IndexOf(" ");
                if (num4 > 0)
                {
                    strArray[j] = strArray[j].Substring(0, num4);
                }
                if (strArray[j].IndexOf("UNIQUE") == 0)
                {
                    break;
                }
                this.field_names = (string[])Utils.CopyArray((Array)this.field_names, new string[j + 1]);
                this.field_names[j] = strArray[j];
            }
            return this.ReadTableFromOffset((ulong)((this.master_table_entries[index].root_num - 1L) * this.page_size));
        }

19 View Source File : Program.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 0xthirteen

static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                HowTo();
                return;
            }
            var arguments = new Dictionary<string, string>();
            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
            }

            if (arguments.ContainsKey("command"))
            {
                CleanSingle(arguments["command"]);
            }
            else if (args[0].ToLower() == "clearall")
            {
                Clereplacedl();
            }
            else if (args[0].ToLower() == "query")
            {
                QueryReg();
            }
            else
            {
                HowTo();
                return;
            }
        }

19 View Source File : ExcelDCOM.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void Main(string[] args)
        {
            var arguments = new Dictionary<string, string>();
            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
            }

            if(!arguments.ContainsKey("computername"))
            {
                Console.WriteLine("[-] Error: computername arg is required");
                return;
            }
            else
            {
                string arch = "x86";
                string target = arguments["computername"];
                if (arguments.ContainsKey("arch"))
                {
                    if(arguments["arch"].ToLower() == "x64" || arguments["arch"] == "64")
                    {
                        arch = "x64";
                    }
                }
                ExecExcelDCOM(target, arch);
            }
        }

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

public static byte[] ToByteArray(this string hexString)
        {
            if (hexString == null)
                return null;

            if (hexString.Length == 0)
                return new byte[0];

            if (hexString.Length % 2 != 0)
                throw new FormatException("Not a valid hex string");

            var result = new byte[hexString.Length / 2];
            for (int i = 0; i < hexString.Length; i += 2)
                result[i / 2] = byte.Parse(hexString.Substring(i, 2), NumberStyles.HexNumber);
            return result;
        }

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

public static byte[] AsBytes(this string hex)
        {
            if (hex == null)
                return null;

            if (hex.Length == 0)
                return new byte[0];

            if (hex.Length %2 == 1)
                throw new InvalidOperationException($"Odd hex string length of {hex.Length}");

            var result = new byte[hex.Length % 2];
            for (int i = 0, j = 0; i < hex.Length; i += 2, j++)
                result[j] = byte.Parse(hex.Substring(i, 2), NumberStyles.HexNumber);
            return result;
        }

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

private static TypeSyntax GenerateType(Type type)
        {
            if (!type.IsGenericType)
                return GenerateQualifiedNameSyntax(type);


            var list = new List<SyntaxNodeOrToken>();
            foreach (var genericType in type.GetGenericArguments())
            {
                list.Add(genericType.IsGenericType ? GenerateType(genericType) : GenerateQualifiedNameSyntax(genericType.FullName));
                list.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
            }
            var typeArgumentList = SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList<TypeSyntax>(list.Take(list.Count - 1)));
            //if (type.Namespace == typeof(Task).Namespace)
            return SyntaxFactory.GenericName(type.Name.Substring(0, type.Name.IndexOf('`'))).WithTypeArgumentList(typeArgumentList);
            //return SyntaxFactory.GenericName(type.FullName?.Substring(0, type.FullName.IndexOf('`'))).WithTypeArgumentList(typeArgumentList);
        }

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

public static string Trim(this string str, int maxLength)
        {
            const int minSaneLimit = 4;

            if (maxLength < minSaneLimit)
                throw new ArgumentException("Argument cannot be less than " + minSaneLimit, nameof(maxLength));

            if (string.IsNullOrEmpty(str))
                return str;

            if (str.Length > maxLength)
                return str.Substring(0, maxLength - 3) + "...";

            return str;
        }

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

public static string Truncate(this string str, int maxLength)
        {
            if (maxLength < 1)
                throw new ArgumentException("Argument must be positive, but was " + maxLength, nameof(maxLength));

            if (string.IsNullOrEmpty(str) || str.Length <= maxLength)
                return str;

            return str.Substring(0, maxLength);
        }

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

internal static string Trim(this string str, int maxLength)
        {
            if (string.IsNullOrEmpty(str))
                return str;

            const string suffix = "…";
            if (str.Length > maxLength)
            {
                if (maxLength > suffix.Length)
                    return str.Substring(0, maxLength - suffix.Length) + suffix;

                return str.Substring(0, maxLength);
            }

            return str;
        }

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

public static byte[] AsBytes(this string hexString)
        {
            if (hexString == null)
                return null;

            if (hexString.Length == 0)
                return Array.Empty<byte>();

            if (hexString.Length%2 == 1)
                throw new ArgumentException("Hex string cannot have an odd number of characters");

            var result = new byte[hexString.Length / 2];
            for (int ri = 0, si = 0; ri < result.Length; ri++, si += 2)
                result[ri] = byte.Parse(hexString.Substring(si, 2), NumberStyles.HexNumber);
            return result;
        }

19 View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResovleOperator(string text)
        {
            var operators = new string[] { "!", "*", "/", "%", "+", "-", "<", ">", "<=", ">=", "==", "!=", "&&", "||" };
            for (int i = 0; i < text.Length - 1; i++)
            {
                var opt1 = text[i].ToString();
                var opt2 = text.Substring(i, 2);
                if (operators.Contains(opt2))
                {
                    return opt2;
                }
                else if(operators.Contains(opt1))
                {
                    return opt1;
                }
            }
            throw new Exception("resolve operator eroor");
        }

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

public static byte[] Hex2Bytes(this string s)
    {
        if (s.IsNull())
            return null;
        var bytes = new byte[s.Length / 2];

        for (int x = 0; x < s.Length / 2; x++)
        {
            int i = (Convert.ToInt32(s.Substring(x * 2, 2), 16));
            bytes[x] = (byte)i;
        }

        return bytes;
    }

19 View Source File : GeneratorClass.cs
License : MIT License
Project Creator : 188867052

private static string GetCrefNamespace(string cref, string @namespace)
        {
            IList<string> sameString = new List<string>();
            var splitNamespace = @namespace.Split('.');
            var splitCref = cref.Split('.');
            int minLength = Math.Min(splitNamespace.Length, splitCref.Length);
            for (int i = 0; i < minLength; i++)
            {
                if (splitCref[i] == splitNamespace[i])
                {
                    sameString.Add(splitCref[i]);
                }
                else
                {
                    break;
                }
            }

            cref = cref.Substring(string.Join('.', sameString).Length + 1);
            return cref;
        }

19 View Source File : StringInputDataSource.cs
License : MIT License
Project Creator : 1996v

public string GetCurrentSegmentString()
        {
            if (curIsMapKey)
            {
                return _str.Substring(mapKeyIndex, mapKeyLength);
            }
            else
            {
                return "$" + aryIndexNumber.ToString();
            }
        }

19 View Source File : ConditionTaskForm.cs
License : Apache License 2.0
Project Creator : 214175590

public void RenderConditionFinish(int index)
        {
            string condition = cmdShell.Condition;
            string[] items = condition.Split(';');            
            if (items.Length >= index)
            {
                string[] arrs = items[index - 1].Split(',');
                ConditionItem ci = null;
                SpringBootMonitorItem spring = null;
                TomcatMonitorItem tomcat = null;
                NginxMonitorItem nginx = null;
                string uuid = "", itemUuid = "";
                int itemIndex = 0;
                SkinComboBox combo = null;
                if (index == 1)
                {
                    combo = scb_condition1;
                }
                else if (index == 2)
                {
                    combo = scb_condition2;
                }
                else if (index == 3)
                {
                    combo = scb_condition3;
                }
                foreach (var item in combo.Items)
                {
                    ci = (ConditionItem)item;
                    if(ci.Index == 0){
                        spring = (SpringBootMonitorItem) ci.Item;
                        uuid = spring.Uuid;
                        itemIndex = spring.Index;
                    }
                    else if (ci.Index == 1)
                    {
                        tomcat = (TomcatMonitorItem)ci.Item;
                        uuid = spring.Uuid;
                        itemIndex = spring.Index;
                    }
                    else if (ci.Index == 2)
                    {
                        nginx = (NginxMonitorItem)ci.Item;
                        uuid = spring.Uuid;
                        itemIndex = spring.Index;
                    }

                    if (index == 1)
                    {
                        itemUuid = arrs[0];
                    }
                    else
                    {
                        itemUuid = arrs[0].Substring(1);
                    }
                    if (uuid == itemUuid)
                    {
                        combo.SelectedItem = item;
                        InitConditionStatus(index, itemIndex);
                        break;
                    }
                }
                // ========================
                if (index == 1)
                {
                    scb_status1.SelectedIndex = arrs[1] == "Y" ? 1 : 0;
                    if (items.Length >= 2)
                    {
                        if (items[index].Substring(0, 1) == "&")
                        {
                            rb_q1.Checked = true;
                        }
                        else
                        {
                            rb_h1.Checked = true;
                        }
                        InitCondition(2, new RenderFinishDelegate(RenderConditionFinish));
                    }
                }
                else if (index == 2)
                {
                    scb_status2.SelectedIndex = arrs[1] == "Y" ? 1 : 0;
                    if (items.Length >= 3)
                    {
                        if (items[index].Substring(0, 1) == "&")
                        {
                            rb_q2.Checked = true;
                        }
                        else
                        {
                            rb_h2.Checked = true;
                        }
                        InitCondition(3, new RenderFinishDelegate(RenderConditionFinish));
                    }
                }
                else if (index == 3)
                {
                    scb_status3.SelectedIndex = arrs[1] == "Y" ? 1 : 0;
                }
            }
        }

19 View Source File : CustomScriptForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void CustomScriptForm_Load(object sender, EventArgs e)
        {
            if (index != 999999 && index < config.ShellList.Count)
            {
                string shell = config.ShellList[index];
                if(shell.EndsWith("&")){
                    shell = shell.Substring(0, shell.Length - 1);
                    cb_cr.Checked = true;
                }
                stb_shell.Text = shell;
            }
        }

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

private static string GetScope(string name)
        {
            var indexOfLastPeriod = name.LastIndexOf('.');
            if (indexOfLastPeriod != name.Length - 1)
            {
                return name.Substring(0, indexOfLastPeriod);
            }
            return name;
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : 1y0n

private byte string_to_int(string str)
        {
            string temp = str.Substring(str.Length - 2, 2);
            int hex = int.Parse(temp, System.Globalization.NumberStyles.HexNumber);
            return BitConverter.GetBytes(hex)[0];
        }

19 View Source File : Core.cs
License : MIT License
Project Creator : 1y0n

public static string XOR_C(string format, string raw)
        {
            string result = "";
            string[] shellcode_array = raw.Split(',');
            string[] temp = new string[shellcode_array.Length];
            int j = 234;
            int add = 12;
            for (int i = 0; i < shellcode_array.Length; i++)
            {
                temp[i] = string.Format("{0:x2}", string_to_int(shellcode_array[i]) ^ 123 ^ j);
                temp[i] = "0x" + temp[i].Substring(temp[i].Length - 2, 2);
                j += add;
            }
            result = string.Join(",", temp);
            //转换一下格式
            if (format == "c")
            {
                result = result.Replace("0x", @"\x").Replace(",", "");
            }
            return result;
        }

19 View Source File : Core.cs
License : MIT License
Project Creator : 1y0n

public static byte string_to_int(string str)
        {
            string temp = str.Substring(str.Length - 2, 2);
            int hex = int.Parse(temp, System.Globalization.NumberStyles.HexNumber);
            return BitConverter.GetBytes(hex)[0];
        }

19 View Source File : Core.cs
License : MIT License
Project Creator : 1y0n

public static bool C_Compiler(string arch, string source_path, string save_path, bool res=false)
        {
            string arch_cmd = " -m" + arch.Substring(0, 2);
            string compile_cmd = @"gcc -mwindows -o """ + save_path + @"""" + arch_cmd + @" """ + source_path + @"""";
            if (res)
            {
                compile_cmd += @" C:\\Windows\\Temp\\Yanri_res.o";
            }
            //System.IO.File.WriteAllText(@"C:\\Users\\www1y\\Desktop\\cmd1.txt", compile_cmd);
            if (!Common.Execute_Cmd(compile_cmd).Contains("rror:"))
            {
                return true;
            }
            return false;
        }

19 View Source File : StringExtensionMethods.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static string BeforeLast(this string str, string sub)
    {
        var idx = str.LastIndexOf(sub);
        return idx < 0 ? "" : str.Substring(0, idx);
    }

19 View Source File : StringExtensionMethods.cs
License : MIT License
Project Creator : 1ZouLTReX1

public static string BeforeFirst(this string str, string sub)
    {
        var idx = str.IndexOf(sub);
        return idx < 0 ? "" : str.Substring(0, idx);
    }

19 View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590

void SrvPath_TextChanged(object sender, EventArgs e)
        {
            string path = stb_ice_srvpath.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                string appname = stb_ice_appname.Text;

                if (!string.IsNullOrWhiteSpace(appname) && string.IsNullOrWhiteSpace(stb_ice_ports.Text))
                {
                    try
                    {
                        if (get_ice_port_run)
                        {
                            return;
                        }
                        get_ice_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = string.Format("{0}config/{1}.xml", path, appname);
                        string targetxml = MainForm.TEMP_DIR + string.Format("srv-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                        targetxml = targetxml.Replace("\\", "/");
                        parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                        ThreadPool.QueueUserWorkItem((a) =>
                        {
                            Thread.Sleep(500);

                            List<Hashtable> list = YSTools.YSXml.readXml(targetxml, "icegrid");
                            if (list != null && list.Count > 0)
                            {
                                List<Hashtable> appList = null, nodeList = null;
                                List<Hashtable> serverList = null;
                                string ports = "", nodeName = "", serverName = "";
                                foreach (Hashtable one in list)
                                {
                                    if (one["NodeName"].ToString() == "application")
                                    {
                                        appList = (List<Hashtable>)one["ChildList"];
                                        foreach (Hashtable two in appList)
                                        {
                                            if (two["NodeName"].ToString() == "node")
                                            {
                                                nodeName = two["name"].ToString();
                                                nodeList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in nodeList)
                                                {
                                                    if (four["NodeName"].ToString() == "server-instance")
                                                    {
                                                        ports += "," + four["serverport"].ToString();
                                                    }
                                                }

                                            }

                                            if (two["NodeName"].ToString() == "server-template")
                                            {
                                                serverList = (List<Hashtable>)two["ChildList"];
                                                foreach (Hashtable four in serverList)
                                                {
                                                    if (four["NodeName"].ToString() == "icebox")
                                                    {
                                                        serverName = four["id"].ToString();
                                                        serverName = serverName.Substring(0, serverName.IndexOf("$")) + "1";
                                                        break;
                                                    }
                                                }
                                            }

                                            if (ports != "")
                                            {
                                                break;
                                            }
                                        }
                                    }
                                }
                                                                
                                stb_ice_ports.BeginInvoke((MethodInvoker)delegate()
                                {
                                    stb_ice_servername.Text = serverName;
                                    stb_ice_ports.Text = ports == "" ? "8082" : ports.Substring(1);
                                });
                            }
                            get_ice_port_run = false;

                            File.Delete(targetxml);
                        });
                    }
                    catch { }
                }
            }
        }

See More Examples