System.Text.StringBuilder.ToString()

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

40717 Examples 7

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

private string RebuildArgList(string argList, string extras)
        {
            if (string.IsNullOrEmpty(extras))
                return argList;

            StringBuilder sb = new StringBuilder();
            string s;
            Dictionary<string, string> eArgs = Helper.ParseOptions(argList);
            Dictionary<string, string> extraDict = Helper.ParseOptions(extras);

            foreach (var key in extraDict.Keys)
            {
                if (eArgs.ContainsKey(key))
                {
                    eArgs[key] = extraDict[key];
                }
                else
                {
                    eArgs.Add(key, extraDict[key]);
                }
            }


            extraDict.Clear();
            extraDict = null;

            foreach (var key in eArgs.Keys)
            {
                sb.AppendFormat("{0} {1} ", key, eArgs[key]);
            }

            s = sb.ToString().TrimEnd();

            eArgs.Clear();
            eArgs = null;

            sb.Clear();
            sb = null;

            return s;
        }

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

private static string BuildFetchSQLQuery(
            ref string baseQueryHash,
            string content, 
            string suser, 
            DateTime begin, DateTime end,
            int rowBegin,int rowEnd)
        {
            bool linkAnd = false;
            string query;

            StringBuilder sb = new StringBuilder();
            StringBuilder cond = new StringBuilder();

            if (!CacheManager.TryGetCachedResult<string>(baseQueryHash, out query))
            {

                if (!string.IsNullOrEmpty(suser))
                    sb.AppendFormat(SEARCH_SUSER_ID_GET_SQL, suser.Trim());

                if (!string.IsNullOrEmpty(content))
                {
                    cond.AppendFormat(SEARCH_COND_CONTENT, content.Trim());
                    linkAnd = true;
                }

                if (!string.IsNullOrEmpty(suser))
                {
                    if (linkAnd)
                        cond.Append(" AND ");
                    else
                        linkAnd = true;

                    cond.Append(SEARCH_COND_SUSER);
                }

                if (begin != DateTime.MinValue && end != DateTime.MinValue)
                {
                    if (linkAnd)
                        cond.Append(" AND ");

                    cond.AppendFormat(SEARCH_COND_DATE, begin.ToString(), end.ToString());

                }

                sb.Append(SEARCH_SQL_BASE);

                if (cond.Length > 0)
                {
                    cond.Insert(0, "WHERE ");
                    sb.Replace("%%CONDITIONS%%", cond.ToString());
                }
                else
                {
                    sb.Replace("%%CONDITIONS%%", string.Empty);
                }

                if (!string.IsNullOrEmpty(content))
                    sb.Replace("%%COUNT_CONDITION%%", string.Format(SEARCH_COND_COUNT_CONTENT, content));
                else
                    sb.Replace("%%COUNT_CONDITION%%", SEARCH_COND_COUNT_ALL);


                if (!string.IsNullOrEmpty(suser))
                    sb.Append(" AND EntryCount > 0");

                sb.Append(";");

                baseQueryHash = Helper.Md5(sb.ToString());

                CacheManager.CacheObject(baseQueryHash, sb.ToString());
            }
            else
            {
                sb.Append(query);
            }

            sb.Replace("%%ROW_LIMIT_CONDITION%%",
                string.Format("RowNum BETWEEN {0} AND {1}", rowBegin, rowEnd));
            
            query = sb.ToString();

            cond.Clear();
            sb.Clear();

            cond = null;
            sb = null;

            return query;
        }

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

private string NormalizeTerm(string s)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var c in s)
            {
                if (char.IsLetterOrDigit(c) || c == ' ')
                    sb.Append(char.ToLower(c));
                else if (char.IsSeparator(c))
                    sb.Append(' ');
            }

            s = sb.ToString();
            sb.Clear();
            sb = null;

            return s;
        }

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

public bool PushBackToBridge()
        {
            bool result;

            if (this.respData.Length > 0)
            {
                result = this.req.Reply(this.respData.ToString());
            }

            return true;
        }

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

public string GetTransportString()
        {
            StringBuilder sb = new StringBuilder();

            string s;

            if (RepCount > 1)
                sb.Append(MakeTag("Baslik", this.Baslik, "RepCount", RepCount)); 
            else
                sb.Append(MakeTag("Baslik", this.Baslik));

            sb.Append(MakeTag("Suser", Suser));
            sb.Append(MakeTag("Date", Date));
            sb.Append(MakeTag("Desc", Content));

            s = sb.ToString();
            sb.Clear();
            sb = null;
            
            return s;
        }

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

private static string HashWith(HashAlgorithm algo,string v)
        {
            string hash;
            StringBuilder sb = new StringBuilder();
            byte[] bytes = Encoding.ASCII.GetBytes(v);

            bytes = algo.ComputeHash(bytes);
            algo.Dispose();

            for (int i = 0; i < bytes.Length; i++)
                sb.Append(bytes[i].ToString("X2"));

            hash = sb.ToString();
            sb.Clear();
            sb = null;
            
            return hash;
        }

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

public void SendTalkData(Dictionary<string, string> data)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var key in data.Keys)
            {
                sb.AppendFormat("{0}={1};", key, data[key]);
            }

            SendPacket(sb.ToString());

            sb.Clear();
            sb = null;
        }

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

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

            Channels channels = env.Server.Channels;

            Channel? c;

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

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

                const int pageSize = 8;

                StringBuilder builder = new();

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

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

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

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

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

                return;
            }

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

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

private static void GenSessionId()
        {
            StringBuilder sb = new StringBuilder();
            string hx = "abcdefgh0123456789";
            Random rnd = new Random();

            for (int i=0;i<16;i++)
            {
                sb.Append(hx[rnd.Next(hx.Length)]);
            }

            sessionId = sb.ToString();
            sb.Clear();
            sb = null;
        }

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

