string.EndsWith(string)

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

6314 Examples 7

19 Source : Helper.cs
with MIT License
from 0ffffffffh

public static Dictionary<string, string> ParseOptions(string s)
        {
            Dictionary<string, string> argDict = new Dictionary<string, string>();

            string tmp = "";
            bool putTmp = false;
            string opt = null;

            if (string.IsNullOrEmpty(s))
                return argDict;

            string[] breaks = s.Split(' ');

            foreach (string item in breaks)
            {
                if (item.StartsWith("\""))
                {
                    tmp = item;
                    putTmp = true;
                }
                else if (item.EndsWith("\""))
                {
                    putTmp = false;

                    if (opt != null)
                    {
                        argDict.Add(opt, tmp + item);
                        opt = null;
                    }
                    else
                        argDict.Add(tmp + item, "");

                    tmp = "";
                }
                else
                {
                    if (putTmp)
                        tmp += item;
                    else
                    {
                        var value = item.Trim();

                        if (value.Length > 0)
                        {
                            if (value.StartsWith("-"))
                            {
                                if (opt != null)
                                {
                                    argDict.Add(opt, "");
                                }

                                opt = value;

                            }
                            else
                            {
                                if (opt != null)
                                {
                                    argDict.Add(opt, value);
                                    opt = null;
                                }
                                else
                                    argDict.Add(value, "");
                            }
                        }
                    }
                }

            }

            if (opt != null)
                argDict.Add(opt, "");

            breaks = null;

            return argDict;
        }

19 Source : Frontend.cs
with MIT License
from 0x0ade

public Stream? OpenContent(string path, out string pathNew, out DateTime? lastMod, out string? contentType) {
            pathNew = path;

            try {
                string dir = Path.GetFullPath(Settings.ContentRoot);
                string pathFS = Path.GetFullPath(Path.Combine(dir, path));
                if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
                    lastMod = File.GetLastWriteTimeUtc(pathFS);
                    contentType = GetContentType(pathFS);
                    return File.OpenRead(pathFS);
                }
            } catch {
            }

#if DEBUG
            try {
                string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "Content"));
                string pathFS = Path.GetFullPath(Path.Combine(dir, path));
                if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
                    lastMod = File.GetLastWriteTimeUtc(pathFS);
                    contentType = GetContentType(pathFS);
                    return File.OpenRead(pathFS);
                }
            } catch {
            }

            try {
                string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "CelesteNet.Server.FrontendModule", "Content"));
                string pathFS = Path.GetFullPath(Path.Combine(dir, path));
                if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
                    lastMod = File.GetLastWriteTimeUtc(pathFS);
                    contentType = GetContentType(pathFS);
                    return File.OpenRead(pathFS);
                }
            } catch {
            }
#endif

            if (!path.EndsWith("/index.html")) {
                path = path.EndsWith("/") ? path : (path + "/");
                Stream? index = OpenContent(path + "index.html", out _, out lastMod, out contentType);
                if (index != null) {
                    pathNew = path;
                    return index;
                }
            }

            lastMod = null;
            contentType = GetContentType(path);
            return typeof(CelesteNetServer).replacedembly.GetManifestResourceStream("Celeste.Mod.CelesteNet.Server.Content." + path.Replace("/", "."));
        }

19 Source : Program.cs
with MIT License
from 0x0ade

static void Main(string[] args) {
            // Required for the relative extra paths to work properly.
            if (!File.Exists("MonoMod.RuntimeDetour.dll"))
                Environment.CurrentDirectory = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location);

            string inputDir, outputDir;
            if (args.Length != 2 ||
                !Directory.Exists(inputDir = args[0]) ||
                !Directory.Exists(outputDir = args[1])) {
                Console.Error.WriteLine("Usage: inputdir outputdir");
                return;
            }

            // Check that the files exist.
            if (!VerifyFile(out string inputXNA, inputDir, "Terraria.XNA.exe"))
                return;
            if (!VerifyFile(out string inputFNA, inputDir, "Terraria.FNA.exe"))
                return;

            // Strip or copy.
            foreach (string path in Directory.GetFiles(inputDir)) {
                if (!path.EndsWith(".exe") && !path.EndsWith(".dll")) {
                    Console.WriteLine($"Copying: {path}");
                    File.Copy(path, Path.Combine(outputDir, Path.GetFileName(path)));
                    continue;
                }

                Console.WriteLine($"Stripping: {path}");
                Stripper.Strip(path);
            }

            // Generate hooks.
            string hooksXNA = Path.Combine(outputDir, "Windows.Pre.dll");
            string hooksFNA = Path.Combine(outputDir, "Mono.Pre.dll");
            GenHooks(inputXNA, hooksXNA);
            GenHooks(inputFNA, hooksFNA);

            // Merge generated .dlls and MonoMod into one .dll per environment.
            string[] extrasMod = {
                "TerrariaHooks.dll",
                "MonoMod.exe",
                "MonoMod.RuntimeDetour.dll",
                "MonoMod.Utils.dll"
            };
            Repack(hooksXNA, extrasMod, Path.Combine(outputDir, "Windows.dll"), "TerrariaHooks.dll");
            File.Delete(hooksXNA);
            Repack(hooksFNA, extrasMod, Path.Combine(outputDir, "Mono.dll"), "TerrariaHooks.dll");
            File.Delete(hooksFNA);
        }

19 Source : TerrariaHooksManager.cs
with MIT License
from 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 Source : XnaToFnaUtil.cs
with zlib License
from 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 Source : XnaToFnaUtil.Processor.cs
with zlib License
from 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 Source : XnaToFnaUtil.Processor.cs
with zlib License
from 0x0ade

public OpCode LongToShortOp(OpCode op) {
            string name = Enum.GetName(typeof(Code), op.Code);
            if (name.EndsWith("_S"))
                return op;
            return (OpCode?) typeof(OpCodes).GetField(name + "_S")?.GetValue(null) ?? op;
        }

19 Source : BaseDapper.Async.cs
with MIT License
from 1100100

public virtual async Task<PageResult<TReturn>> QueryPageAsync<TReturn>(string countSql, string dataSql, int pageindex, int pageSize, object param = null, int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });

            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return await CommandExecuteAsync(enableCache, async () =>
            {
                using var multi = await Conn.Value.QueryMultipleAsync(sql, pars, Transaction, commandTimeout);
                var count = (await multi.ReadAsync<long>()).FirstOrDefault();
                var data = (await multi.ReadAsync<TReturn>()).ToList();
                var result = new PageResult<TReturn>
                {
                    TotalCount = count,
                    Page = pageindex,
                    PageSize = pageSize,
                    Contents = data
                };
                result.TotalPage = result.TotalCount % pageSize == 0
                    ? result.TotalCount / pageSize
                    : result.TotalCount / pageSize + 1;
                if (result.Page > result.TotalPage)
                    result.Page = result.TotalPage;
                return result;
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);
        }

19 Source : BaseDapper.Async.cs
with MIT License
from 1100100

public virtual async Task<PageResult<dynamic>> QueryPageAsync(string countSql, string dataSql, int pageindex, int pageSize, object param = null,
            int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });
            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return await CommandExecuteAsync(enableCache, async () =>
            {
                using var multi = await Conn.Value.QueryMultipleAsync(sql, pars, Transaction, commandTimeout);
                var count = (await multi.ReadAsync<long>()).FirstOrDefault();
                var data = (await multi.ReadAsync()).ToList();
                var result = new PageResult<dynamic>
                {
                    TotalCount = count,
                    Page = pageindex,
                    PageSize = pageSize,
                    Contents = data
                };
                result.TotalPage = result.TotalCount % pageSize == 0
                    ? result.TotalCount / pageSize
                    : result.TotalCount / pageSize + 1;
                if (result.Page > result.TotalPage)
                    result.Page = result.TotalPage;
                return result;
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);

        }