public void RebuildList() {
            if (MDraw.DefaultFont == null || Client == null || Channels == null)
                return;

            DataPlayerInfo[] all = Client.Data.GetRefs<DataPlayerInfo>();

            List<Blob> list = new() {
                new Blob {
                    Text = $"{all.Length} player{(all.Length == 1 ? "" : "s")}",
                    Color = ColorCountHeader
                }
            };

            StringBuilder builder = new();


            switch (Mode) {
                case ListMode.Clreplacedic:
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        builder.Append(player.DisplayName);

                        DataChannelList.Channel channel = Channels.List.FirstOrDefault(c => c.Players.Contains(player.ID));
                        if (channel != null && !string.IsNullOrEmpty(channel.Name)) {
                            builder
                                .Append(" #")
                                .Append(channel.Name);
                        }

                        if (Client.Data.TryGetBoundRef(player, out DataPlayerState state))
                            AppendState(builder, state);

                        builder.AppendLine();
                    }

                    list.Add(new() {
                        Text = builder.ToString().Trim(),
                        ScaleFactor = 1f
                    });
                    break;

                case ListMode.Channels:
                    HashSet<DataPlayerInfo> listed = new();

                    DataChannelList.Channel own = Channels.List.FirstOrDefault(c => c.Players.Contains(Client.PlayerInfo.ID));

                    if (own != null) {
                        list.Add(new() {
                            Text = own.Name,
                            Color = ColorChannelHeaderOwn
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in own.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p))) 
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 0.5f
                        });
                    }

                    foreach (DataChannelList.Channel channel in Channels.List) {
                        if (channel == own)
                            continue;

                        list.Add(new() {
                            Text = channel.Name,
                            Color = ColorChannelHeader
                        });

                        builder.Clear();
                        foreach (DataPlayerInfo player in channel.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p)))
                            listed.Add(ListPlayerUnderChannel(builder, player));
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }

                    bool wrotePrivate = false;

                    builder.Clear();
                    foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
                        if (listed.Contains(player) || string.IsNullOrWhiteSpace(player.DisplayName))
                            continue;

                        if (!wrotePrivate) {
                            wrotePrivate = true;
                            list.Add(new() {
                                Text = "!<private>",
                                Color = ColorChannelHeaderPrivate
                            });
                        }

                        builder.AppendLine(player.DisplayName);
                    }

                    if (wrotePrivate) {
                        list.Add(new() {
                            Text = builder.ToString().Trim(),
                            ScaleFactor = 1f
                        });
                    }
                    break;
            }

            List = list;
        }

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

[RCEndpoint(true, "/settings", "?module={id}", "?module=CelesteNet.Server", "Server Settings", "Get the settings of any server module as YAML.")]
        public static void Settings(Frontend f, HttpRequestEventArgs c) {
            NameValueCollection args = f.ParseQueryString(c.Request.RawUrl);
            string? moduleID = args["module"];
            if (moduleID.IsNullOrEmpty()) {
                c.Response.StatusCode = (int) HttpStatusCode.BadRequest;
                f.RespondJSON(c, new {
                    Error = "No ID."
                });
                return;
            }

            CelesteNetServerModuleSettings? settings;
            if (moduleID == "CelesteNet.Server") {
                settings = f.Server.Settings;
            } else {
                lock (f.Server.Modules)
                    settings = f.Server.Modules.FirstOrDefault(m => m.Wrapper.ID == moduleID)?.GetSettings();
            }

            if (settings == null) {
                c.Response.StatusCode = (int) HttpStatusCode.NotFound;
                f.RespondJSON(c, new {
                    Error = $"Module {moduleID} not loaded or doesn't have settings."
                });
                return;
            }

            if (c.Request.HttpMethod == "POST") {
                try {
                    using (StreamReader sr = new(c.Request.InputStream, Encoding.UTF8, false, 1024, true))
                        settings.Load(sr);
                    settings.Save();
                    f.RespondJSON(c, new {
                        Info = "Success."
                    });
                    return;
                } catch (Exception e) {
                    f.RespondJSON(c, new {
                        Error = e.ToString()
                    });
                    return;
                }
            }

            StringBuilder sb = new();
            using (StringWriter sw = new(sb))
                settings.Save(sw);
            f.Respond(c, sb.ToString());
        }

19 Source : MainActivity.cs
with Microsoft Public License
from 0x0ade

public static void SDL_Main()
		{
			if (string.IsNullOrEmpty(Instance.GamePath))
			{
				AlertDialog dialog = null;
				Instance.RunOnUiThread(() =>
				{
					using (AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(Instance))
					{
						StringBuilder stringBuilder = new StringBuilder();
						stringBuilder.Append("Game not found: ").AppendLine(Game);
						foreach (Java.IO.File root in Instance.GetExternalFilesDirs(null))
						{
							stringBuilder.AppendLine();
							stringBuilder.AppendLine(Path.Combine(root.AbsolutePath, Game));
						}

						dialogBuilder.SetMessage(stringBuilder.ToString());
						dialogBuilder.SetCancelable(false);
						dialog = dialogBuilder.Show();
					}
				});

				while (dialog == null || dialog.IsShowing)
				{
					System.Threading.Thread.Sleep(0);
				}
				dialog.Dispose();
				return;
			}

			// Replace the following with whatever was in your Program.Main method.

			/*/
			using (TestGame game = new TestGame())
			{
				game.Run();
			}
			/*/
			replacedembly.LoadFrom(Instance.GamePath).EntryPoint.Invoke(null, new object[] { new string[] { /*args*/ } });
			/**/
		}

19 Source : Message.cs
with zlib License
from 0x0ade

public static string ToString(IntPtr hWnd, int msg, IntPtr wparam, IntPtr lparam, IntPtr result) {
            StringBuilder builder = new StringBuilder();
            builder
                .Append("msg=0x").Append(Convert.ToString(msg, 16)).Parenthesize(MsgToString(msg))
                .Append(" hwnd=0x").Append(Convert.ToString((long) hWnd, 16))
                .Append(" wparam=0x").Append(Convert.ToString((long) wparam, 16))
                .Append(" lparam=0x").Append(Convert.ToString((long) lparam, 16))
                .Parenthesize(msg == (int) Messages.WM_PARENTNOTIFY ? MsgToString((int) wparam & 0x0000FFFF) : null)
                .Append(" result=0x").Append(Convert.ToString((long) result, 16));
            return builder.ToString();
        }

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

public string GetCommandPage(ChatCMDEnv env, int page = 0) {
            const int pageSize = 8;

            string prefix = Chat.Settings.CommandPrefix;
            StringBuilder builder = new();

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

            for (int i = page * pageSize; i < (page + 1) * pageSize && i < Chat.Commands.All.Count; i++) {
                ChatCMD cmd = Chat.Commands.All[i];
                builder
                    .Append(prefix)
                    .Append(cmd.ID)
                    .Append(" ")
                    .Append(cmd.Args)
                    .AppendLine();
            }

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

            return builder.ToString().Trim();
        }

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

public string Help_GetCommandSnippet(ChatCMDEnv env, ChatCMD cmd) {
            string prefix = Chat.Settings.CommandPrefix;
            StringBuilder builder = new();

            builder
                .Append(prefix)
                .Append(cmd.ID)
                .Append(" ")
                .Append(cmd.Args)
                .AppendLine()
                .AppendLine(cmd.Help);

            return builder.ToString().Trim();
        }

19 Source : CelesteNetUtils.BinaryRWCompat.cs
with MIT License
from 0x0ade

[Obsolete("Use CelesteNetBinaryReader instead.")]
        public static string ReadNetString(this BinaryReader stream) {
            StringBuilder sb = new();
            char c;
            while ((c = stream.ReadChar()) != '\0') {
                sb.Append(c);
                if (sb.Length > 4096)
                    throw new Exception("String too long.");
            }
            return sb.ToString();
        }

19 Source : FileSystemHelper.cs
with zlib License
from 0x0ade

public static string ChangePath(string path, char separator) {
            // Can't trust File.Exists if MONO_IOMAP_ALL is set.
            if (!MONO_IOMAP_ALL) {
                string pathMaybe = path;
                // Check if target exists in the first place.
                if (Directory.Exists(path) || File.Exists(path))
                    return pathMaybe;

                // Try a simpler fix first: Maybe the casing is already correct...
                pathMaybe = path.Replace('/', separator).Replace('\\', separator);
                if (Directory.Exists(pathMaybe) || File.Exists(pathMaybe))
                    return pathMaybe;

                // Fall back to the slow rebuild.
            }

            // Check if the path has been rebuilt before.
            Dictionary<string, string> cachedPaths;
            if (!_CachedChanges.TryGetValue(separator, out cachedPaths))
                _CachedChanges[separator] = cachedPaths = new Dictionary<string, string>();
            string cachedPath;
            if (cachedPaths.TryGetValue(path, out cachedPath))
                return cachedPath;

            // Split and rebuild path.

            string[] pathSplit = path.Split(DirectorySeparatorChars);

            StringBuilder builder = new StringBuilder();

            bool unixRooted = false;

            if (Path.IsPathRooted(path)) {
                // The first element in a rooted path will always be correct.
                // On Windows, this will be the drive letter.
                // On Unix and Unix-like systems, this will be empty.
                if (unixRooted = (builder.Length == 0))
                    // Path is rooted, but the path separator is the root.
                    builder.Append(separator);
                else
                    builder.Append(pathSplit[0]);
            }

            for (int i = 1; i < pathSplit.Length; i++) {
                string next;
                if (i < pathSplit.Length - 1)
                    next = GetDirectory(builder.ToString(), pathSplit[i]);
                else
                    next = GetTarget(builder.ToString(), pathSplit[i]);
                next = next ?? pathSplit[i];

                if (i != 1 || !unixRooted)
                    builder.Append(separator);

                builder.Append(next);
            }

            return cachedPaths[path] = builder.ToString();
        }

19 Source : SqlBuilderBase.cs
with MIT License
from 0x1000000

public override string ToString()
        {
            return this.Builder.ToString();
        }

19 Source : SqlStatementBuilderBase.cs
with MIT License
from 0x1000000

private string BuildFkName(IExprTableFullName tableIn, IExprTableFullName foreignTableIn)
        {
            StringBuilder nameBuilder = new StringBuilder();

            ExprTableFullName table = tableIn.AsExprTableFullName();

            ExprTableFullName foreignTable = foreignTableIn.AsExprTableFullName();

            var schemaName = table.DbSchema != null ? this.Options.MapSchema(table.DbSchema.Schema.Name) + "_" : null;

            nameBuilder.Append("FK_");
            if (schemaName != null)
            {
                nameBuilder.Append(schemaName);
                nameBuilder.Append('_');
            }
            nameBuilder.Append(table.TableName.Name);
            nameBuilder.Append("_to_");
            if (schemaName != null)
            {
                nameBuilder.Append(schemaName);
                nameBuilder.Append('_');
            }
            nameBuilder.Append(foreignTable.TableName.Name);

            return nameBuilder.ToString();
        }

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

private static void Generate(string projDir, string relativePath, IReadOnlyList<NodeModel> model, Action<IReadOnlyList<NodeModel>, StringBuilder> generator)
        {
            var path = Path.Combine(projDir, relativePath);

            StringBuilder newContentBuilder = new StringBuilder();

            bool skip = false;
            foreach (var line in File.ReadLines(path))
            {
                if (line.Contains("//CodeGenEnd"))
                {
                    generator.Invoke(model, newContentBuilder);
                    skip = false;
                }

                if (!skip)
                {
                    newContentBuilder.AppendLine(line);
                }

                if (line.Contains("//CodeGenStart"))
                {
                    skip = true;
                }
            }

            File.WriteAllText(path, newContentBuilder.ToString());
        }

19 Source : SyntaxTreeOperationsTest.cs
with MIT License
from 0x1000000

[Test]
        public void WalkThroughTest()
        {
            var tUser = Tables.User();
            var tCustomer = Tables.Customer();

            var e = Select(tUser.UserId, tUser.FirstName, tCustomer.CustomerId)
                .From(tUser)
                .InnerJoin(tCustomer, on: tCustomer.UserId == tUser.UserId)
                .Done();

            string expected = "0ExprQuerySpecification,1Int32TableColumn,2ExprTableAlias,3ExprAliasGuid," +
                              "2ExprColumnName,1StringTableColumn,2ExprTableAlias,3ExprAliasGuid," +
                              "2ExprColumnName,1Int32TableColumn,2ExprTableAlias,3ExprAliasGuid,2ExprColumnName," +
                              "1ExprJoinedTable,2User,3ExprTableFullName,4ExprDbSchema,5ExprSchemaName," +
                              "4ExprTableName,3ExprTableAlias,4ExprAliasGuid,2Customer,3ExprTableFullName," +
                              "4ExprDbSchema,5ExprSchemaName,4ExprTableName,3ExprTableAlias,4ExprAliasGuid," +
                              "2ExprBooleanEq,3NullableInt32TableColumn,4ExprTableAlias,5ExprAliasGuid," +
                              "4ExprColumnName,3Int32TableColumn,4ExprTableAlias,5ExprAliasGuid,4ExprColumnName,";

            StringBuilder builder = new StringBuilder();

            e.SyntaxTree().WalkThrough((expr, tier) =>
            {
                builder.Append(tier);
                builder.Append(expr.GetType().Name);
                builder.Append(',');
                return VisitorResult<int>.Continue(tier+1);
            }, 0);

            replacedert.AreEqual(expected, builder.ToString());
        }

19 Source : SyntaxTreeOperationsTest.cs
with MIT License
from 0x1000000