19 Source : BaseDapper.cs
with MIT License
from 1100100

public virtual PageResult<TReturn> QueryPage<TReturn>(string countSql, string dataSql, int pageindex, int pageSize, object param = null, int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });
            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return CommandExecute(enableCache, () =>
            {
                using var multi = Conn.Value.QueryMultiple(sql, pars, Transaction, commandTimeout);
                var count = multi.Read<long>().FirstOrDefault();
                var data = multi.Read<TReturn>().ToList();
                var result = new PageResult<TReturn>
                {
                    TotalCount = count,
                    Page = pageindex,
                    PageSize = pageSize,
                    Contents = data
                };
                result.TotalPage = result.TotalCount % pageSize == 0
                    ? result.TotalCount / pageSize
                    : result.TotalCount / pageSize + 1;
                if (result.Page > result.TotalPage)
                    result.Page = result.TotalPage;
                return result;
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);
        }

19 Source : BaseDapper.cs
with MIT License
from 1100100

public virtual PageResult<dynamic> QueryPage(string countSql, string dataSql, int pageindex, int pageSize, object param = null,
            int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });
            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return CommandExecute(enableCache, () =>
            {
                using var multi = Conn.Value.QueryMultiple(sql, pars, Transaction, commandTimeout);
                var count = multi.Read<long>().FirstOrDefault();
                var data = multi.Read().ToList();
                var result = new PageResult<dynamic>
                {
                    TotalCount = count,
                    Page = pageindex,
                    PageSize = pageSize,
                    Contents = data
                };
                result.TotalPage = result.TotalCount % pageSize == 0
                    ? result.TotalCount / pageSize
                    : result.TotalCount / pageSize + 1;
                if (result.Page > result.TotalPage)
                    result.Page = result.TotalPage;
                return result;
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);

        }

19 Source : MsSqlDapper.cs
with MIT License
from 1100100

public override async Task<PageResult<TReturn>> QueryPageAsync<TReturn>(string countSql, string dataSql, int pageindex, int pageSize, object param = null, int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });

            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return await CommandExecuteAsync(enableCache, async () =>
            {
                using (var multi = await Conn.Value.QueryMultipleAsync(sql, pars, Transaction, commandTimeout))
                {
                    var count = (await multi.ReadAsync<int>()).FirstOrDefault();
                    var data = (await multi.ReadAsync<TReturn>()).ToList();
                    var result = new PageResult<TReturn>
                    {
                        TotalCount = count,
                        Page = pageindex,
                        PageSize = pageSize,
                        Contents = data
                    };
                    result.TotalPage = result.TotalCount % pageSize == 0
                        ? result.TotalCount / pageSize
                        : result.TotalCount / pageSize + 1;
                    if (result.Page > result.TotalPage)
                        result.Page = result.TotalPage;
                    return result;
                }
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);
        }

19 Source : MsSqlDapper.cs
with MIT License
from 1100100

public override async Task<PageResult<dynamic>> QueryPageAsync(string countSql, string dataSql, int pageindex, int pageSize, object param = null,
            int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });
            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return await CommandExecuteAsync(enableCache, async () =>
            {
                using (var multi = await Conn.Value.QueryMultipleAsync(sql, pars, Transaction, commandTimeout))
                {
                    var count = (await multi.ReadAsync<int>()).FirstOrDefault();
                    var data = (await multi.ReadAsync()).ToList();
                    var result = new PageResult<dynamic>
                    {
                        TotalCount = count,
                        Page = pageindex,
                        PageSize = pageSize,
                        Contents = data
                    };
                    result.TotalPage = result.TotalCount % pageSize == 0
                        ? result.TotalCount / pageSize
                        : result.TotalCount / pageSize + 1;
                    if (result.Page > result.TotalPage)
                        result.Page = result.TotalPage;
                    return result;
                }
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);

        }

19 Source : MsSqlDapper.cs
with MIT License
from 1100100

public override PageResult<TReturn> QueryPage<TReturn>(string countSql, string dataSql, int pageindex, int pageSize, object param = null, int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });

            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return CommandExecute(enableCache, () =>
            {
                using (var multi = Conn.Value.QueryMultiple(sql, pars, Transaction, commandTimeout))
                {
                    var count = multi.Read<int>().FirstOrDefault();
                    var data = multi.Read<TReturn>().ToList();
                    var result = new PageResult<TReturn>
                    {
                        TotalCount = count,
                        Page = pageindex,
                        PageSize = pageSize,
                        Contents = data
                    };
                    result.TotalPage = result.TotalCount % pageSize == 0
                        ? result.TotalCount / pageSize
                        : result.TotalCount / pageSize + 1;
                    if (result.Page > result.TotalPage)
                        result.Page = result.TotalPage;
                    return result;
                }
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);
        }

19 Source : OdbcDapper.cs
with MIT License
from 1100100

public override PageResult<TReturn> QueryPage<TReturn>(string countSql, string dataSql, int pageindex, int pageSize, object param = null, int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });
            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return CommandExecute(enableCache, () =>
            {
                using (var multi = Conn.Value.QueryMultiple(sql, pars, Transaction, commandTimeout))
                {
                    var count = multi.Read<int>().FirstOrDefault();
                    var data = multi.Read<TReturn>().ToList();
                    var result = new PageResult<TReturn>
                    {
                        TotalCount = count,
                        Page = pageindex,
                        PageSize = pageSize,
                        Contents = data
                    };
                    result.TotalPage = result.TotalCount % pageSize == 0
                        ? result.TotalCount / pageSize
                        : result.TotalCount / pageSize + 1;
                    if (result.Page > result.TotalPage)
                        result.Page = result.TotalPage;
                    return result;
                }
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);
        }

19 Source : IsoHeaderParser.cs
with MIT License
from 13xforever

public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
        {
            var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
            var nextLevel = new List<string>();
            var filePaths = new List<string>();
            var dirPaths = new List<string>();
            while (fsObjects.Any())
            {
                foreach (var path in fsObjects)
                {
                    if (reader.FileExists(path))
                        filePaths.Add(path);
                    else if (reader.DirectoryExists(path))
                    {
                        dirPaths.Add(path);
                        nextLevel.AddRange(reader.GetFileSystemEntries(path));
                    }
                    else
                        Log.Warn($"Unknown filesystem object: {path}");
                }
                (fsObjects, nextLevel) = (nextLevel, fsObjects);
                nextLevel.Clear();
            }
            
            var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
            var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
            var deepestDirnames = new List<string>();
            foreach (var dirname in dirnames)
            {
                var tmp = dirname + "\\";
                if (deepestDirnames.Any(n => n.StartsWith(tmp)))
                    continue;
                
                deepestDirnames.Add(dirname);
            }
            dirnames = deepestDirnames.OrderBy(n => n).ToList();
            var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
            var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();

            var fileList = new List<FileRecord>();
            foreach (var filename in filenames)
            {
                var clusterRange = reader.PathToClusters(filename);
                if (clusterRange.Length != 1)
                    Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
                if (filename.EndsWith("."))
                    Log.Warn($"Fixing potential mastering error in {filename}");
                fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
            }
            fileList = fileList.OrderBy(r => r.StartSector).ToList();
            return (files: fileList, dirs: emptydirs);
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

static void CleanSingle(string command)
        {
            string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
            string keyvalue = string.Empty;
            string regcmd = string.Empty;
            if (command.EndsWith("\\1"))
            {
                regcmd = command;
            }
            else
            {
                regcmd = string.Format("{0}\\1", command);
            }
             
            try
            {
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);

                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        if(regkey.GetValue(subKey).ToString() == regcmd)
                        {
                            keyvalue = subKey;
                            regkey.DeleteValue(subKey);
                            Console.WriteLine(regcmd);
                            Console.WriteLine("[+] Cleaned {0} from HKCU:{1}", command, keypath);
                        }
                    }
                    if(keyvalue != string.Empty)
                    {
                        string mruchars = regkey.GetValue("MRUList").ToString();
                        int index = mruchars.IndexOf(keyvalue);
                        mruchars = mruchars.Remove(index, 1);
                        regkey.SetValue("MRUList", mruchars);
                    }
                }
                regkey.Close();
            }
            catch (ArgumentException)
            {
                Console.WriteLine("[-] Error: Selected Registry value does not exist");
            }
        }