[Test]
        public void TestExportImportXml()
        {
            var tUser = Tables.User();
            var tCustomer = Tables.Customer();

            var selectExpr = Select(tUser.UserId, tUser.FirstName, tCustomer.CustomerId, Cast(Literal(12.8m), SqlType.Decimal(new DecimalPrecisionScale(10, 2))).As("Salary"))
                .From(tUser)
                .InnerJoin(tCustomer, on: tCustomer.UserId == tUser.UserId)
                .Where(tUser.Version == 5 & tUser.RegDate > new DateTime(2020, 10, 18, 1,2,3,400) & tUser.RegDate <= new DateTime(2021,01,01))
                .OrderBy(tUser.FirstName)
                .OffsetFetch(100, 5)
                .Done();

            var sb = new StringBuilder();
            
            using XmlWriter writer = XmlWriter.Create(sb);
            selectExpr.SyntaxTree().ExportToXml(writer);

            var doc = new XmlDoreplacedent();
            doc.LoadXml(sb.ToString());

            var res = ExprDeserializer.DeserializeFormXml(doc.DoreplacedentElement!);
            replacedert.AreEqual(selectExpr.ToSql(), res.ToSql());
        }

19 Source : Form1.cs
with GNU General Public License v3.0
from 0x4F776C

private string RunCommand(string script)
        {
            Runspace runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();

            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(script);
            pipeline.Commands.Add("Out-String");

            Collection<PSObject> results = pipeline.Invoke();

            runspace.Close();

            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject psObject in results)
                stringBuilder.AppendLine(psObject.ToString());
            return stringBuilder.ToString();
        }

19 Source : FourCC.cs
with MIT License
from 0xC0000054

public override string ToString()
        {
            uint value = this.Value;

            StringBuilder builder = new StringBuilder(20);
            builder.Append('\'');

            for (int i = 3; i >= 0; i--)
            {
                uint c = (value >> (i * 8)) & 0xff;

                // Ignore any bytes that are not printable ASCII characters
                // because they can not be displayed in the debugger watch windows.

                if (c >= 0x20 && c <= 0x7e)
                {
                    builder.Append((char)c);
                }
            }
            builder.Append('\'');
            builder.Append(" (0x").Append(value.ToString("X8")).Append(')');

            return builder.ToString();
        }

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

private static async Task Step19ExportToXml(ISqDatabase database)
        {
            var tableUser = new TableUser(Alias.Empty);

            var selectExpr = Select(tableUser.FirstName, tableUser.LastName)
                .From(tableUser)
                .Where(tableUser.LastName == "Sturman")
                .Done();

            //Exporting
            var stringBuilder = new StringBuilder();
            using XmlWriter writer = XmlWriter.Create(stringBuilder);
            selectExpr.SyntaxTree().ExportToXml(writer);

            //Importing
            XmlDoreplacedent doreplacedent = new XmlDoreplacedent();
            doreplacedent.LoadXml(stringBuilder.ToString());
            var restored = (ExprQuerySpecification)ExprDeserializer
                .DeserializeFormXml(doreplacedent.DoreplacedentElement!);

            var result = await restored
                .QueryList(database, r => (tableUser.FirstName.Read(r), tableUser.LastName.Read(r)));

            foreach (var name in result)
            {
                Console.WriteLine(name);
            }
        }

19 Source : GmicPipeServer.cs
with GNU General Public License v3.0
from 0xC0000054

private unsafe string PrepareCroppedLayers(InputMode inputMode, RectangleF cropRect)
        {
            if (inputMode == InputMode.NoInput)
            {
                return string.Empty;
            }

            IReadOnlyList<GmicLayer> layers = GetRequestedLayers(inputMode);

            if (layers.Count == 0)
            {
                return string.Empty;
            }

            if (memoryMappedFiles.Capacity < layers.Count)
            {
                memoryMappedFiles.Capacity = layers.Count;
            }

            StringBuilder reply = new StringBuilder();

            foreach (GmicLayer layer in layers)
            {
                Surface surface = layer.Surface;
                bool disposeSurface = false;
                int destinationImageStride = surface.Stride;

                if (cropRect != WholeImageCropRect)
                {
                    int cropX = (int)Math.Floor(cropRect.X * layer.Width);
                    int cropY = (int)Math.Floor(cropRect.Y * layer.Height);
                    int cropWidth = (int)Math.Min(layer.Width - cropX, 1 + Math.Ceiling(cropRect.Width * layer.Width));
                    int cropHeight = (int)Math.Min(layer.Height - cropY, 1 + Math.Ceiling(cropRect.Height * layer.Height));

                    try
                    {
                        surface = layer.Surface.CreateWindow(cropX, cropY, cropWidth, cropHeight);
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        throw new InvalidOperationException(string.Format("Surface.CreateWindow bounds invalid, cropRect={0}", cropRect.ToString()), ex);
                    }
                    disposeSurface = true;
                    destinationImageStride = cropWidth * ColorBgra.SizeOf;
                }

                string mapName = "pdn_" + Guid.NewGuid().ToString();

                try
                {
                    MemoryMappedFile file = MemoryMappedFile.CreateNew(mapName, surface.Scan0.Length);
                    memoryMappedFiles.Add(file);

                    using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                    {
                        byte* destination = null;
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try
                        {
                            accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref destination);

                            for (int y = 0; y < surface.Height; y++)
                            {
                                ColorBgra* src = surface.GetRowAddressUnchecked(y);
                                byte* dst = destination + (y * destinationImageStride);

                                Buffer.MemoryCopy(src, dst, destinationImageStride, destinationImageStride);
                            }
                        }
                        finally
                        {
                            if (destination != null)
                            {
                                accessor.SafeMemoryMappedViewHandle.ReleasePointer();
                            }
                        }
                    }
                }
                finally
                {
                    if (disposeSurface)
                    {
                        surface.Dispose();
                    }
                }

                reply.AppendFormat(
                    CultureInfo.InvariantCulture,
                    "{0},{1},{2},{3}\n",
                    mapName,
                    surface.Width.ToString(CultureInfo.InvariantCulture),
                    surface.Height.ToString(CultureInfo.InvariantCulture),
                    destinationImageStride.ToString(CultureInfo.InvariantCulture));
            }

            return reply.ToString();
        }

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

public static string[] SplitCommandLine(string commandLine)
        {
            var translatedArguments = new StringBuilder(commandLine);
            var escaped = false;
            for (var i = 0; i < translatedArguments.Length; i++)
            {
                if (translatedArguments[i] == '"')
                {
                    escaped = !escaped;
                }
                if (translatedArguments[i] == ' ' && !escaped)
                {
                    translatedArguments[i] = '\n';
                }
            }

            var toReturn = translatedArguments.ToString().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            for (var i = 0; i < toReturn.Length; i++)
            {
                toReturn[i] = RemoveMatchingQuotes(toReturn[i]);
            }
            return toReturn;
        }

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

public static string CreateMD5(string input)
        {
            // Use input string to calculate MD5 hash
            using (System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
                byte[] hashBytes = md5.ComputeHash(inputBytes);

                // Convert the byte array to hexadecimal string
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hashBytes.Length; i++)
                {
                    sb.Append(hashBytes[i].ToString("X2"));
                }
                return sb.ToString();
            }
        }

19 Source : ExifParser.cs
with MIT License
from 0xC0000054

private string GetValueStringFromOffset()
            {
                string valueString;

                TagDataType type = this.entry.Type;
                uint count = this.entry.Count;
                uint offset = this.entry.Offset;

                if (count == 0)
                {
                    return string.Empty;
                }

                int typeSizeInBytes = TagDataTypeUtil.GetSizeInBytes(type);

                if (typeSizeInBytes == 1)
                {
                    byte[] bytes = new byte[count];

                    if (this.offsetIsBigEndian)
                    {
                        switch (count)
                        {
                            case 1:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                break;
                            case 2:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                bytes[1] = (byte)((offset >> 16) & 0x000000ff);
                                break;
                            case 3:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                bytes[1] = (byte)((offset >> 16) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 8) & 0x000000ff);
                                break;
                            case 4:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                bytes[1] = (byte)((offset >> 16) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 8) & 0x000000ff);
                                bytes[3] = (byte)(offset & 0x000000ff);
                                break;
                        }
                    }
                    else
                    {
                        switch (count)
                        {
                            case 1:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                break;
                            case 2:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                bytes[1] = (byte)((offset >> 8) & 0x000000ff);
                                break;
                            case 3:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                bytes[1] = (byte)((offset >> 8) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 16) & 0x000000ff);
                                break;
                            case 4:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                bytes[1] = (byte)((offset >> 8) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 16) & 0x000000ff);
                                bytes[3] = (byte)((offset >> 24) & 0x000000ff);
                                break;
                        }
                    }

                    if (type == TagDataType.Ascii)
                    {
                        valueString = Encoding.ASCII.GetString(bytes).TrimEnd('\0');
                    }
                    else if (count == 1)
                    {
                        valueString = bytes[0].ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        StringBuilder builder = new StringBuilder();

                        uint lasreplacedemIndex = count - 1;

                        for (int i = 0; i < count; i++)
                        {
                            builder.Append(bytes[i].ToString(CultureInfo.InvariantCulture));

                            if (i < lasreplacedemIndex)
                            {
                                builder.Append(",");
                            }
                        }

                        valueString = builder.ToString();
                    }
                }
                else if (typeSizeInBytes == 2)
                {
                    ushort[] values = new ushort[count];
                    if (this.offsetIsBigEndian)
                    {
                        switch (count)
                        {
                            case 1:
                                values[0] = (ushort)((offset >> 16) & 0x0000ffff);
                                break;
                            case 2:
                                values[0] = (ushort)((offset >> 16) & 0x0000ffff);
                                values[1] = (ushort)(offset & 0x0000ffff);
                                break;
                        }
                    }
                    else
                    {
                        switch (count)
                        {
                            case 1:
                                values[0] = (ushort)(offset & 0x0000ffff);
                                break;
                            case 2:
                                values[0] = (ushort)(offset & 0x0000ffff);
                                values[1] = (ushort)((offset >> 16) & 0x0000ffff);
                                break;
                        }
                    }

                    if (count == 1)
                    {
                        switch (type)
                        {
                            case TagDataType.SShort:
                                valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture);
                                break;
                            case TagDataType.Short:
                            default:
                                valueString = values[0].ToString(CultureInfo.InvariantCulture);
                                break;
                        }
                    }
                    else
                    {
                        switch (type)
                        {
                            case TagDataType.SShort:
                                valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture) + "," +
                                              ((short)values[1]).ToString(CultureInfo.InvariantCulture);
                                break;
                            case TagDataType.Short:
                            default:
                                valueString = values[0].ToString(CultureInfo.InvariantCulture) + "," +
                                              values[1].ToString(CultureInfo.InvariantCulture);
                                break;
                        }
                    }
                }
                else
                {
                    valueString = offset.ToString(CultureInfo.InvariantCulture);
                }

                return valueString;
            }

19 Source : ExifParser.cs
with MIT License
from 0xC0000054

private string GetValueStringFromOffset()
            {
                string valueString;

                TagDataType type = entry.Type;
                uint count = entry.Count;
                uint offset = entry.Offset;

                if (count == 0)
                {
                    return string.Empty;
                }

                int typeSizeInBytes = TagDataTypeUtil.GetSizeInBytes(type);

                if (typeSizeInBytes == 1)
                {
                    byte[] bytes = new byte[count];

                    if (offsetIsBigEndian)
                    {
                        switch (count)
                        {
                            case 1:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                break;
                            case 2:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                bytes[1] = (byte)((offset >> 16) & 0x000000ff);
                                break;
                            case 3:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                bytes[1] = (byte)((offset >> 16) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 8) & 0x000000ff);
                                break;
                            case 4:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                bytes[1] = (byte)((offset >> 16) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 8) & 0x000000ff);
                                bytes[3] = (byte)(offset & 0x000000ff);
                                break;
                        }
                    }
                    else
                    {
                        switch (count)
                        {
                            case 1:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                break;
                            case 2:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                bytes[1] = (byte)((offset >> 8) & 0x000000ff);
                                break;
                            case 3:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                bytes[1] = (byte)((offset >> 8) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 16) & 0x000000ff);
                                break;
                            case 4:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                bytes[1] = (byte)((offset >> 8) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 16) & 0x000000ff);
                                bytes[3] = (byte)((offset >> 24) & 0x000000ff);
                                break;
                        }
                    }

                    if (type == TagDataType.Ascii)
                    {
                        valueString = Encoding.ASCII.GetString(bytes).TrimEnd('\0');
                    }
                    else if (count == 1)
                    {
                        valueString = bytes[0].ToString(CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        StringBuilder builder = new StringBuilder();

                        uint lasreplacedemIndex = count - 1;

                        for (int i = 0; i < count; i++)
                        {
                            builder.Append(bytes[i].ToString(CultureInfo.InvariantCulture));

                            if (i < lasreplacedemIndex)
                            {
                                builder.Append(",");
                            }
                        }

                        valueString = builder.ToString();
                    }
                }
                else if (typeSizeInBytes == 2)
                {
                    ushort[] values = new ushort[count];
                    if (offsetIsBigEndian)
                    {
                        switch (count)
                        {
                            case 1:
                                values[0] = (ushort)((offset >> 16) & 0x0000ffff);
                                break;
                            case 2:
                                values[0] = (ushort)((offset >> 16) & 0x0000ffff);
                                values[1] = (ushort)(offset & 0x0000ffff);
                                break;
                        }
                    }
                    else
                    {
                        switch (count)
                        {
                            case 1:
                                values[0] = (ushort)(offset & 0x0000ffff);
                                break;
                            case 2:
                                values[0] = (ushort)(offset & 0x0000ffff);
                                values[1] = (ushort)((offset >> 16) & 0x0000ffff);
                                break;
                        }
                    }

                    if (count == 1)
                    {
                        switch (type)
                        {
                            case TagDataType.SShort:
                                valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture);
                                break;
                            case TagDataType.Short:
                            default:
                                valueString = values[0].ToString(CultureInfo.InvariantCulture);
                                break;
                        }
                    }
                    else
                    {
                        switch (type)
                        {
                            case TagDataType.SShort:
                                valueString = ((short)values[0]).ToString(CultureInfo.InvariantCulture) + "," +
                                              ((short)values[1]).ToString(CultureInfo.InvariantCulture);
                                break;
                            case TagDataType.Short:
                            default:
                                valueString = values[0].ToString(CultureInfo.InvariantCulture) + "," +
                                              values[1].ToString(CultureInfo.InvariantCulture);
                                break;
                        }
                    }
                }
                else
                {
                    valueString = offset.ToString(CultureInfo.InvariantCulture);
                }

                return valueString;
            }