19 Source : MsSqlDapper.cs
with MIT License
from 1100100

public override PageResult<dynamic> QueryPage(string countSql, string dataSql, int pageindex, int pageSize, object param = null,
            int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });

            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return CommandExecute(enableCache, () =>
            {
                using (var multi = Conn.Value.QueryMultiple(sql, pars, Transaction, commandTimeout))
                {
                    var count = multi.Read<int>().FirstOrDefault();
                    var data = multi.Read().ToList();
                    var result = new PageResult<dynamic>
                    {
                        TotalCount = count,
                        Page = pageindex,
                        PageSize = pageSize,
                        Contents = data
                    };
                    result.TotalPage = result.TotalCount % pageSize == 0
                        ? result.TotalCount / pageSize
                        : result.TotalCount / pageSize + 1;
                    if (result.Page > result.TotalPage)
                        result.Page = result.TotalPage;
                    return result;
                }
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);

        }

19 Source : OdbcDapper.cs
with MIT License
from 1100100

public override PageResult<dynamic> QueryPage(string countSql, string dataSql, int pageindex, int pageSize, object param = null,
            int? commandTimeout = null, bool? enableCache = default, TimeSpan? cacheExpire = default, string cacheKey = default)
        {
            if (pageindex < 1)
                throw new ArgumentException("The pageindex cannot be less then 1.");
            if (pageSize < 1)
                throw new ArgumentException("The pageSize cannot be less then 1.");
            var pars = new DynamicParameters();
            if (param != null)
                pars.AddDynamicParams(param);

            pars.AddDynamicParams(new
            {
                TakeStart = (pageindex - 1) * pageSize + 1,
                TakeEnd = pageindex * pageSize,
                Skip = (pageindex - 1) * pageSize,
                Take = pageSize
            });
            var sql = $"{countSql}{(countSql.EndsWith(";") ? "" : ";")}{dataSql}";
            return CommandExecute(enableCache, () =>
            {
                using (var multi = Conn.Value.QueryMultiple(sql, pars, Transaction, commandTimeout))
                {
                    var count = multi.Read<int>().FirstOrDefault();
                    var data = multi.Read().ToList();
                    var result = new PageResult<dynamic>
                    {
                        TotalCount = count,
                        Page = pageindex,
                        PageSize = pageSize,
                        Contents = data
                    };
                    result.TotalPage = result.TotalCount % pageSize == 0
                        ? result.TotalCount / pageSize
                        : result.TotalCount / pageSize + 1;
                    if (result.Page > result.TotalPage)
                        result.Page = result.TotalPage;
                    return result;
                }
            }, sql, pars, cacheKey, cacheExpire, pageindex, pageSize);

        }

19 Source : Program.cs
with MIT License
from 13xforever