19 Source : StringUtils.cs
with Apache License 2.0
from 0xFireball

public static string SecureRandomString(int maxSize)
        {
            var chars = new char[62];
            chars =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            var data = new byte[1];
            using (var prng = RandomNumberGenerator.Create())
            {
                prng.GetBytes(data);
                data = new byte[maxSize];
                prng.GetBytes(data);
            }
            var result = new StringBuilder(maxSize);
            foreach (var b in data)
            {
                result.Append(chars[b % (chars.Length)]);
            }
            return result.ToString();
        }

19 Source : FilenameProvider.cs
with MIT License
from 0xd4d

static string ReplaceInvalidFilenameChars(string candidate) {
			var invalidChars = Path.GetInvalidFileNameChars();
			if (candidate.IndexOfAny(invalidChars) < 0)
				return candidate;
			var sb = new System.Text.StringBuilder();
			foreach (var c in candidate) {
				if (Array.IndexOf(invalidChars, c) >= 0)
					sb.Append('-');
				else
					sb.Append(c);
			}
			return sb.ToString();
		}

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

public static Uri AddQueryParameters(Uri uri, IEnumerable<KeyValuePair<string, string>> parameters)
        {
            var builder = new StringBuilder();
            foreach (var param in parameters)
            {
                if (builder.Length > 0)
                    builder.Append('&');
                builder.Append(Uri.EscapeDataString(param.Key));
                builder.Append('=');
                builder.Append(Uri.EscapeDataString(param.Value));
            }
            return AddQueryValue(uri, builder.ToString());
        }

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

public static ParamSfoEntry Read(BinaryReader reader, ParamSfo paramSfo, int itemNumber)
        {
            const int indexOffset = 0x14;
            const int indexEntryLength = 0x10;
            reader.BaseStream.Seek(indexOffset + indexEntryLength * itemNumber, SeekOrigin.Begin);
            var result = new ParamSfoEntry();
            result.KeyOffset = reader.ReadUInt16();
            result.ValueFormat = (EntryFormat)reader.ReadUInt16();
            result.ValueLength = reader.ReadInt32();
            result.ValueMaxLength = reader.ReadInt32();
            result.ValueOffset = reader.ReadInt32();

            reader.BaseStream.Seek(paramSfo.KeysOffset + result.KeyOffset, SeekOrigin.Begin);
            byte tmp;
            var sb = new StringBuilder(32);
            while ((tmp = reader.ReadByte()) != 0)
                sb.Append((char)tmp);
            result.Key = sb.ToString();

            reader.BaseStream.Seek(paramSfo.ValuesOffset + result.ValueOffset, SeekOrigin.Begin);
            result.BinaryValue = reader.ReadBytes(result.ValueMaxLength);

            return result;
        }

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

public static string ToHexString(this byte[] bytes)
        {
            if (bytes == null)
                return null;

            if (bytes.Length == 0)
                return "";

            var result = new StringBuilder(bytes.Length*2);
            foreach (var b in bytes)
                result.Append(b.ToString("x2"));
            return result.ToString();
        }

19 Source : DefaultCacheKeyBuilder.cs
with MIT License
from 1100100

public string Generate(string sql, object param, string customKey, int? pageIndex = default, int? pageSize = default)
        {
            if (!string.IsNullOrWhiteSpace(customKey))
                return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{customKey}";

            if (string.IsNullOrWhiteSpace(sql))
                throw new ArgumentNullException(nameof(sql));

            var builder = new StringBuilder();
            builder.AppendFormat("{0}:", sql);

            if (param == null)
                return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd(':'))}";

            var prop = GetProperties(param);
            foreach (var item in prop)
            {
                builder.AppendFormat("{0}={1}&", item.Name, item.GetValue(param));
            }
            if (pageIndex.HasValue)
            {
                builder.AppendFormat("pageindex={0}&", pageIndex.Value);
            }
            if (pageSize.HasValue)
            {
                builder.AppendFormat("pagesize={0}&", pageSize.Value);
            }
            return $"{CacheConfiguration.KeyPrefix}{(string.IsNullOrWhiteSpace(CacheConfiguration.KeyPrefix) ? "" : ":")}{HashCacheKey(builder.ToString().TrimEnd('&'))}";
        }

19 Source : ICachingKeyGenerator.Default.cs
with MIT License
from 1100100

public string GenerateKeyPlaceholder(string keyPrefix, int globalExpire, string route, MethodInfo methodInfo, CachingAttribute cachingAttribute = default)
        {
            var sb = new StringBuilder();
            if (!string.IsNullOrWhiteSpace(keyPrefix))
                sb.AppendFormat("{0}{1}", keyPrefix, LinkString);
            if (cachingAttribute == null || string.IsNullOrWhiteSpace(cachingAttribute.Key))
            {
                sb.AppendFormat("{0}", route);
                if (methodInfo.GetParameters().Length > 0)
                    sb.Append(LinkString + "{0}");
            }
            else
                sb.Append(cachingAttribute.Key);

            return sb.ToString();
        }

19 Source : ZooKeeperServiceDiscovery.cs
with MIT License
from 1100100

private async Task CreatePath(string path, byte[] data)
        {
            path = path.Trim('/');
            if (string.IsNullOrWhiteSpace(path))
                return;
            var children = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var nodePath = new StringBuilder();
            for (var i = 0; i < children.Length; i++)
            {
                nodePath.Append("/" + children[i]);
                if (await ZooKeeper.existsAsync(nodePath.ToString()) == null)
                {
                    await ZooKeeper.createAsync(nodePath.ToString(), i == children.Length - 1 ? data : null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }
            }
        }

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

public static string AsHex(this byte[] bytes)
        {
            if (bytes == null)
                return null;

            if (bytes.Length == 0)
                return "";

            var result = new StringBuilder(bytes.Length*2);
            foreach (var b in bytes)
                result.Append(b.ToString("x2"));
            return result.ToString();
        }

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

private static string Delimitied(string value, char separator)
        {
            if (value == null)
                throw new ArgumentNullException(nameof(value));

            if (value.Length == 0)
                return value;

            var hasPrefix = true;
            var builder = new StringBuilder(value.Length + 3);
            foreach (var c in value)
            {
                var ch = c;
                if (char.IsUpper(ch))
                {
                    ch = char.ToLower(ch);
                    if (!hasPrefix)
                        builder.Append(separator);
                    hasPrefix = true;
                }
                else
                    hasPrefix = false;
                builder.Append(ch);
            }
            return builder.ToString();
        }

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

internal static string AsHexString(this byte[] bytes)
        {
            var result = new StringBuilder();
            foreach (var b in bytes)
                result.Append(b.ToString("x2"));
            return result.ToString();
        }

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

internal static async Task Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Drag .pkg files and/or folders onto this .exe to verify the packages.");
                    var isFirstChar = true;
                    var completedPath = false;
                    var path = new StringBuilder();
                    do
                    {
                        var keyInfo = Console.ReadKey(true);
                        if (isFirstChar)
                        {
                            isFirstChar = false;
                            if (keyInfo.KeyChar != '"')
                                return;
                        }
                        else
                        {
                            if (keyInfo.KeyChar == '"')
                            {
                                completedPath = true;
                                args = new[] {path.ToString()};
                            }
                            else
                                path.Append(keyInfo.KeyChar);
                        }
                    } while (!completedPath);
                    Console.Clear();
                }

                Console.OutputEncoding = new UTF8Encoding(false);
                Console.replacedle = replacedle;
                Console.CursorVisible = false;
                Console.WriteLine("Scanning for PKGs...");
                var pkgList = new List<FileInfo>();
                Console.ForegroundColor = ConsoleColor.Yellow;
                foreach (var item in args)
                {
                    var path = item.Trim('"');
                    if (File.Exists(path))
                        pkgList.Add(new FileInfo(path));
                    else if (Directory.Exists(path))
                        pkgList.AddRange(GetFilePaths(path, "*.pkg", SearchOption.AllDirectories).Select(p => new FileInfo(p)));
                    else
                        Console.WriteLine("Unknown path: " + path);
                }
                Console.ResetColor();
                if (pkgList.Count == 0)
                {
                    Console.WriteLine("No packages were found. Check paths, and try again.");
                    return;
                }

                var longestFilename = Math.Max(pkgList.Max(i => i.Name.Length), HeaderPkgName.Length);
                var sigWidth = Math.Max(HeaderSignature.Length, 8);
                var csumWidth = Math.Max(HeaderChecksum.Length, 5);
                var csumsWidth = 1 + sigWidth + 1 + csumWidth + 1;
                var idealWidth = longestFilename + csumsWidth;
                try
                {
                    if (idealWidth > Console.LargestWindowWidth)
                    {
                        longestFilename = Console.LargestWindowWidth - csumsWidth;
                        idealWidth = Console.LargestWindowWidth;
                    }
                    if (idealWidth > Console.WindowWidth)
                    {
                        Console.BufferWidth = Math.Max(Console.BufferWidth, idealWidth);
                        Console.WindowWidth = idealWidth;
                    }
                    Console.BufferHeight = Math.Max(Console.BufferHeight, Math.Min(9999, pkgList.Count + 10));
                }
                catch (PlatformNotSupportedException) { }
                Console.WriteLine($"{HeaderPkgName.Trim(longestFilename).PadRight(longestFilename)} {HeaderSignature.PadLeft(sigWidth)} {HeaderChecksum.PadLeft(csumWidth)}");
                using var cts = new CancellationTokenSource();
                Console.CancelKeyPress += (sender, eventArgs) => { cts.Cancel(); };
                var t = new Thread(() =>
                                   {
                                       try
                                       {
                                           var indicatorIdx = 0;
                                           while (!cts.Token.IsCancellationRequested)
                                           {
                                               Task.Delay(1000, cts.Token).ConfigureAwait(false).GetAwaiter().GetResult();
                                               if (cts.Token.IsCancellationRequested)
                                                   return;

                                               PkgChecker.Sync.Wait(cts.Token);
                                               try
                                               {
                                                   var frame = Animation[(indicatorIdx++) % Animation.Length];
                                                   var currentProgress = PkgChecker.CurrentFileProcessedBytes;
                                                   Console.replacedle = $"{replacedle} [{(double)(PkgChecker.ProcessedBytes + currentProgress) / PkgChecker.TotalFileSize * 100:0.00}%] {frame}";
                                                   if (PkgChecker.CurrentPadding > 0)
                                                   {
                                                       Console.CursorVisible = false;
                                                       var (top, left) = (Console.CursorTop, Console.CursorLeft);
                                                       Console.Write($"{(double)currentProgress / PkgChecker.CurrentFileSize * 100:0}%".PadLeft(PkgChecker.CurrentPadding));
                                                       Console.CursorTop = top;
                                                       Console.CursorLeft = left;
                                                       Console.CursorVisible = false;
                                                   }
                                               }
                                               finally
                                               {
                                                   PkgChecker.Sync.Release();
                                               }
                                           }
                                       }
                                       catch (TaskCanceledException)
                                       {
                                       }
                                   });
                t.Start();
                await PkgChecker.CheckAsync(pkgList, longestFilename, sigWidth, csumWidth, csumsWidth-2, cts.Token).ConfigureAwait(false);
                cts.Cancel(false);
                t.Join();
            }
            finally
            {
                Console.replacedle = replacedle;
                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
                Console.WriteLine();
                Console.CursorVisible = true;
            }
        }

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

private string ResolveWhere()
        {
            var builder = new StringBuilder();
            foreach (var expression in _whereExpressions)
            {
                var result = new BooleanExpressionResovle(expression, _parameters).Resovle();
                if (expression == _whereExpressions.First())
                {
                    builder.Append($" WHERE {result}");
                }
                else
                {
                    builder.Append($" AND {result}");
                }
            }
            return builder.ToString();
        }

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