static async Task<int> Main(string[] args)
        {
            Log.Info("PS3 Disc Dumper v" + Dumper.Version);

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Console.WindowHeight < 1 && Console.WindowWidth < 1)
                try
                {
                    Log.Error("Looks like there's no console present, restarting...");
                    var launchArgs = Environment.GetCommandLineArgs()[0];
                    if (launchArgs.Contains("/var/tmp") || launchArgs.EndsWith(".dll"))
                    {
                        Log.Debug("Looks like we were launched from a single executable, looking for the parent...");
                        using var currentProcess = Process.GetCurrentProcess();
                        var pid = currentProcess.Id;
                        var procCmdlinePath = Path.Combine("/proc", pid.ToString(), "cmdline");
                        launchArgs = File.ReadAllLines(procCmdlinePath).FirstOrDefault()?.TrimEnd('\0');
                    }
                    Log.Debug($"Using cmdline '{launchArgs}'");
                    launchArgs = $"-e bash -c {launchArgs}";
                    var startInfo = new ProcessStartInfo("x-terminal-emulator", launchArgs);
                    using var proc = Process.Start(startInfo);
                    if (proc.WaitForExit(1_000))
                    {
                        if (proc.ExitCode != 0)
                        {
                            startInfo = new ProcessStartInfo("xdg-terminal", launchArgs);
                            using var proc2 = Process.Start(startInfo);
                            if (proc2.WaitForExit(1_000))
                            {
                                if (proc2.ExitCode != 0)
                                {
                                    startInfo = new ProcessStartInfo("gnome-terminal", launchArgs);
                                    using var proc3 = Process.Start(startInfo);
                                    if (proc3.WaitForExit(1_000))
                                    {
                                        if (proc3.ExitCode != 0)
                                        {
                                            startInfo = new ProcessStartInfo("konsole", launchArgs);
                                            using var _ = Process.Start(startInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    return -2;
                }
                catch (Exception e)
                {
                    Log.Error(e);
                    return -3;
                }
            var lastDiscId = "";
start:
            const string replacedleBase = "PS3 Disc Dumper";
            var replacedle = replacedleBase;
            Console.replacedle = replacedle;
            var output = ".";
            var inDir = "";
            var showHelp = false;
            var options = new OptionSet
            {
                {
                    "i|input=", "Path to the root of blu-ray disc mount", v =>
                    {
                        if (v is string ind)
                            inDir = ind;
                    }
                },
                {
                    "o|output=", "Path to the output folder. Subfolder for each disc will be created automatically", v =>
                    {
                        if (v is string outd)
                            output = outd;
                    }
                },
                {
                    "?|h|help", "Show help", v =>
                    {
                        if (v != null)
                            showHelp = true;
                    },
                    true
                },
            };
            try
            {
                var unknownParams = options.Parse(args);
                if (unknownParams.Count > 0)
                {
                    Log.Warn("Unknown parameters: ");
                    foreach (var p in unknownParams)
                        Log.Warn("\t" + p);
                    showHelp = true;
                }
                if (showHelp)
                {
                    ShowHelp(options);
                    return 0;
                }

                var dumper = new Dumper(ApiConfig.Cts);
                dumper.DetectDisc(inDir);
                await dumper.FindDiscKeyAsync(ApiConfig.IrdCachePath).ConfigureAwait(false);
                if (string.IsNullOrEmpty(dumper.OutputDir))
                {
                    Log.Info("No compatible disc was found, exiting");
                    return 2;
                }
                if (lastDiscId == dumper.ProductCode)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("You're dumping the same disc, are you sure you want to continue? (Y/N, default is N)");
                    Console.ResetColor();
                    var confirmKey = Console.ReadKey(true);
                    switch (confirmKey.Key)
                    {
                        case ConsoleKey.Y:
                            break;
                        default:
                            throw new OperationCanceledException("Aborting re-dump of the same disc");
                    }
                }
                lastDiscId = dumper.ProductCode;

                replacedle += " - " + dumper.replacedle;
                var monitor = new Thread(() =>
                {
                    try
                    {
                        do
                        {
                            if (dumper.CurrentSector > 0)
                                Console.replacedle = $"{replacedle} - File {dumper.CurrentFileNumber} of {dumper.TotalFileCount} - {dumper.CurrentSector * 100.0 / dumper.TotalSectors:0.00}%";
                            Task.Delay(1000, ApiConfig.Cts.Token).GetAwaiter().GetResult();
                        } while (!ApiConfig.Cts.Token.IsCancellationRequested);
                    }
                    catch (TaskCanceledException)
                    {
                    }
                    Console.replacedle = replacedle;
                });
                monitor.Start();

                await dumper.DumpAsync(output).ConfigureAwait(false);

                ApiConfig.Cts.Cancel(false);
                monitor.Join(100);

                if (dumper.BrokenFiles.Count > 0)
                {
                    Log.Fatal("Dump is not valid");
                    foreach (var file in dumper.BrokenFiles)
                        Log.Error($"{file.error}: {file.filename}");
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Dump is valid");
                    Console.ResetColor();
                }
            }
            catch (OptionException)
            {
                ShowHelp(options);
                return 1;
            }
            catch (Exception e)
            {
                Log.Error(e, e.Message);
            }
            Console.WriteLine("Press X or Ctrl-C to exit, any other key to start again...");
            var key = Console.ReadKey(true);
            switch (key.Key)
            {
                case ConsoleKey.X:
                    return 0;
                default:
                    goto start;
            }
        }

19 Source : ExpressionActivator.cs
with Apache License 2.0
from 1448376744

private Expression ResovleConstantExpression(string expression)
        {
            //自动类型推断生成表达式
            if (expression.StartsWith("'") && expression.EndsWith("'"))
            {
                //字符串常量
                return Expression.Constant(expression.Trim('\''), typeof(string));
            }
            else if (expression == "true" || expression == "false")
            {
                return Expression.Constant(expression, typeof(bool));
            }
            else if (Regex.IsMatch(expression, @"^\d+$"))
            {
                //int类型常量
                return Expression.Constant(expression, typeof(int));
            }
            else if (Regex.IsMatch(expression, @"^\d*\.\d*$"))
            {
                //double
                return Expression.Constant(expression, typeof(int));
            }
            else if (expression == "null")
            {
                return Expression.Constant(null, typeof(object));
            }
            return Expression.Constant(expression, typeof(object));
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

private void stb_home_url_Enter(object sender, EventArgs e)
        {
            string sdir = stb_project_source_dir.Text;
            string appname = stb_app_name.Text;
            string url = stb_home_url.Text;
            if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
                try
                {
                    if (get_spboot_port_run)
                    {
                        return;
                    }
                    get_spboot_port_run = true;
                    if (!sdir.EndsWith("/"))
                    {
                        sdir += "/";
                    }
                    string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
                    string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
                    targetxml = targetxml.Replace("\\", "/");
                    parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        string port = "", ctx = "";
                        string yml = YSTools.YSFile.readFileToString(targetxml);
                        if(!string.IsNullOrWhiteSpace(yml)){
                            string[] lines = yml.Split('\n');
                            bool find = false;                            
                            int index = 0, start = 0;
                            foreach(string line in lines){
                                if (line.Trim().StartsWith("server:"))
                                {
                                    find = true;
                                    start = index;
                                }
                                else if(find && line.Trim().StartsWith("port:")){
                                    port = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                else if (find && line.Trim().StartsWith("context-path:"))
                                {
                                    ctx = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                if (index - start > 4 && start > 0)
                                {
                                    break;
                                }
                                index++;
                            }
                        }

                        if (port != "")
                        {
                            stb_home_url.BeginInvoke((MethodInvoker)delegate()
                            {
                                stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
                            });
                        }
                        
                        get_spboot_port_run = false;

                        File.Delete(targetxml);
                    });
                }
                catch(Exception ex) {
                    logger.Error("Error", ex);
                }

            }
        }

19 Source : AppConfig.cs
with Apache License 2.0
from 214175590

public void LoadConfig()
        {
            // 初始化主配置            
            try
            {
                MainConfig config = null;
                if (File.Exists(MainForm.CONF_DIR + MC_NAME))
                {
                    string mconfig = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + MC_NAME, false, CONFIG_KEY);
                    if (!string.IsNullOrWhiteSpace(mconfig))
                    {
                        config = JsonConvert.DeserializeObject<MainConfig>(mconfig);
                        if(null != config){
                            MConfig = config;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("加载Main配置文件异常:" + ex.Message);
                logger.Error("--->" + MC_NAME);
            }

            // 初始化session配置
            SessionConfigDict = new Dictionary<string, SessionConfig>();

            DirectoryInfo direct = new DirectoryInfo(MainForm.SESSION_DIR);
            if (direct.Exists)
            {
                FileInfo[] files = direct.GetFiles();
                string content = null;
                SessionConfig sessionConfig = null;
                foreach(FileInfo file in files){
                    try
                    {
                        if (file.Name.EndsWith(".json"))
                        {
                            content = YSTools.YSFile.readFileToString(file.FullName, false, CONFIG_KEY);
                            if (!string.IsNullOrWhiteSpace(content))
                            {
                                sessionConfig = JsonConvert.DeserializeObject<SessionConfig>(content);
                                if (null != sessionConfig)
                                {
                                    SessionConfigDict.Add(sessionConfig.SessionId, sessionConfig);
                                }
                            }                            
                        }
                    }catch(Exception ex){
                        logger.Error("加载Session配置文件异常:" + ex.Message);
                        logger.Error("--->" + file.Name);
                    }                    
                }
            }

        }

19 Source : CustomScriptForm.cs
with Apache License 2.0
from 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 Source : QuickCommandManageForm.cs
with Apache License 2.0
from 214175590

public void RenderList()
        {
            if (config.ShellList.Count > 0)
            {
                string shell = null;
                int index = 0;
                bool needCr = false;
                skinDataGridView1.Rows.Clear();
                DataGridViewRow row = null;
                DataGridViewTextBoxCell textCell = null;
                DataGridViewCheckBoxCell checkCell = null;
                DataGridViewButtonCell btnCell = null;
                foreach (string cmd in config.ShellList)
                {
                    try
                    {
                        shell = cmd;
                        if (shell.EndsWith("\n"))
                        {
                            needCr = true;
                            shell = shell.Substring(0, shell.Length - 1);
                        }
                        else
                        {
                            needCr = false;
                        }

                        row = new DataGridViewRow();
                        textCell = new DataGridViewTextBoxCell();
                        textCell.Value = index;
                        row.Cells.Add(textCell);

                        textCell = new DataGridViewTextBoxCell();
                        textCell.Value = shell;
                        row.Cells.Add(textCell);

                        checkCell = new DataGridViewCheckBoxCell();
                        checkCell.Value = needCr;
                        row.Cells.Add(checkCell);

                        btnCell = new DataGridViewButtonCell();
                        btnCell.Value = "删除";
                        row.Cells.Add(btnCell);

                        skinDataGridView1.Rows.Add(row);
                    }
                    catch { }
                    index++;                    
                }
            }


        }

19 Source : IceMonitorForm.cs
with Apache License 2.0
from 214175590

public override void ReflushMonitorItem()
        {
            l_appname.Text = itemConfig.ice.AppName;
            string srcdir = itemConfig.ice.IceSrvDir;
            if (srcdir != null)
            {
                if (!srcdir.EndsWith("/"))
                    srcdir += "/";
                l_pro_path.Text = srcdir;
            }
            l_node_port.Text = itemConfig.ice.NodePorts;
            l_server_name.Text = itemConfig.ice.ServerName;

            if (itemConfig.ice.NodePorts != null)
            {
                string[] ports = itemConfig.ice.NodePorts.Split(',');
                ListViewItem item = null;
                foreach(string port in ports){
                    item = new ListViewItem();
                    item.Text = string.Format("http://{0}:{1}", seConfig.Host, port);
                    item.Tag = port;
                    projects.Items.Add(item);
                }
            }
        }

19 Source : IceMonitorForm.cs
with Apache License 2.0
from 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) => {

                string srvdir = itemConfig.ice.IceSrvDir;
                if (null != srvdir)
                {
                    if (!srvdir.EndsWith("/"))
                    {
                        srvdir += "/";
                    }
                }

                string shell = task.Shell;
                if (shell.Contains("{icesrv_dir}"))
                {
                    shell = shell.Replace("{icesrv_dir}", srvdir);
                }

                if (shell.Contains("{server_name}"))
                {
                    shell = shell.Replace("{server_name}", l_server_name.Text);
                }

                if (shell.Contains("{adminsh}"))
                {
                    shell = shell.Replace("{adminsh}", srvdir + "bin/admin.sh");
                }
                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

void Tomcat_TextChanged(object sender, EventArgs e)
        {
            string path = stb_tomcat_path.Text;
            if (!string.IsNullOrWhiteSpace(path))
            {
                if (string.IsNullOrWhiteSpace(tomcat_name))
                {
                    try
                    {
                        stb_tomcat_name.Text = path.Substring(path.LastIndexOf("/") + 1);
                    }
                    catch { }
                }

                if (string.IsNullOrWhiteSpace(stb_tomcat_port.Text))
                {
                    try
                    {
                        if (get_tomcat_port_run)
                        {
                            return;
                        }
                        get_tomcat_port_run = true;
                        if (!path.EndsWith("/"))
                        {
                            path += "/";
                        }
                        string serverxml = path + "conf/server.xml";
                        string targetxml = MainForm.TEMP_DIR + string.Format("server-{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, "Server");
                            if(list != null && list.Count > 0){
                                List<Hashtable> serviceList = null;
                                string port = null;
                                foreach(Hashtable one in list){
                                    if (one["NodeName"].ToString() == "Service")
                                    {
                                        serviceList = (List<Hashtable>) one["ChildList"];
                                        foreach (Hashtable two in serviceList)
                                        {
                                            if (two["NodeName"].ToString() == "Connector")
                                            {
                                                port = two["port"].ToString();

                                                break;
                                            }
                                        }
                                        if(port != null){
                                            break;
                                        }
                                    }
                                }

                                stb_tomcat_port.BeginInvoke((MethodInvoker)delegate()
                                {
                                   stb_tomcat_port.Text = port == null ? "8080" : port;
                                });
                            }
                            get_tomcat_port_run = false;

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

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 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 { }
                }
            }
        }

19 Source : SpringBootMonitorForm.cs
with Apache License 2.0
from 214175590

public override void ReflushMonitorItem()
        {
            l_appname.Text = itemConfig.spring.AppName;
            string soudir = itemConfig.spring.ProjectSourceDir;
            if (soudir != null)
            {
                if (!soudir.EndsWith("/"))
                    soudir += "/";
                l_source_path.Text = soudir + itemConfig.spring.AppName;
            }

            string dir = itemConfig.spring.ShFileDir;
            if (null != dir)
            {
                if (!dir.EndsWith("/"))
                {
                    dir += "/";
                }
                l_build_path.Text = dir + itemConfig.spring.BuildFileName;
            }

            l_ctl_path.Text = dir + itemConfig.spring.CrlFileName;

            string homeUrl = itemConfig.spring.HomeUrl;
            if (!string.IsNullOrWhiteSpace(homeUrl))
            {
                l_pro_visit_url.Text = homeUrl;
                CheckItem();
            }
            else
            {
                l_pro_visit_url.Text = "http://" + seConfig.Host + ":[port]/";
            }
        }

19 Source : SpringBootMonitorForm.cs
with Apache License 2.0
from 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) => { 

                string shdir = itemConfig.spring.ShFileDir;
                if (null != shdir)
                {
                    if (!shdir.EndsWith("/"))
                    {
                        shdir += "/";
                    }
                }

                string shell = task.Shell;
                if (shell.Contains("{sh_bin_dir}"))
                {
                    shell = shell.Replace("{sh_bin_dir}", shdir);
                }

                if (shell.Contains("{project_dir}"))
                {
                    shell = shell.Replace("{project_dir}", l_source_path.Text);
                }

                if (shell.Contains("{build_sh_file}"))
                {
                    shell = shell.Replace("{build_sh_file}", itemConfig.spring.BuildFileName);
                }

                if (shell.Contains("{ctl_sh_file}"))
                {
                    shell = shell.Replace("{ctl_sh_file}", itemConfig.spring.CrlFileName);
                }
                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 Source : Utils.cs
with Apache License 2.0
from 214175590

public static string PathEndAddSlash(string path)
        {
            if(!path.EndsWith("/")){
                path += "/";
            }
            return path;
        }

19 Source : NginxMonitorForm.cs
with Apache License 2.0
from 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {

                string shdir = itemConfig.nginx.NginxPath;
                if (null != shdir)
                {
                    if (shdir.EndsWith("/"))
                    {
                        shdir = shdir.Substring(0, shdir.Length - 1);
                    }
                    shdir = shdir.Substring(0, shdir.LastIndexOf("/") + 1);
                }

                string shell = task.Shell;
                if (shell.Contains("{nginx_dir}"))
                {
                    shell = shell.Replace("{nginx_dir}", shdir);
                }

                if (shell.Contains("{nginx}"))
                {
                    shell = shell.Replace("{nginx}", itemConfig.nginx.NginxPath);
                }

                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590

public string getCurrDir()
        {
            if(!dir.EndsWith("/") && dir != "/"){
                return dir + "/";
            }
            return dir;
        }

19 Source : SftpLinuxForm.cs
with Apache License 2.0
from 214175590

public void OpenUpDir()
        {
            if(dir != "/" && dir.Length > 1){
                if(dir.EndsWith("/")){
                    dir = dir.Substring(0, dir.Length - 1);
                }
                string dirpath = dir;
                int index = dirpath.LastIndexOf("/");
                if(index > 0){
                    dirpath = dirpath.Substring(0, index);
                } else if(index == 0){
                    dirpath = "/";                    
                }
                LoadDirFilesToListView(dirpath, () =>
                {
                    dir = dirpath;
                    text_adress.Text = dir;
                });
            }            
        }

19 Source : JcApiHelper_InitParam.cs
with MIT License
from 279328316

private static bool IsIgnoreType(Type type)
        {
            bool result = false;
            try
            {
                string typeName = TypeHelper.GetTypeName(type);
                typeName = typeName.Replace("[]", "");  //获取数组 元类型

                //基类为ValueType的值类型 或Type,*Attribute
                result = type.BaseType?.Name == "ValueType" 
                            || typeName == "Type" 
                            || typeName.EndsWith("Attribute");
                
                if (!result)
                {   //排除 系统基本类型
                    result = Enum.IsDefined(typeof(TypeCode), typeName);
                }
            }
            catch (Exception ex)
            {
            }
            return result;
        }

19 Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590

public override void ReflushMonitorItem()
        {
            l_name.Text = itemConfig.tomcat.TomcatName;
            string soudir = itemConfig.tomcat.TomcatDir;
            if (soudir != null)
            {
                if (!soudir.EndsWith("/"))
                    soudir += "/";
                l_tomcat_path.Text = soudir;
            }

            l_xml_path.Text = soudir + "conf/server.xml";

            l_visit_url.Text = "http://" + seConfig.Host + ":" + itemConfig.tomcat.TomcatPort;

            tb_port.Text = itemConfig.tomcat.TomcatPort;

            CheckItem();
        }

19 Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590

public List<JObject> loadTomcatServerProject()
        {
            List<JObject> itemList = new List<JObject>();
            try
            {
                string serverxml = l_tomcat_path.Text + "conf/server.xml";
                string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                targetxml = targetxml.Replace("\\", "/");
                monitorForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    
                List<System.Collections.Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
                if (list != null && list.Count > 0)
                {
                    List<System.Collections.Hashtable> serviceList = null;
                    List<System.Collections.Hashtable> engineList = null;
                    List<System.Collections.Hashtable> hostList = null;
                    string port = null, docBase = "", path = "";
                    JObject json = null;
                    foreach (System.Collections.Hashtable one in list)
                    {
                        if (one["NodeName"].ToString() == "Service")
                        {
                            serviceList = (List<System.Collections.Hashtable>)one["ChildList"];
                            foreach (System.Collections.Hashtable two in serviceList)
                            {
                                if (two["NodeName"].ToString() == "Engine")
                                {
                                    engineList = (List<System.Collections.Hashtable>)two["ChildList"];
                                    foreach (System.Collections.Hashtable three in engineList)
                                    {
                                        if (three["NodeName"].ToString() == "Host")
                                        {
                                            hostList = (List<System.Collections.Hashtable>)three["ChildList"];
                                            foreach (System.Collections.Hashtable four in hostList)
                                            {
                                                if (four["NodeName"].ToString() == "Context")
                                                {
                                                    json = new JObject();
                                                    docBase = four["docBase"].ToString();
                                                    path = four["path"].ToString();
                                                    if (!docBase.EndsWith(path))
                                                    {
                                                        if (docBase.StartsWith("/"))
                                                        {
                                                            json.Add("path", docBase);
                                                        }
                                                        else
                                                        {
                                                            json.Add("path", l_tomcat_path.Text + "webapps/" + docBase);
                                                        }
                                                        json.Add("name", docBase);
                                                        json.Add("url", l_visit_url.Text + "/" + path);
                                                        
                                                        itemList.Add(json);
                                                    }                                                    
                                                }
                                            }
                                        }
                                    }

                                    break;
                                }
                            }
                            if (port != null)
                            {
                                break;
                            }
                        }
                    }

                }

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

19 Source : TomcatMonitorForm.cs
with Apache License 2.0
from 214175590

public void runTaskShell(CmdShell cmds, TaskShell task)
        {
            ThreadPool.QueueUserWorkItem((a) =>
            {

                string shdir = itemConfig.tomcat.TomcatDir;
                if (null != shdir)
                {
                    if (!shdir.EndsWith("/"))
                    {
                        shdir += "/";
                    }
                }

                string shell = task.Shell;
                if (shell.Contains("{tomcat_dir}"))
                {
                    shell = shell.Replace("{tomcat_dir}", shdir);
                }

                if (shell.Contains("{tomcat_webapps}"))
                {
                    shell = shell.Replace("{tomcat_webapps}", shdir + "webapps/");
                }

                if (shell.Contains("{tomcat_logs}"))
                {
                    shell = shell.Replace("{tomcat_logs}", shdir + "logs/");
                }

                if (shell.Contains("{tomcat_startup}"))
                {
                    shell = shell.Replace("{tomcat_startup}", shdir + "bin/startup.sh");
                }

                if (shell.Contains("{tomcat_shutdown}"))
                {
                    shell = shell.Replace("{tomcat_shutdown}", shdir + "bin/shutdown.sh");
                }
                
                shell = shell.Replace("//", "/");

                monitorForm.RunShell(shell, false);
            });
        }

19 Source : IceDeployVersionForm.cs
with Apache License 2.0
from 214175590

void stb_local_pdir_TextChanged(object sender, EventArgs e)
        {
            string dir = stb_local_pdir.Text;
            string path = stb_icexml.Text;
            if (!string.IsNullOrWhiteSpace(dir) && string.IsNullOrWhiteSpace(path))
            {
                if (Directory.Exists(dir))
                {
                    dir = dir.Replace("\\", "/");
                    if(!dir.EndsWith("/")){
                        dir += "/";
                    }
                    path = string.Format("{0}icedeploy/config/{1}.xml", dir, ice.AppName);
                    if (File.Exists(path))
                    {
                        stb_icexml.Text = path;
                    }
                }
            }            
        }

19 Source : SftpWinForm.cs
with Apache License 2.0
from 214175590

public string getCurrDir()
        {
            dir = dir.Replace("\\", "/");
            if (!dir.EndsWith("/"))
            {
                return dir + "/";
            }
            return dir;
        }

19 Source : Form1.cs
with Apache License 2.0
from 214175590

public void ShowLogger(string line)
        {
            this.BeginInvoke((MethodInvoker)delegate()
            {
                line = line.Replace("\r\r", "");
                if(!line.EndsWith("\n")){
                    line += "\n";
                }
                List<Message> msgList = new List<Message>();
                if(line.StartsWith(cmd + "\r\n")){
                    string str1 = line.Substring(0, (cmd + "\r\n").Length);
                    msgList.Add(new Message() { 
                        Text = str1,
                        Color = Color.Red
                    });
                    MessageUtils.FormatMessage(msgList, line.Substring((cmd + "\r\n").Length));
                }
                else
                {
                    MessageUtils.FormatMessage(msgList, line);
                }
                foreach (Message msg in msgList)
                {
                    if(msg != null && msg.Text != null){
                        rtb_log.SelectionColor = msg.Color;
                        rtb_log.SelectionBackColor = msg.BackColor;
                        rtb_log.AppendText(msg.Text); 
                    }                     
                }

                rtb_log.Select(rtb_log.TextLength, 0);
                rtb_log.Focus();
                //滚动到控件光标处 
                rtb_log.ScrollToCaret();
                tb_shell.Focus();
            });
        }

19 Source : TsCreator.cs
with MIT License
from 279328316

private string GetTsType(string typeName)
        {
            string tsTypeStr = "";

            List<string> numberTypeList =
                ("int,int?,int16,int16?,int32,int32?,int64,int64?,decimal,decimal?," +
                "double,double?,byte,byte?,long,long?,single,single?").Split(',').ToList();
            
            List<string> boolTypeList = ("bool,bool?,boolean,boolean?").Split(',').ToList();
            List<string> stringTypeList =
                ("string,guid,guid?").Split(',').ToList();
            List<string> dateTimeTypeList =
                ("datetime,datetime?").Split(',').ToList();

            if (boolTypeList.Contains(typeName.ToLower()))
            {
                tsTypeStr = "boolean";
            }
            else if (stringTypeList.Contains(typeName.ToLower()))
            {
                tsTypeStr = "string";
            }
            else if (dateTimeTypeList.Contains(typeName.ToLower()))
            {
                tsTypeStr = "Date";
            }
            else if (numberTypeList.Contains(typeName.ToLower()))
            {
                tsTypeStr = "number";
            }
            else
            {
                tsTypeStr = typeName;
                #region 去掉Dto,Model命名
                if (tsTypeStr.EndsWith("Dto"))
                {   //参数类型名称 去掉末尾Dto,Model命名
                    tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Dto"));
                }
                else if (tsTypeStr.EndsWith("Dto>"))
                {
                    tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Dto")) + ">";
                }
                else if (tsTypeStr.EndsWith("Model"))
                {
                    tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Model"));
                }
                else if (tsTypeStr.EndsWith("Model>"))
                {
                    tsTypeStr = tsTypeStr.Substring(0, tsTypeStr.LastIndexOf("Model")) + ">";
                }
                #endregion
            }
            return tsTypeStr;
        }

19 Source : CentralServerConfigForm.cs
with Apache License 2.0
from 214175590

private void CentralServerConfigForm_Load(object sender, EventArgs e)
        {
            if(monitorForm != null){
                this.Text = "Docker公共配置 - " + monitorForm.getSessionConfig().Host;
                cfgDir = MainForm.TEMP_DIR + monitorForm.getSessionConfig().Host;
                cfgDir = cfgDir.Replace("\\", "/");
                if (!Directory.Exists(cfgDir))
                {
                    Directory.CreateDirectory(cfgDir);
                }

                string cfgPath = monitorForm.getSessionConfig().CentralServerConfigDir;
                if (string.IsNullOrWhiteSpace(cfgPath))
                {
                    string home = monitorForm.getSftp().getHome();
                    if (!home.EndsWith("/"))
                    {
                        home += "/";
                    }
                    remoteCfgPath = home + "docker/central-server-config";
                    monitorForm.getSessionConfig().CentralServerConfigDir = remoteCfgPath;
                    AppConfig.Instance.SaveConfig(2);
                }
                else
                {
                    remoteCfgPath = cfgPath;
                }                

                stb_remote_dir.Text = remoteCfgPath;

                LoadRemoteYmls();
            }
            else
            {
                btn_reload.Enabled = false;
                btn_show.Enabled = false;
                下载到本地ToolStripMenuItem.Enabled = false;
                上传到服务器ToolStripMenuItem.Enabled = false;
                更改文件名ToolStripMenuItem.Enabled = false;
                删除文件ToolStripMenuItem.Enabled = false;
                this.AllowDrop = true;
            }
        }

19 Source : ClusterAdapter.cs
with MIT License
from 2881099

void RefershClusterNodes()
            {
                foreach (var testConnection in _clusterConnectionStrings)
                {
                    RegisterClusterNode(testConnection);
                    //尝试求出其他节点,并缓存slot
                    try
                    {
                        var cnodes = AdapterCall<string>("CLUSTER".SubCommand("NODES"), rt => rt.ThrowOrValue<string>()).Split('\n');
                        foreach (var cnode in cnodes)
                        {
                            if (string.IsNullOrEmpty(cnode)) continue;
                            var dt = cnode.Trim().Split(' ');
                            if (dt.Length < 9) continue;
                            if (!dt[2].StartsWith("master") && !dt[2].EndsWith("master")) continue;
                            if (dt[7] != "connected") continue;

                            var endpoint = dt[1];
                            var at40 = endpoint.IndexOf('@');
                            if (at40 != -1) endpoint = endpoint.Remove(at40);

                            if (endpoint.StartsWith("127.0.0.1"))
                                endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
                            else if (endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
                                endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
                            ConnectionStringBuilder connectionString = testConnection.ToString();
                            connectionString.Host = endpoint;
                            RegisterClusterNode(connectionString);

                            for (var slotIndex = 8; slotIndex < dt.Length; slotIndex++)
                            {
                                var slots = dt[slotIndex].Split('-');
                                if (ushort.TryParse(slots[0], out var tryslotStart) &&
                                    ushort.TryParse(slots[1], out var tryslotEnd))
                                {
                                    for (var slot = tryslotStart; slot <= tryslotEnd; slot++)
                                        _slotCache.AddOrUpdate(slot, connectionString.Host, (k1, v1) => connectionString.Host);
                                }
                            }
                        }
                        break;
                    }
                    catch
                    {
                        _ib.TryRemove(testConnection.Host, true);
                    }
                }

                if (_ib.GetKeys().Length == 0)
                    throw new RedisClientException($"All \"clusterConnectionStrings\" failed to connect");
            }

19 Source : DynamicProxy.cs
with MIT License
from 2881099

public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
        {
            if (type == null) return null;
            var typeCSharpName = type.DisplayCsharp();

            if (type.IsNotPublic)
            {
                if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
                return null;
            }

            var matchedMemberInfos = new List<MemberInfo>();
            var matchedAttributes = new List<DynamicProxyAttribute>();
            var matchedAttributesFromServices = new List<FieldInfo[]>();
            var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
            var methodOverrideSb = new StringBuilder();
            var sb = methodOverrideSb;

            #region Common Code

            Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
            {
                var sbt = new StringBuilder();
                for (var a = attrsIndex; a < matchedAttributes.Count; a++)
                {
                    sbt.Append($@"{(proxyMethodName == "Before" ? $@"
        var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
        __DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
        var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
        {(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
        {(proxyMethodName == "Before" ? 
        $@"if (__DP_ARG___is_return == false)
        {{
            __DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
            if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
        }}" : 
        $"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
                }
                return sbt.ToString();
            };
            Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
            {
                var sbt = new StringBuilder();
                var taskType = returnType.ReturnTypeWithoutTask();
                sbt.Append($@"
        {(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
                (taskType.IsValueType || taskType.IsGenericParameter ?
                    $"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
                    $"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
                ) :
                (returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
                return sbt.ToString();
            };
            Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
            {
                return $@"
            if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
            };
            #endregion

            #region Methods
            var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
            var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            foreach (var method in methods)
            {
                if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
                    if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
                var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                if (attrs.Any() == false) continue;
                var attrsIndex = matchedAttributes.Count;
                matchedMemberInfos.AddRange(attrs.Select(a => method));
                matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
                matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
                    .Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
                matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
                if (method.IsVirtual == false || method.IsFinal)
                {
                    if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
                    continue;
                }

#if net40
                var returnType = method.ReturnType;
                var methodIsAsync = false;
#else
                var returnType = method.ReturnType.ReturnTypeWithoutTask();
                var methodIsAsync = method.ReturnType.IsTask();

                //if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
                //    attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
                //{

                //}
#endif

                var baseInvoke = type.IsInterface == false ? $@"

        try
        {{
            if (__DP_ARG___is_return == false)
            {{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
                {(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
            }}
        }}
        catch (Exception __DP_ARG___ex)
        {{
            __DP_ARG___exception = __DP_ARG___ex;
        }}" : "";

                sb.Append($@"

    {(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
    {{
        Exception __DP_ARG___exception = null;
        var __DP_ARG___is_return = false;
        object __DP_ARG___return_value = null;
        var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n        ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
        {getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
        {getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
        {getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
    }}");
            }
            #endregion

            var propertyOverrideSb = new StringBuilder();
            sb = propertyOverrideSb;
            #region Property
            var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
            foreach (var prop2 in props)
            {
                var getMethod = prop2.GetGetMethod(false);
                var setMethod = prop2.GetSetMethod(false);
                if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
                {
                    if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
                        setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
                    {
                        if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
                        continue;
                    }
                }

                var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                var prop2AttributeAny = attrs.Any();
                var getMethodAttributeAny = prop2AttributeAny;
                var setMethodAttributeAny = prop2AttributeAny;
                if (attrs.Any() == false && getMethod?.IsVirtual == true)
                {
                    attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                    getMethodAttributeAny = attrs.Any();
                }
                if (attrs.Any() == false && setMethod?.IsVirtual == true)
                {
                    attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                    setMethodAttributeAny = attrs.Any();
                }
                if (attrs.Any() == false) continue;

                var attrsIndex = matchedAttributes.Count;
                matchedMemberInfos.AddRange(attrs.Select(a => prop2));
                matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
                matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
                    .Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
                matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif

                var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();

                var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
                var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
                var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
                if (propSetModification == propModification) propSetModification = "";
                if (propGetModification == propModification) propGetModification = "";

                //if (getMethod.IsAbstract) sb.Append("abstract ");
                sb.Append($@"

    {propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
    {{");

                if (getMethod != null)
                {
                    if (getMethodAttributeAny == false) sb.Append($@"
        {propGetModification} get
        {{
            return base.{prop2.Name}
        }}");
                    else sb.Append($@"
        {propGetModification} get
        {{
            Exception __DP_ARG___exception = null;
            var __DP_ARG___is_return = false;
            object __DP_ARG___return_value = null;
            var __DP_ARG___parameters = new Dictionary<string, object>();
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}

            try
            {{
                if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
            }}
            catch (Exception __DP_ARG___ex)
            {{
                __DP_ARG___exception = __DP_ARG___ex;
            }}
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
            {getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
        }}");
                }

                if (setMethod != null)
                {
                    if (setMethodAttributeAny == false) sb.Append($@"
        {propSetModification} set
        {{
            base.{prop2.Name} = value;
        }}");
                    else sb.Append($@"
        {propSetModification} set
        {{
            Exception __DP_ARG___exception = null;
            var __DP_ARG___is_return = false;
            object __DP_ARG___return_value = null;
            var __DP_ARG___parameters = new Dictionary<string, object>();
            __DP_ARG___parameters.Add(""value"", value);
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}

            try
            {{
                if (__DP_ARG___is_return == false)
                {{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
                    base.{prop2.Name} = value;
                }}
            }}
            catch (Exception __DP_ARG___ex)
            {{
                __DP_ARG___exception = __DP_ARG___ex;
            }}
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
        }}");
                }


                sb.Append($@"
    }}");
            }
            #endregion

            string proxyCscode = "";
            replacedembly proxyreplacedembly = null;
            Type proxyType = null;

            if (matchedMemberInfos.Any())
            {
                #region Constructors
                sb = new StringBuilder();
                var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
                sb.Append(string.Join("", fromServicesTypes.Select(serviceType => $@"
    private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
                foreach (var ctor in ctors)
                {
                    var ctorParams = ctor.GetParameters();
                    sb.Append($@"

    {(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
                        (ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
                        string.Join(", ", fromServicesTypes.Select(serviceType => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
        : base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
    {{{string.Join("", fromServicesTypes.Select(serviceType => $@"
        {serviceType.Value} = parameter{serviceType.Value};"))}
    }}");
                }
                for (var a = 0; a < matchedAttributesFromServices.Count; a++)
                {
                    sb.Append($@"

    private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
    {{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
        __DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
    }}");
                }
                #endregion

                proxyCscode = $@"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

public clreplaced {clreplacedName} : {typeCSharpName}
{{
    private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));

    //这里要注释掉,如果重写的基类没有无参构造函数,会报错
    //public {clreplacedName}({_metaName} meta)
    //{{
    //    __DP_Meta = meta;
    //}}
    {sb.ToString()}
    {methodOverrideSb.ToString()}

    {propertyOverrideSb.ToString()}
}}";
                proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
                proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
            }
            methodOverrideSb.Clear();
            propertyOverrideSb.Clear();
            sb.Clear();
            return new DynamicProxyMeta(
                type, ctors,
                matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
                isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from 2dust

private void ShowMsg(string msg)
        {
            if (txtMsgBox.Lines.Length > 999)
            {
                ClearMsg();
            }
            this.txtMsgBox.AppendText(msg);
            if (!msg.EndsWith(Environment.NewLine))
            {
                this.txtMsgBox.AppendText(Environment.NewLine);
            }
        }

19 Source : AdminLTEExtesions.cs
with MIT License
from 2881099

public static IApplicationBuilder UseFreeAdminLtePreview(this IApplicationBuilder app, string requestPathBase, params Type[] enreplacedyTypes) {

			requestPathBase = requestPathBase.ToLower();
			if (requestPathBase.StartsWith("/") == false) requestPathBase = $"/{requestPathBase}";
			if (requestPathBase.EndsWith("/") == false) requestPathBase = $"{requestPathBase}/";
			var restfulRequestPath = $"{requestPathBase}restful-api";

			IFreeSql fsql = app.ApplicationServices.GetService(typeof(IFreeSql)) as IFreeSql;
			if (fsql == null) throw new Exception($"UseFreeAdminLtePreview 错误,找不到 IFreeSql,请提前注入");

			var dicEnreplacedyTypes = enreplacedyTypes.ToDictionary(a => a.Name);

			app.UseFreeAdminLteStaticFiles(requestPathBase);

			app.Use(async (context, next) => {

				var req = context.Request;
				var res = context.Response;
				var location = req.Path.Value;
				var is301 = false;

				if (location.EndsWith("/") == false) {
					is301 = true;
					location = $"{location}/";
				}

				var reqPath = location.ToLower();
				try {
					if (reqPath == requestPathBase) {
						if (is301) {
							res.StatusCode = 301;
							res.Headers["Location"] = location;
							return;
						}
						//首页
						var sb = new StringBuilder();
						sb.AppendLine(@"<ul clreplaced=""treeview-menu"">");
						foreach (var et in dicEnreplacedyTypes) {
							sb.AppendLine($@"<li><a href=""{requestPathBase}{et.Key}/""><i clreplaced=""fa fa-circle-o""></i>{fsql.CodeFirst.GetTableByEnreplacedy(et.Value).Comment.IsNullOrEmtpty(et.Key)}</a></li>");
						}
						sb.AppendLine(@"</ul>");
						await res.WriteAsync(Views.Index.Replace(@"<ul clreplaced=""treeview-menu""></ul>", sb.ToString()));
						return;
					}
					else if (reqPath.StartsWith(restfulRequestPath)) {
						//动态接口
						if (await Restful.Use(context, fsql, restfulRequestPath, dicEnreplacedyTypes)) return;
					}
					else if (reqPath.StartsWith(requestPathBase)) {
						if (reqPath == "/favicon.ico/") return;
						//前端UI
						if (await Admin.Use(context, fsql, requestPathBase, dicEnreplacedyTypes)) return;
					}

				} catch (Exception ex) {
					await Utils.Jsonp(context, new { code = 500, message = ex.Message });
					return;
				}
				await next();
			});

			return app;
		}

19 Source : RazorModel.cs
with MIT License
from 2881099

public string GetColumnDefaultValue(DbColumnInfo col, bool isInsertValueSql)
	{
		var defval = col.DefaultValue?.Trim();
		if (string.IsNullOrEmpty(defval)) return null;
		var cstype = col.CsType.NullableTypeOrThis();
		if (fsql.Ado.DataType == DataType.SqlServer || fsql.Ado.DataType == DataType.OdbcSqlServer)
		{
			if (defval.StartsWith("((") && defval.EndsWith("))")) defval = defval.Substring(2, defval.Length - 4);
			else if (defval.StartsWith("('") && defval.EndsWith("')")) defval = defval.Substring(2, defval.Length - 4).Replace("''", "'");
			else if(defval.StartsWith("(") && defval.EndsWith(")")) defval = defval.Substring(1, defval.Length - 2);
			else return null;
		}
		else if ((cstype == typeof(string) && defval.StartsWith("'") && defval.EndsWith("'::character varying") ||
			cstype == typeof(Guid) && defval.StartsWith("'") && defval.EndsWith("'::uuid")
			) && (fsql.Ado.DataType == DataType.PostgreSQL || fsql.Ado.DataType == DataType.OdbcPostgreSQL ||
				fsql.Ado.DataType == DataType.OdbcKingbaseES ||
				fsql.Ado.DataType == DataType.ShenTong))
        {
			defval = defval.Substring(1, defval.LastIndexOf("'::") - 1).Replace("''", "'");
		}
		else if (defval.StartsWith("'") && defval.EndsWith("'"))
		{
			defval = defval.Substring(1, defval.Length - 2).Replace("''", "'");
			if (fsql.Ado.DataType == DataType.MySql || fsql.Ado.DataType == DataType.OdbcMySql) defval = defval.Replace("\\\\", "\\");
		}
		if (cstype.IsNumberType() && decimal.TryParse(defval, out var trydec))
		{
			if (isInsertValueSql) return defval;
			if (cstype == typeof(float)) return defval + "f";
			if (cstype == typeof(double)) return defval + "d";
			if (cstype == typeof(decimal)) return defval + "M";
			return defval;
		}
		if (cstype == typeof(Guid) && Guid.TryParse(defval, out var tryguid)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"Guid.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
		if (cstype == typeof(DateTime) && DateTime.TryParse(defval, out var trydt)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"DateTime.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
		if (cstype == typeof(TimeSpan) && TimeSpan.TryParse(defval, out var tryts)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"TimeSpan.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
		if (cstype == typeof(string)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\"";
		if (cstype == typeof(bool)) return isInsertValueSql ? defval : (defval == "1" || defval == "t" ? "true" : "false");
		if (fsql.Ado.DataType == DataType.MySql || fsql.Ado.DataType == DataType.OdbcMySql)
			if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
				if (isInsertValueSql) return (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval);
		return isInsertValueSql ? defval : null; //sql function or exp
	}

19 Source : Config.cs
with GNU General Public License v3.0
from 2dust

public string getSubRemarks(Config config)
        {
            string subRemarks = string.Empty;
            if (Utils.IsNullOrEmpty(subid))
            {
                return subRemarks;
            }
            foreach (SubItem sub in config.subItem)
            {
                if (sub.id.EndsWith(subid))
                {
                    return sub.remarks;
                }
            }
            if (subid.Length <= 4)
            {
                return subid;
            }
            return subid.Substring(0, 4);
        }

See More Examples