private string ResolveHaving()
        {
            var buffer = new StringBuilder();
            foreach (var item in _havingExpressions)
            {
                var result = new BooleanExpressionResovle(item, _parameters).Resovle();
                if (item == _havingExpressions.First())
                {
                    buffer.Append($" HAVING {result}");
                }
                else
                {
                    buffer.Append($" AND {result}");
                }
            }
            return buffer.ToString();
        }

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

private string ResolveOrder()
        {
            var buffer = new StringBuilder();
            foreach (var item in _orderExpressions)
            {
                if (item == _orderExpressions.First())
                {
                    buffer.Append($" ORDER BY ");
                }
                var result = new OrderExpressionResovle(item.Expression, item.Asc).Resovle();
                buffer.Append(result);
                buffer.Append(",");
            }
            return buffer.ToString().Trim(',');
        }

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

public virtual string Resovle()
        {
            Visit(_expression);
            return _textBuilder.ToString();
        }

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

public string Resolve<T>(CommandNode command, T parameter) where T : clreplaced
        {
            var buffer = new StringBuilder();
            foreach (var item in command.Nodes)
            {
                if (item is TextNode)
                {
                    var txt = ResolveTextNode(item as TextNode);
                    if (txt.Length > 0)
                    {
                        buffer.AppendFormat($" {txt}");
                    }
                }
                else if (item is WhereNode)
                {
                    var wheresql = ResolveWhereNode(item as WhereNode, parameter);
                    if (wheresql.Length > 0)
                    {
                        buffer.AppendFormat($" {wheresql}");
                    }
                }
                else if (item is IfNode)
                {
                    var txt = ResolveIfNode(item as IfNode, parameter);
                    if (txt.Length > 0)
                    {
                        buffer.AppendFormat($" {txt}");
                    }
                }
            }
            return buffer.ToString().Trim(' ');
        }

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

private string ResovleBatchInsert(IEnumerable<T> enreplacedys)
        {
            var table = GetTableMetaInfo().TableName;
            var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
            var columns = GetColumnMetaInfos()
                .Where(a => !a.IsComplexType).ToList();
            var intcolumns = columns
                .Where(a => !filters.Contains(a.ColumnName) && !a.IsNotMapped && !a.IsIdenreplacedy)
                .ToList();
            var columnNames = string.Join(",", intcolumns.Select(s => s.ColumnName));
            if (_context.DbContextType == DbContextType.Mysql)
            {
                var buffer = new StringBuilder();
                buffer.Append($"INSERT INTO {table}({columnNames}) VALUES ");
                var serializer = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(typeof(T));
                var list = enreplacedys.ToList();
                for (var i = 0; i < list.Count; i++)
                {
                    var item = list[i];
                    var values = serializer(item);
                    buffer.Append("(");
                    for (var j = 0; j < intcolumns.Count; j++)
                    {
                        var column = intcolumns[j];
                        var value = values[column.CsharpName];
                        if (value == null)
                        {
                            buffer.Append(column.IsDefault ? "DEFAULT" : "NULL");
                        }
                        else if (column.CsharpType == typeof(bool) || column.CsharpType == typeof(bool?))
                        {
                            buffer.Append(Convert.ToBoolean(value) == true ? 1 : 0);
                        }
                        else if (column.CsharpType == typeof(DateTime) || column.CsharpType == typeof(DateTime?))
                        {
                            buffer.Append($"'{value}'");
                        }
                        else if (column.CsharpType.IsValueType || (Nullable.GetUnderlyingType(column.CsharpType)?.IsValueType == true))
                        {
                            buffer.Append(value);
                        }
                        else
                        {
                            var str = SqlEncoding(value.ToString());
                            buffer.Append($"'{str}'");
                        }
                        if (j + 1 < intcolumns.Count)
                        {
                            buffer.Append(",");
                        }
                    }
                    buffer.Append(")");
                    if (i + 1 < list.Count)
                    {
                        buffer.Append(",");
                    }
                }
                return buffer.Remove(buffer.Length - 1, 0).ToString();
            }
            throw new NotImplementedException();
        }

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

private string ResolveUpdate()
        {
            var table = GetTableMetaInfo().TableName;
            var builder = new StringBuilder();
            if (_setExpressions.Count > 0)
            {
                var where = ResolveWhere();
                foreach (var item in _setExpressions)
                {
                    var column = new BooleanExpressionResovle(item.Column).Resovle();
                    var expression = new BooleanExpressionResovle(item.Expression, _parameters).Resovle();
                    builder.Append($"{column} = {expression},");
                }
                var sql = $"UPDATE {table} SET {builder.ToString().Trim(',')}{where}";
                return sql;
            }
            else
            {
                var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
                var where = ResolveWhere();
                var columns = GetColumnMetaInfos();
                var updcolumns = columns
                    .Where(a => !filters.Contains(a.ColumnName))
                    .Where(a => !a.IsComplexType)
                    .Where(a => !a.IsIdenreplacedy && !a.IsPrimaryKey && !a.IsNotMapped)
                    .Where(a => !a.IsConcurrencyCheck)
                    .Select(s => $"{s.ColumnName} = @{s.CsharpName}");
                if (string.IsNullOrEmpty(where))
                {
                    var primaryKey = columns.Where(a => a.IsPrimaryKey).FirstOrDefault()
                        ?? columns.First();
                    where = $" WHERE {primaryKey.ColumnName} = @{primaryKey.CsharpName}";
                    if (columns.Exists(a => a.IsConcurrencyCheck))
                    {
                        var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                        where += $" AND {checkColumn.ColumnName} = @{checkColumn.CsharpName}";
                    }
                }
                var sql = $"UPDATE {table} SET {string.Join(",", updcolumns)}";
                if (columns.Exists(a => a.IsConcurrencyCheck))
                {
                    var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                    sql += $",{checkColumn.ColumnName} = @New{checkColumn.CsharpName}";
                    if (checkColumn.CsharpType.IsValueType)
                    {
                        var version = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                    else
                    {
                        var version = Guid.NewGuid().ToString("N");
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                }
                sql += where;
                return sql;
            }
        }

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

private string SqlEncoding(string sql)
        {
            var buffer = new StringBuilder();
            for (int i = 0; i < sql.Length; i++)
            {
                var ch = sql[i];
                if (ch == '\'' || ch == '-' || ch == '\\' || ch == '*' || ch == '@')
                {
                    buffer.Append('\\');
                }
                buffer.Append(ch);
            }
            return buffer.ToString();
        }

See More Examples