System.Text.StringBuilder.AppendFormat(string, object)

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

2044 Examples 7

19 View Source File : SozlukDataStore.cs
License : MIT License
Project Creator : 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 View Source File : DefaultCacheKeyBuilder.cs
License : MIT License
Project Creator : 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 View Source File : ICachingKeyGenerator.Default.cs
License : MIT License
Project Creator : 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 View Source File : MySqlDbAdapter.cs
License : MIT License
Project Creator : 17MKH

public override string GeneratePagingSql(string select, string table, string where, string sort, int skip, int take, string groupBy = null, string having = null)
    {
        var sqlBuilder = new StringBuilder();
        sqlBuilder.AppendFormat("SELECT {0} FROM {1}", select, table);
        if (where.NotNull())
            sqlBuilder.AppendFormat(" {0}", where);

        if (groupBy.NotNull())
            sqlBuilder.Append(groupBy);

        if (having.NotNull())
            sqlBuilder.Append(having);

        if (sort.NotNull())
            sqlBuilder.AppendFormat("{0}", sort);

        if (skip == 0)
            sqlBuilder.AppendFormat(" LIMIT {0}", take);
        else
            sqlBuilder.AppendFormat(" LIMIT {0},{1}", skip, take);

        return sqlBuilder.ToString();
    }

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

private string GenerateCreateTableSql(IEnreplacedyDescriptor descriptor)
    {
        var columns = descriptor.Columns;
        var sql = new StringBuilder();
        sql.AppendFormat("CREATE TABLE {0}(", AppendQuote(descriptor.TableName));

        for (int i = 0; i < columns.Count; i++)
        {
            var column = columns[i];

            sql.Append(GetColumnAddSql(column, descriptor));

            if (i < columns.Count - 1)
            {
                sql.Append(",");
            }
        }

        sql.Append(");");

        return sql.ToString();
    }

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

private string GetColumnAddSql(IColumnDescriptor column, IEnreplacedyDescriptor descriptor)
    {
        var sql = new StringBuilder();
        sql.AppendFormat("{0} ", AppendQuote(column.Name));

        switch (column.TypeName)
        {
            case "decimal":
                var precision = column.Precision < 1 ? 18 : column.Precision;
                var scale = column.Scale < 1 ? 4 : column.Scale;
                sql.AppendFormat("{0}({1},{2}) ", column.TypeName, precision, scale);
                break;
            default:
                sql.AppendFormat("{0} ", column.TypeName);
                break;
        }
        if (column.IsPrimaryKey)
        {
            sql.Append("PRIMARY KEY ");

            if (descriptor.PrimaryKey.IsInt || descriptor.PrimaryKey.IsLong)
            {
                sql.Append("AUTOINCREMENT ");
            }
        }
        if (!column.IsPrimaryKey && column.DefaultValue.NotNull())
        {
            sql.AppendFormat("DEFAULT {0}", column.DefaultValue);
        }

        if (!column.Nullable)
        {
            sql.Append(" NOT NULL ");
        }

        return sql.ToString();
    }

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

public static void AppendValue(QueryBody queryBody, object value, StringBuilder sqlBuilder, IQueryParameters parameters)
    {
        if (value == null)
        {
            var len = sqlBuilder.Length;
            if (sqlBuilder[len - 1] == ' ' && sqlBuilder[len - 2] == '>' && sqlBuilder[len - 3] == '<')
            {
                sqlBuilder.Remove(len - 3, 3);
                sqlBuilder.Append("IS NOT NULL");
                return;
            }

            if (sqlBuilder[len - 1] == ' ' && sqlBuilder[len - 2] == '=')
            {
                sqlBuilder.Remove(len - 2, 2);
                sqlBuilder.Append("IS NULL");
            }

            return;
        }

        var dbAdapter = queryBody.DbAdapter;
        if (queryBody.UseParameters)
        {
            //使用参数化
            var pName = parameters.Add(value);
            sqlBuilder.Append(dbAdapter.AppendParameter(pName));
        }
        else
        {
            var type = value.GetType();
            //不使用参数化
            if (type.IsNullable())
            {
                type = Nullable.GetUnderlyingType(type);
            }

            if (type!.IsEnum)
            {
                sqlBuilder.AppendFormat("{0}", value.ToInt());
            }
            else if (type.IsBool())
            {
                sqlBuilder.AppendFormat("{0}", value.ToBool() ? dbAdapter.BooleanTrueValue : dbAdapter.BooleanFalseValue);
            }
            else if (type.IsDateTime())
            {
                sqlBuilder.AppendFormat("'{0:yyyy-MM-dd HH:mm:ss}'", value);
            }
            else if (type.IsString() || type.IsGuid())
            {
                sqlBuilder.AppendFormat("'{0}'", value);
            }
            else
            {
                sqlBuilder.AppendFormat("{0}", value);
            }
        }
    }

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

private string GenerateCreateTableSql(IEnreplacedyDescriptor descriptor)
    {
        var columns = descriptor.Columns;
        var sql = new StringBuilder();
        sql.AppendFormat("CREATE TABLE {0}(", AppendQuote(descriptor.TableName));

        for (int i = 0; i < columns.Count; i++)
        {
            var column = columns[i];

            sql.Append(GenerateColumnAddSql(column, descriptor));

            if (i < columns.Count - 1)
            {
                sql.Append(",");
            }
        }

        sql.Append(") ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;");

        return sql.ToString();
    }

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

private string GenerateColumnAddSql(IColumnDescriptor column, IEnreplacedyDescriptor descriptor)
    {
        var sql = new StringBuilder();
        sql.AppendFormat("{0} ", AppendQuote(column.Name));

        switch (column.TypeName)
        {
            case "CHAR":
                //MySql中使用CHAR(36)来保存GUID格式
                sql.AppendFormat("CHAR({0}) ", column.Length);
                break;
            case "VARCHAR":
                sql.AppendFormat("VARCHAR({0}) ", column.Length);
                break;
            case "DECIMAL":
            case "DOUBLE":
            case "FLOAT":
                var precision = column.Precision < 1 ? 18 : column.Precision;
                var scale = column.Scale < 1 ? 4 : column.Scale;
                sql.AppendFormat("{0}({1},{2}) ", column.TypeName, precision, scale);
                break;
            default:
                sql.AppendFormat("{0} ", column.TypeName);
                break;
        }
        if (column.IsPrimaryKey)
        {
            sql.Append("PRIMARY KEY ");

            if (descriptor.PrimaryKey.IsInt || descriptor.PrimaryKey.IsLong)
            {
                sql.Append("AUTO_INCREMENT ");
            }
        }

        if (!column.Nullable)
        {
            sql.Append("NOT NULL ");
        }

        if (!column.IsPrimaryKey && column.DefaultValue.NotNull())
        {
            sql.AppendFormat("DEFAULT {0}", column.DefaultValue);
        }

        if (column.Description.NotNull())
        {
            sql.AppendFormat(" COMMENT '{0}' ", column.Description);
        }

        return sql.ToString();
    }

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

public override string GeneratePagingSql(string select, string table, string where, string sort, int skip, int take, string groupBy = null, string having = null)
    {
        var sqlBuilder = new StringBuilder();
        sqlBuilder.AppendFormat("SELECT {0} FROM {1}", select, table);
        if (where.NotNull())
            sqlBuilder.AppendFormat(" {0}", where);

        if (groupBy.NotNull())
            sqlBuilder.Append(groupBy);

        if (having.NotNull())
            sqlBuilder.Append(having);

        if (sort.NotNull())
            sqlBuilder.AppendFormat("{0}", sort);

        sqlBuilder.AppendFormat(" LIMIT {0} OFFSET {1};", take, skip);

        return sqlBuilder.ToString();
    }

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

private string GenerateCreateTableSql(IEnreplacedyDescriptor descriptor)
    {
        var columns = descriptor.Columns;
        var sql = new StringBuilder();
        sql.AppendFormat("CREATE TABLE {0}(", AppendQuote(descriptor.TableName));

        for (int i = 0; i < columns.Count; i++)
        {
            var column = columns[i];

            sql.Append(GenerateColumnAddSql(column, descriptor));

            if (i < columns.Count - 1)
            {
                sql.Append(",");
            }
        }

        sql.Append(");");

        foreach (var column in columns)
        {
            if (column.Description.NotNull())
            {
                sql.AppendFormat("EXECUTE sp_addextendedproperty N'MS_Description','{0}',N'user',N'dbo',N'table',N'{1}',N'column',N'{2}';", column.Description, descriptor.TableName, column.Name);
            }
        }

        return sql.ToString();
    }

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

public override string GeneratePagingSql(string select, string table, string where, string sort, int skip, int take, string groupBy = null, string having = null)
    {
        if (sort.IsNull())
        {
            if (groupBy.IsNull())
                sort = " ORDER BY [Id] ASC";
            else
            {
                throw new ArgumentException("SqlServer分组分页查询需要指定排序规则");
            }
        }

        var sqlBuilder = new StringBuilder();
        if (IsHighVersion)
        {
            #region ==2012+版本==

            sqlBuilder.AppendFormat("SELECT {0} FROM {1}", select, table);

            if (where.NotNull())
                sqlBuilder.AppendFormat(" {0}", where);

            if (groupBy.NotNull())
                sqlBuilder.Append(groupBy);

            if (having.NotNull())
                sqlBuilder.Append(having);

            sqlBuilder.AppendFormat("{0} OFFSET {1} ROW FETCH NEXT {2} ROW ONLY", sort, skip, take);

            #endregion
        }
        else
        {
            #region ==2012以下版本==

            sqlBuilder.AppendFormat("SELECT * FROM (SELECT ROW_NUMBER() OVER({0}) AS RowNum,{1} FROM {2}", sort, select, table);
            if (!string.IsNullOrWhiteSpace(where))
                sqlBuilder.AppendFormat(" WHERE {0}", where);

            sqlBuilder.AppendFormat(") AS T WHERE T.RowNum BETWEEN {0} AND {1}", skip + 1, skip + take);

            #endregion
        }

        return sqlBuilder.ToString();
    }

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

private static void ResolveInForGeneric(StringBuilder sqlBuilder, string columnName, Expression exp, Type valueType, bool notContainer = false)
    {
        var value = ResolveDynamicInvoke(exp);
        var isValueType = false;
        var list = new List<string>();
        if (valueType.IsEnum)
        {
            isValueType = true;
            var valueList = (IEnumerable)value;
            if (valueList != null)
            {
                foreach (var c in valueList)
                {
                    list.Add(Enum.Parse(valueType, c.ToString()!).ToInt().ToString());
                }
            }
        }
        else
        {
            var typeName = valueType.Name;
            switch (typeName)
            {
                case "Guid":
                    if (value is IEnumerable<Guid> guidValues)
                    {
                        foreach (var c in guidValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "DateTime":
                    if (value is IEnumerable<DateTime> dateTimeValues)
                    {
                        foreach (var c in dateTimeValues)
                        {
                            list.Add(c.ToString("yyyy-MM-dd HH:mm:ss"));
                        }
                    }
                    break;
                case "Byte":
                    isValueType = true;
                    if (value is IEnumerable<byte> byteValues)
                    {
                        foreach (var c in byteValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
                case "Char":
                    if (value is IEnumerable<char> charValues)
                    {
                        foreach (var c in charValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Int16":
                    isValueType = true;
                    if (value is IEnumerable<short> shortValues)
                    {
                        foreach (var c in shortValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Int32":
                    isValueType = true;
                    if (value is IEnumerable<int> intValues)
                    {
                        foreach (var c in intValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Int64":
                    isValueType = true;
                    if (value is IEnumerable<long> longValues)
                    {
                        foreach (var c in longValues)
                        {
                            list.Add(c.ToString());
                        }
                    }
                    break;
                case "Double":
                    isValueType = true;
                    if (value is IEnumerable<double> doubleValues)
                    {
                        foreach (var c in doubleValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
                case "Single":
                    isValueType = true;
                    if (value is IEnumerable<float> floatValues)
                    {
                        foreach (var c in floatValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
                case "Decimal":
                    isValueType = true;
                    if (value is IEnumerable<decimal> decimalValues)
                    {
                        foreach (var c in decimalValues)
                        {
                            list.Add(c.ToString(CultureInfo.InvariantCulture));
                        }
                    }
                    break;
            }
        }

        if (list!.Count < 1)
            return;

        sqlBuilder.Append(columnName);
        sqlBuilder.Append(notContainer ? " NOT IN (" : " IN (");

        //值类型不带引号
        if (isValueType)
        {
            for (var i = 0; i < list.Count; i++)
            {
                sqlBuilder.AppendFormat("{0}", list[i]);
                if (i != list.Count - 1)
                {
                    sqlBuilder.Append(",");
                }
            }
        }
        else
        {
            for (var i = 0; i < list.Count; i++)
            {
                sqlBuilder.AppendFormat("'{0}'", list[i].Replace("'", "''"));
                if (i != list.Count - 1)
                {
                    sqlBuilder.Append(",");
                }
            }
        }

        sqlBuilder.Append(")");
    }

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

private string GenerateColumnAddSql(IColumnDescriptor column, IEnreplacedyDescriptor descriptor)
    {
        var sql = new StringBuilder();
        sql.AppendFormat("{0} ", AppendQuote(column.Name));

        switch (column.TypeName)
        {
            case "NVARCHAR":
                sql.AppendFormat("NVARCHAR({0}) ", column.Length < 1 ? "MAX" : column.Length.ToString());
                break;
            case "DECIMAL":
            case "DOUBLE":
            case "FLOAT":
                var precision = column.Precision < 1 ? 18 : column.Precision;
                var scale = column.Scale < 1 ? 4 : column.Scale;
                sql.AppendFormat("{0}({1},{2}) ", column.TypeName, precision, scale);
                break;
            default:
                sql.AppendFormat("{0} ", column.TypeName);
                break;
        }
        if (column.IsPrimaryKey)
        {
            sql.Append("PRIMARY KEY ");

            //整数主键要自增
            if (descriptor.PrimaryKey.IsInt || descriptor.PrimaryKey.IsLong)
            {
                sql.Append("IDENreplacedY(1,1) ");
            }
        }

        if (!column.Nullable)
        {
            sql.Append("NOT NULL ");
        }

        if (!column.IsPrimaryKey && column.DefaultValue.NotNull())
        {
            sql.AppendFormat("DEFAULT({0})", column.DefaultValue);
        }

        return sql.ToString();
    }

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

private static ITemplateOutput Parser(string tplcode, string[] usings, IDictionary options) {
			int view = Interlocked.Increment(ref _view);
			StringBuilder sb = new StringBuilder();
			IDictionary options_copy = new Hashtable();
			foreach (DictionaryEntry options_de in options) options_copy[options_de.Key] = options_de.Value;
			sb.AppendFormat(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;{1}

//namespace TplDynamicCodeGenerate {{
	public clreplaced TplDynamicCodeGenerate_view{0} : FreeSql.Template.TemplateEngin.ITemplateOutput {{
		public FreeSql.Template.TemplateEngin.TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, FreeSql.Template.TemplateEngin tEmPlAtEsEnDeR) {{
			FreeSql.Template.TemplateEngin.TemplateReturnInfo rTn = tOuTpUt == null ? 
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = (tOuTpUt = new StringBuilder()), Blocks = new Dictionary<string, int[]>() }} :
				new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = tOuTpUt, Blocks = new Dictionary<string, int[]>() }};
			Dictionary<string, int[]> TPL__blocks = rTn.Blocks;
			Stack<int[]> TPL__blocks_stack = new Stack<int[]>();
			int[] TPL__blocks_stack_peek;
			List<IDictionary> TPL__forc = new List<IDictionary>();
			Func<IDictionary> pRoCeSsOpTiOnS = new Func<IDictionary>(delegate () {{
				IDictionary nEwoPtIoNs = new Hashtable();
				foreach (DictionaryEntry oPtIoNs_dE in oPtIoNs)
					nEwoPtIoNs[oPtIoNs_dE.Key] = oPtIoNs_dE.Value;
				foreach (IDictionary TPL__forc_dIc in TPL__forc)
					foreach (DictionaryEntry TPL__forc_dIc_dE in TPL__forc_dIc)
						nEwoPtIoNs[TPL__forc_dIc_dE.Key] = TPL__forc_dIc_dE.Value;
				return nEwoPtIoNs;
			}});
			FreeSql.Template.TemplateEngin.TemplateIf tPlIf = delegate(object exp) {{
				if (exp is bool) return (bool)exp;
				if (exp == null) return false;
				if (exp is int && (int)exp == 0) return false;
				if (exp is string && (string)exp == string.Empty) return false;
				if (exp is long && (long)exp == 0) return false;
				if (exp is short && (short)exp == 0) return false;
				if (exp is byte && (byte)exp == 0) return false;
				if (exp is double && (double)exp == 0) return false;
				if (exp is float && (float)exp == 0) return false;
				if (exp is decimal && (decimal)exp == 0) return false;
				return true;
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint print = delegate(object[] pArMs) {{
				if (pArMs == null || pArMs.Length == 0) return;
				foreach (object pArMs_A in pArMs) if (pArMs_A != null) tOuTpUt.Append(pArMs_A);
			}};
			FreeSql.Template.TemplateEngin.TemplatePrint Print = print;", view, usings?.Any() == true ? $"\r\nusing {string.Join(";\r\nusing ", usings)};" : "");

			#region {miss}...{/miss}块内容将不被解析
			string[] tmp_content_arr = _reg_miss.Split(tplcode);
			if (tmp_content_arr.Length > 1) {
				sb.AppendFormat(@"
			string[] TPL__MISS = new string[{0}];", Math.Ceiling(1.0 * (tmp_content_arr.Length - 1) / 2));
				int miss_len = -1;
				for (int a = 1; a < tmp_content_arr.Length; a += 2) {
					sb.Append(string.Concat(@"
			TPL__MISS[", ++miss_len, @"] = """, Utils.GetConstString(tmp_content_arr[a]), @""";"));
					tmp_content_arr[a] = string.Concat("{#TPL__MISS[", miss_len, "]}");
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			#region 扩展语法如 <div @if="表达式"></div>
			tplcode = htmlSyntax(tplcode, 3); //<div @if="c#表达式" @for="index 1,100"></div>
											  //处理 {% %} 块 c#代码
			tmp_content_arr = _reg_code.Split(tplcode);
			if (tmp_content_arr.Length == 1) {
				tplcode = Utils.GetConstString(tplcode)
					.Replace("{%", "{$TEMPLATE__CODE}")
					.Replace("%}", "{/$TEMPLATE__CODE}");
			} else {
				tmp_content_arr[0] = Utils.GetConstString(tmp_content_arr[0]);
				for (int a = 1; a < tmp_content_arr.Length; a += 4) {
					tmp_content_arr[a] = "{$TEMPLATE__CODE}";
					tmp_content_arr[a + 2] = "{/$TEMPLATE__CODE}";
					tmp_content_arr[a + 3] = Utils.GetConstString(tmp_content_arr[a + 3]);
				}
				tplcode = string.Join("", tmp_content_arr);
			}
			#endregion
			sb.Append(@"
			tOuTpUt.Append(""");

			string error = null;
			int tpl_tmpid = 0;
			int forc_i = 0;
			string extends = null;
			Stack<string> codeTree = new Stack<string>();
			Stack<string> forEndRepl = new Stack<string>();
			sb.Append(_reg.Replace(tplcode, delegate (Match m) {
				string _0 = m.Groups[0].Value;
				if (!string.IsNullOrEmpty(error)) return _0;

				string _1 = m.Groups[1].Value.Trim(' ', '\t');
				string _2 = m.Groups[2].Value
					.Replace("\\\\", "\\")
					.Replace("\\\"", "\"");
				_2 = Utils.ReplaceSingleQuote(_2);

				switch (_1) {
					#region $TEMPLATE__CODE--------------------------------------------------
					case "$TEMPLATE__CODE":
						codeTree.Push(_1);
						return @""");
";
					case "/$TEMPLATE__CODE":
						string pop = codeTree.Pop();
						if (pop != "$TEMPLATE__CODE") {
							codeTree.Push(pop);
							error = "编译出错,{% 与 %} 并没有配对";
							return _0;
						}
						return @"
			tOuTpUt.Append(""";
					#endregion
					case "include":
						return string.Format(@""");
tEmPlAtEsEnDeR.RenderFile2(tOuTpUt, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
			tOuTpUt.Append(""", _2);
					case "import":
						return _0;
					case "module":
						return _0;
					case "/module":
						return _0;
					case "extends":
						//{extends ../inc/layout.html}
						if (string.IsNullOrEmpty(extends) == false) return _0;
						extends = _2;
						return string.Empty;
					case "block":
						codeTree.Push("block");
						return string.Format(@""");
TPL__blocks_stack_peek = new int[] {{ tOuTpUt.Length, 0 }};
TPL__blocks_stack.Push(TPL__blocks_stack_peek);
TPL__blocks.Add(""{0}"", TPL__blocks_stack_peek);
tOuTpUt.Append(""", _2.Trim(' ', '\t'));
					case "/block":
						codeTreeEnd(codeTree, "block");
						return @""");
TPL__blocks_stack_peek = TPL__blocks_stack.Pop();
TPL__blocks_stack_peek[1] = tOuTpUt.Length - TPL__blocks_stack_peek[0];
tOuTpUt.Append(""";

					#region ##---------------------------------------------------------
					case "#":
						if (_2[0] == '#')
							return string.Format(@""");
			try {{ Print({0}); }} catch {{ }}
			tOuTpUt.Append(""", _2.Substring(1));
						return string.Format(@""");
			Print({0});
			tOuTpUt.Append(""", _2);
					#endregion
					#region for--------------------------------------------------------
					case "for":
						forc_i++;
						int cur_tpl_tmpid = tpl_tmpid;
						string sb_endRepl = string.Empty;
						StringBuilder sbfor = new StringBuilder();
						sbfor.Append(@""");");
						Match mfor = _reg_forin.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{1} != null)
	foreach (var TPL__tmp{0} in TPL__tmp{1}) {{", ++tpl_tmpid, cur_tpl_tmpid + 2);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor2, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = TPL__tmp{2};
		{0} = TPL__tmp{2};
		tOuTpUt.Append(""", mfor1, cur_tpl_tmpid + 1, tpl_tmpid);
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_foron.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
							string mfor3 = mfor.Groups[3].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {3};
	var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[4].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							if (!string.IsNullOrEmpty(mfor2)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};", mfor2, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
								if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
							}
							if (!string.IsNullOrEmpty(mfor3)) {
								sbfor.AppendFormat(@"
	var TPL__tmp{1} = {0};
	{0} = 0;", mfor3, ++tpl_tmpid);
								sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor3, tpl_tmpid));
								if (options_copy.Contains(mfor3) == false) options_copy[mfor3] = null;
							}
							sbfor.AppendFormat(@"
	if (TPL__tmp{2} != null)
	foreach (DictionaryEntry TPL__tmp{1} in TPL__tmp{2}) {{
		{0} = TPL__tmp{1}.Key;
		TPL__tmp{3}[""{0}""] = {0};", mfor1, ++tpl_tmpid, cur_tpl_tmpid + 2, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor2))
								sbfor.AppendFormat(@"
		{0} = TPL__tmp{1}.Value;
		TPL__tmp{2}[""{0}""] = {0};", mfor2, tpl_tmpid, cur_tpl_tmpid + 1);
							if (!string.IsNullOrEmpty(mfor3))
								sbfor.AppendFormat(@"
		TPL__tmp{1}[""{0}""] = ++ {0};", mfor3, cur_tpl_tmpid + 1);
							sbfor.AppendFormat(@"
		tOuTpUt.Append(""");
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						mfor = _reg_forab.Match(_2);
						if (mfor.Success) {
							string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
							sbfor.AppendFormat(@"
//new Action(delegate () {{
	IDictionary TPL__tmp{0} = new Hashtable();
	TPL__forc.Add(TPL__tmp{0});
	var TPL__tmp{1} = {5};
	{5} = {3} - 1;
	if ({5} == null) {5} = 0;
	var TPL__tmp{2} = {4} + 1;
	while (++{5} < TPL__tmp{2}) {{
		TPL__tmp{0}[""{5}""] = {5};
		tOuTpUt.Append(""", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[2].Value, mfor.Groups[3].Value, mfor1);
							sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
	{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 1));
							if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
							codeTree.Push("for");
							forEndRepl.Push(sb_endRepl);
							return sbfor.ToString();
						}
						return _0;
					case "/for":
						if (--forc_i < 0) return _0;
						codeTreeEnd(codeTree, "for");
						return string.Format(@""");
	}}{0}
	TPL__forc.RemoveAt(TPL__forc.Count - 1);
//}})();
			tOuTpUt.Append(""", forEndRepl.Pop());
					#endregion
					#region if---------------------------------------------------------
					case "if":
						codeTree.Push("if");
						return string.Format(@""");
			if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "elseif":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return string.Format(@""");
			}} else if ({1}tPlIf({0})) {{
				tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
					case "else":
						codeTreeEnd(codeTree, "if");
						codeTree.Push("if");
						return @""");
			} else {
			tOuTpUt.Append(""";
					case "/if":
						codeTreeEnd(codeTree, "if");
						return @""");
			}
			tOuTpUt.Append(""";
						#endregion
				}
				return _0;
			}));

			sb.Append(@""");");
			if (string.IsNullOrEmpty(extends) == false) {
				sb.AppendFormat(@"
FreeSql.Template.TemplateEngin.TemplateReturnInfo eXtEnDs_ReT = tEmPlAtEsEnDeR.RenderFile2(null, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
string rTn_Sb_string = rTn.Sb.ToString();
foreach(string eXtEnDs_ReT_blocks_key in eXtEnDs_ReT.Blocks.Keys) {{
	if (rTn.Blocks.ContainsKey(eXtEnDs_ReT_blocks_key)) {{
		int[] eXtEnDs_ReT_blocks_value = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Remove(eXtEnDs_ReT_blocks_value[0], eXtEnDs_ReT_blocks_value[1]);
		int[] rTn_blocks_value = rTn.Blocks[eXtEnDs_ReT_blocks_key];
		eXtEnDs_ReT.Sb.Insert(eXtEnDs_ReT_blocks_value[0], rTn_Sb_string.Substring(rTn_blocks_value[0], rTn_blocks_value[1]));
		foreach(string eXtEnDs_ReT_blocks_keyb in eXtEnDs_ReT.Blocks.Keys) {{
			if (eXtEnDs_ReT_blocks_keyb == eXtEnDs_ReT_blocks_key) continue;
			int[] eXtEnDs_ReT_blocks_valueb = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_keyb];
			if (eXtEnDs_ReT_blocks_valueb[0] >= eXtEnDs_ReT_blocks_value[0])
				eXtEnDs_ReT_blocks_valueb[0] = eXtEnDs_ReT_blocks_valueb[0] - eXtEnDs_ReT_blocks_value[1] + rTn_blocks_value[1];
		}}
		eXtEnDs_ReT_blocks_value[1] = rTn_blocks_value[1];
	}}
}}
return eXtEnDs_ReT;
", extends);
			} else {
				sb.Append(@"
return rTn;");
			}
			sb.Append(@"
		}
	}
//}
");
			var str = "FreeSql.Template.TemplateEngin.TemplatePrint Print = print;";
			int dim_idx = sb.ToString().IndexOf(str) + str.Length;
			foreach (string dic_name in options_copy.Keys) {
				sb.Insert(dim_idx, string.Format(@"
			dynamic {0} = oPtIoNs[""{0}""];", dic_name));
			}
			//Console.WriteLine(sb.ToString());
			return Complie(sb.ToString(), @"TplDynamicCodeGenerate_view" + view);
		}

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

static void Main(string[] args)
        {
            try
            {
                logo();
                // https://github.com/GhostPack/Rubeus/blob/master/Rubeus/Domain/ArgumentParser.cs#L10

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

                WindowsIdenreplacedy idenreplacedy = WindowsIdenreplacedy.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(idenreplacedy);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with HIGH integrity.");
                }
                else
                {
                    Console.WriteLine($"[+] Process running with {principal.Idenreplacedy.Name} privileges with MEDIUM / LOW integrity.");
                }

                if (arguments.Count == 0)
                {
                    PrintError("[-] No arguments specified. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.ContainsKey("/help"))
                {
                    help();
                }
                else if (arguments.Count < 3)
                {
                    PrintError("[-] Some arguments are missing. Please refer the help section for more details.");
                    help();
                }
                else if (arguments.Count >= 3)
                {
                    string key = "SuperStrongKey";
                    string shellcode = null;
                    byte[] rawshellcode = new byte[] { };
                    if (arguments.ContainsKey("/path") && System.IO.File.Exists(arguments["/path"]))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = System.IO.File.ReadAllBytes(arguments["/path"]);
                        }
                        else
                        {
                            shellcode = System.IO.File.ReadAllText(arguments["/path"]);
                        }

                    }
                    else if (arguments.ContainsKey("/url"))
                    {
                        if (arguments["/f"] == "raw")
                        {
                            rawshellcode = GetRawShellcode(arguments["/url"]);
                        }
                        else
                        {
                            shellcode = GetShellcode(arguments["/url"]);
                        }
                    }

                    if (shellcode != null || rawshellcode.Length > 0)
                    {

                        byte[] buf = new byte[] { };

                        if (arguments.ContainsKey("/key"))
                        {
                            key = (arguments["/key"]);
                        }
                        PrintInfo($"[!] Shellcode will be encrypted using '{key}' key");
                        if (arguments["/enc"] == "xor")
                        {
                            byte[] xorshellcode = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(xorshellcode));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(xorshellcode));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                xorshellcode = XOR(buf, Encoding.ASCII.GetBytes(key));
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < xorshellcode.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", xorshellcode[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                xorshellcode = XOR(rawshellcode, Encoding.ASCII.GetBytes(key));
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], xorshellcode);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", xorshellcode);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else if (arguments["/enc"] == "aes")
                        {
                            byte[] preplacedwordBytes = Encoding.UTF8.GetBytes(key);
                            preplacedwordBytes = SHA256.Create().ComputeHash(preplacedwordBytes);
                            byte[] bytesEncrypted = new byte[] { };
                            if (arguments["/f"] == "base64")
                            {
                                buf = Convert.FromBase64String(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(Convert.ToBase64String(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", Convert.ToBase64String(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "hex")
                            {
                                buf = StringToByteArray(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(ByteArrayToString(bytesEncrypted));
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", ByteArrayToString(bytesEncrypted));
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "c")
                            {
                                buf = convertfromc(shellcode);
                                bytesEncrypted = AES_Encrypt(buf, preplacedwordBytes);
                                StringBuilder newshellcode = new StringBuilder();
                                for (int i = 0; i < bytesEncrypted.Length; i++)
                                {
                                    newshellcode.Append("\\x");
                                    newshellcode.AppendFormat("{0:x2}", bytesEncrypted[i]);
                                }
                                PrintSuccess("[+] Shellcode encrypted successfully.");
                                //Console.WriteLine(newshellcode);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllText(arguments["/o"], newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllText("output.bin", newshellcode.ToString());
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else if (arguments["/f"] == "raw")
                            {
                                bytesEncrypted = AES_Encrypt(rawshellcode, preplacedwordBytes);
                                if (arguments.ContainsKey("/o"))
                                {
                                    System.IO.File.WriteAllBytes(arguments["/o"], bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in '{arguments["/o"]}' file.");
                                }
                                else
                                {
                                    System.IO.File.WriteAllBytes("output.bin", bytesEncrypted);
                                    PrintSuccess($"[+] Output saved in 'output.bin' file.");
                                }
                            }
                            else
                            {
                                PrintError("[-] Please specify correct shellcode format.");
                            }
                        }
                        else
                        {
                            PrintError("[-] Please specify correct encryption type.");
                        }
                    }
                    else
                    {
                        PrintError("[-] Please check the specified file path or the URL.");
                    }
                }
                else
                {
                    PrintError("[-] File doesn't exists. Please check the specified file path.");
                }
            }
            catch (Exception ex)
            {
                PrintError(ex.Message);
            }
        }

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

public static string ByteArrayToString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }

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

private static string GetHexString(byte[] arr)
        {
            var sb = new StringBuilder(arr.Length * 2);
            foreach (var b in arr)
            {
                sb.AppendFormat("{0:X2}", b);
            }

            return sb.ToString();
        }

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

public static string ToHex(byte[] bs, string newLine = "", string format = "{0} ")
        {
            var num = 0;
            var stringBuilder = new StringBuilder();
            foreach (var b in bs)
            {
                if (num++ % 16 == 0)
                {
                    stringBuilder.Append(newLine);
                }

                stringBuilder.AppendFormat(format, b.ToString("X2"));
            }

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

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

public string GetConfigText() {
            var sb = new StringBuilder();
            sb.AppendFormat("target={0}, ", targetGroup);
            sb.AppendFormat("defines={0}", defines);
            return sb.ToString();
        }

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

public string GetConfigText() {
            var sb = new StringBuilder();
            sb.AppendFormat("packageName={0}, ", packageName);
            sb.AppendFormat("versionName={0}, ", versionName);
            sb.AppendFormat("versionCode={0}, ", versionCode);
            return sb.ToString();
        }

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

public string GetConfigText() {
            var sb = new StringBuilder();
            sb.AppendFormat("keystoreName={0}, ", keystoreName);
            sb.AppendFormat("keystorePreplaced={0}, ", keystorePreplaced);
            sb.AppendFormat("keyaliasName={0}, ", keyaliasName);
            sb.AppendFormat("keyaliasPreplaced={0}, ", keyaliasPreplaced);
            return sb.ToString();
        }

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

public string GetConfigText() {
            var sb = new StringBuilder();
            sb.AppendFormat("enabled={0}, ", enabled);
            sb.AppendFormat("devices={0}, ", string.Join(",", devices));
            sb.AppendFormat("stereoRenderingPath={0}", stereoRenderingPath);
            return sb.ToString();
        }

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

internal string GetConfigText() {
            var sb = new StringBuilder();
            sb.AppendFormat("buildTarget={0}, ", Target);
            sb.AppendFormat("buildTargetGroup={0}, ", TargetGroup);
            sb.AppendFormat("options={0}, ", Options);
            sb.AppendFormat("scenes={0}", string.Join(",", scenes));
            return sb.ToString();
        }

19 View Source File : ZUART.cs
License : MIT License
Project Creator : a2633063

public void AddData(byte[] data)
        {
            if (rbtnHex.Checked)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sb.AppendFormat("{0:x2}" + " ", data[i]);
                }
                AddContent(sb.ToString().ToUpper());
            }
            else if (rbtnUTF8.Checked)
            {
                AddContent(new UTF8Encoding().GetString(data));
            }
            else if (rbtnUnicode.Checked)
            {
                AddContent(new UnicodeEncoding().GetString(data));
            }
            else// if (rbtnASCII.Checked)
            {
                //AddContent(new ASCIIEncoding().GetString(data));
                AddContent(Encoding.GetEncoding("GBK").GetString(data));
            }

            lblRevCount.Invoke(new MethodInvoker(delegate
            {
                lblRevCount.Text = "接收:" + (int.Parse(lblRevCount.Text.Substring(3)) + data.Length).ToString();
            }));
        }

19 View Source File : LogToText.cs
License : Apache License 2.0
Project Creator : A7ocin

private void Application_logMessageReceivedThreaded(string condition, string stackTrace, LogType type)
		{
			lock (buffer)
			{
				switch (type)
				{
					case LogType.Log:
						buffer.AppendFormat("{0}\n", condition);
						break;
					case LogType.Warning:
						buffer.AppendFormat("<color=yellow>{0}</color>\n", condition);
						break;
					default:
						buffer.AppendFormat("<color=red>{0}</color>\n", condition);
						break;
				}
			}
			changed = true;
		}

19 View Source File : LogToText.cs
License : Apache License 2.0
Project Creator : A7ocin

void Update()
		{
			if (changed)
			{
				changed = false;
				lock (buffer)
				{
					var text = buffer.ToString();
					var lines = text.Split('\n');
					if (lines.Length > 65)
					{
						buffer.Length = 0;
						for (int i = lines.Length - 65; i < lines.Length; i++)
							buffer.AppendFormat("{0}", lines[i]);
						text = buffer.ToString();
					}
					GetComponent<Text>().text = text;
				}
			}
		}

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

static string ByteArrayToString(byte[] ba)
        {
			var hex = new StringBuilder(ba.Length * 2);
			foreach (byte b in ba)
				hex.AppendFormat("{0:x2}", b);
			return hex.ToString();
		}

19 View Source File : MixedRealityToolkitVisualProfiler.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private void BuildFrameRateStrings()
        {
            cpuFrameRateStrings = new string[maxTargetFrameRate + 1];
            gpuFrameRateStrings = new string[maxTargetFrameRate + 1];
            string displayedDecimalFormat = string.Format("{{0:F{0}}}", displayedDecimalDigits);

            StringBuilder stringBuilder = new StringBuilder(32);
            StringBuilder milisecondStringBuilder = new StringBuilder(16);

            for (int i = 0; i < cpuFrameRateStrings.Length; ++i)
            {
                float miliseconds = (i == 0) ? 0.0f : (1.0f / i) * 1000.0f;
                milisecondStringBuilder.AppendFormat(displayedDecimalFormat, miliseconds);
                stringBuilder.AppendFormat("CPU: {0} fps ({1} ms)", i.ToString(), milisecondStringBuilder.ToString());
                cpuFrameRateStrings[i] = stringBuilder.ToString();
                stringBuilder.Length = 0;
                stringBuilder.AppendFormat("GPU: {0} fps ({1} ms)", i.ToString(), milisecondStringBuilder.ToString());
                gpuFrameRateStrings[i] = stringBuilder.ToString();
                milisecondStringBuilder.Length = 0;
                stringBuilder.Length = 0;
            }
        }

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

void Update()
	{
		OVRInput.Controller activeController = OVRInput.GetActiveController();

		data.Length = 0;
		byte battery = OVRInput.GetControllerBatteryPercentRemaining();
		data.AppendFormat("Battery: {0}\n", battery);

		float framerate = OVRPlugin.GetAppFramerate();
		data.AppendFormat("Framerate: {0:F2}\n", framerate);

		string activeControllerName = activeController.ToString();
		data.AppendFormat("Active: {0}\n", activeControllerName);

		string connectedControllerNames = OVRInput.GetConnectedControllers().ToString();
		data.AppendFormat("Connected: {0}\n", connectedControllerNames);

		data.AppendFormat("PrevConnected: {0}\n", prevConnected);

		controllers.Update();
		controllers.AppendToStringBuilder(ref data);

		prevConnected = connectedControllerNames;

		Quaternion rot = OVRInput.GetLocalControllerRotation(activeController);
		data.AppendFormat("Orientation: ({0:F2}, {1:F2}, {2:F2}, {3:F2})\n", rot.x, rot.y, rot.z, rot.w);

		Vector3 angVel = OVRInput.GetLocalControllerAngularVelocity(activeController);
		data.AppendFormat("AngVel: ({0:F2}, {1:F2}, {2:F2})\n", angVel.x, angVel.y, angVel.z);

		Vector3 angAcc = OVRInput.GetLocalControllerAngularAcceleration(activeController);
		data.AppendFormat("AngAcc: ({0:F2}, {1:F2}, {2:F2})\n", angAcc.x, angAcc.y, angAcc.z);

		Vector3 pos = OVRInput.GetLocalControllerPosition(activeController);
		data.AppendFormat("Position: ({0:F2}, {1:F2}, {2:F2})\n", pos.x, pos.y, pos.z);

		Vector3 vel = OVRInput.GetLocalControllerVelocity(activeController);
		data.AppendFormat("Vel: ({0:F2}, {1:F2}, {2:F2})\n", vel.x, vel.y, vel.z);

		Vector3 acc = OVRInput.GetLocalControllerAcceleration(activeController);
		data.AppendFormat("Acc: ({0:F2}, {1:F2}, {2:F2})\n", acc.x, acc.y, acc.z);

		float indexTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryIndexTrigger);
		data.AppendFormat("PrimaryIndexTriggerAxis1D: ({0:F2})\n", indexTrigger);

		float handTrigger = OVRInput.Get(OVRInput.Axis1D.PrimaryHandTrigger);
		data.AppendFormat("PrimaryHandTriggerAxis1D: ({0:F2})\n", handTrigger);

		for (int i = 0; i < monitors.Count; i++)
		{
			monitors[i].Update();
			monitors[i].AppendToStringBuilder(ref data);
		}

		if (uiText != null)
		{
			uiText.text = data.ToString();
		}
	}

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

void Update()
	{
		data.Length = 0;

		OVRInput.Controller activeController = OVRInput.GetActiveController();

		string activeControllerName = activeController.ToString();
		data.AppendFormat("Active: {0}\n", activeControllerName);

		string connectedControllerNames = OVRInput.GetConnectedControllers().ToString();
		data.AppendFormat("Connected: {0}\n", connectedControllerNames);

		data.AppendFormat("PrevConnected: {0}\n", prevConnected);

		controllers.Update();
		controllers.AppendToStringBuilder(ref data);
		prevConnected = connectedControllerNames;

		Vector3 pos = OVRInput.GetLocalControllerPosition(activeController);
		data.AppendFormat("Position: ({0:F2}, {1:F2}, {2:F2})\n", pos.x, pos.y, pos.z);

		Quaternion rot = OVRInput.GetLocalControllerRotation(activeController);
		data.AppendFormat("Orientation: ({0:F2}, {1:F2}, {2:F2}, {3:F2})\n", rot.x, rot.y, rot.z, rot.w);

		data.AppendFormat("HandTrackingEnabled: {0}\n", OVRPlugin.GetHandTrackingEnabled());

		bool result_hs_LH = OVRPlugin.GetHandState(OVRPlugin.Step.Render, OVRPlugin.Hand.HandLeft, ref hs_LH);
		data.AppendFormat("LH HS Query Res: {0}\n", result_hs_LH);
		data.AppendFormat("LH HS Status: {0}\n", hs_LH.Status);
		data.AppendFormat("LH HS Pose: {0}\n", hs_LH.RootPose);
		data.AppendFormat("LH HS HandConf: {0}\n", hs_LH.HandConfidence);

		bool result_hs_RH = OVRPlugin.GetHandState(OVRPlugin.Step.Render, OVRPlugin.Hand.HandRight, ref hs_RH);
		data.AppendFormat("RH HS Query Res: {0}\n", result_hs_RH);
		data.AppendFormat("RH HS Status: {0}\n", hs_RH.Status);
		data.AppendFormat("RH HS Pose: {0}\n", hs_RH.RootPose);
		data.AppendFormat("RH HS HandConf: {0}\n", hs_RH.HandConfidence);

		data.AppendFormat("LH Skel Query Res: {0}\n", result_skel_LH);
		data.AppendFormat("LH Skel Type: {0}\n", skel_LH.Type);
		data.AppendFormat("LH Skel NumBones: {0}\n", skel_LH.NumBones);

		data.AppendFormat("RH Skel Query Res: {0}\n", result_skel_RH);
		data.AppendFormat("RH Skel Type: {0}\n", skel_RH.Type);
		data.AppendFormat("RH Skel NumBones: {0}\n", skel_RH.NumBones);

		data.AppendFormat("LH Mesh Query Res: {0}\n", result_mesh_LH);
		data.AppendFormat("LH Mesh Type: {0}\n", mesh_LH.Type);
		data.AppendFormat("LH Mesh NumVers: {0}\n", mesh_LH.NumVertices);

		data.AppendFormat("RH Mesh Query Res: {0}\n", result_mesh_RH);
		data.AppendFormat("RH Mesh Type: {0}\n", mesh_RH.Type);
		data.AppendFormat("RH Mesh NumVers: {0}\n", mesh_RH.NumVertices);

		for (int i = 0; i < monitors.Count; i++)
		{
			monitors[i].Update();
			monitors[i].AppendToStringBuilder(ref data);
		}

		if (uiText != null)
		{
			uiText.text = data.ToString();
		}
	}

19 View Source File : TriDiagonalMatrix.cs
License : MIT License
Project Creator : ABTSoftware

public string ToDisplayString(string fmt = "", string prefix = "")
        {
            if (this.N > 0)
            {
                var s = new StringBuilder();
                string formatString = "{0" + fmt + "}";

                for (int r = 0; r < N; r++)
                {
                    s.Append(prefix);

                    for (int c = 0; c < N; c++)
                    {
                        s.AppendFormat(formatString, this[r, c]);
                        if (c < N - 1) s.Append(", ");
                    }

                    s.AppendLine();
                }

                return s.ToString();
            }
            else
            {
                return prefix + "0x0 Matrix";
            }
        }

19 View Source File : CreateInvertedIndex.cs
License : MIT License
Project Creator : ABTSoftware

private static string GetSourceCodeFromExample(Example example)
        {
            var description = example.SourceFiles;
            var uiCodeFiles = description.Where(x => x.Key.EndsWith(".xaml")).ToList();

            var sb = new StringBuilder();

            foreach (var uiFile in uiCodeFiles)
            {
                var xml = XDoreplacedent.Parse(uiFile.Value);

                foreach (var node in xml.Root.Nodes())
                {
                    if (node is XComment)
                    {
                        continue;
                    }

                    var xElements = ((XElement)node).Descendants();
                    foreach (var element in xElements)
                    {
                        if (!_codeStopWords.Contains(element.Name.LocalName))
                        {
                            sb.AppendFormat("{0} ", element.Name.LocalName);
                            foreach (var attribute in element.Attributes())
                            {
                                sb.AppendFormat("{0} ", attribute.Name.LocalName);
                            }
                        }
                    }
                }
            }
            
            var lines = sb.ToString();
            return lines;
        }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void UpdateHitTestInfo(IHitTestResult result) {
			StringBuilder text = new StringBuilder();

			if (result != null) {
				text.AppendFormat("Snapshot version {0}{1}", result.Snapshot.Version.Number, Environment.NewLine);

				if (result.View != null)
					text.AppendFormat("Over '{0}' view{1}", this.GetPlacementName(result.View), Environment.NewLine);

				switch (result.Type) {
					case HitTestResultType.Splitter: {
						EditorViewSplitter splitter = result.VisualElement as EditorViewSplitter;
						if (splitter != null)
							text.AppendLine("Over view splitter");
						break;
					}
					case HitTestResultType.ViewMargin:
						text.AppendFormat("Over '{0}' margin{1}", result.ViewMargin.Key, Environment.NewLine);
						text.AppendFormat("Closest text position is ({0},{1}){2}", result.Position.Line, result.Position.Character, Environment.NewLine);
						break;
					case HitTestResultType.ViewScrollBar: {
						System.Windows.Controls.Primitives.ScrollBar scrollBar = result.VisualElement as System.Windows.Controls.Primitives.ScrollBar;
						if (scrollBar != null)
							text.AppendFormat("Over '{0}' scrollbar{1}", scrollBar.Orientation, Environment.NewLine);
						break;
					}
					case HitTestResultType.ViewScrollBarBlock:
						text.AppendLine("Over scroll bar block");
						break;
					case HitTestResultType.ViewScrollBarSplitter: {
						ScrollBarSplitter splitter = result.VisualElement as ScrollBarSplitter;
						if (splitter != null)
							text.AppendLine("Over scroll bar splitter");
						break;
					}
					case HitTestResultType.ViewScrollBarTray:
						text.AppendLine("Over scroll bar tray (that can contain other controls like buttons)");
						break;
					case HitTestResultType.ViewTextArea:
						text.AppendFormat("Not directly over any view line or character{0}", Environment.NewLine);
						text.AppendFormat("Closest text position is ({0},{1}){2}", result.Position.Line, result.Position.Character, Environment.NewLine);
						break;
					case HitTestResultType.ViewTextAreaOverCharacter: {
						ITextSnapshotReader reader = result.GetReader();
						text.AppendFormat("Directly over offset {0} and text position ({1},{2}){3}", result.Offset, result.Position.Line, result.Position.Character, Environment.NewLine);
						text.AppendFormat("Directly over character '{0}'{1}", reader.Character, Environment.NewLine);
						
						IToken token = reader.Token;
						if (token != null) {
							text.AppendFormat("Directly over token '{0}' with range ({1},{2})-({3},{4}){5}", token.Key, 
								token.StartPosition.Line, token.StartPosition.Character, 
								token.EndPosition.Line, token.EndPosition.Character, Environment.NewLine);
							text.AppendFormat("Directly over token text '{0}'{1}", reader.TokenText, Environment.NewLine);
						}
						break;
					}
					case HitTestResultType.ViewTextAreaOverIntraTextSpacer:
						text.AppendFormat("Over spacer '{0}' on doreplacedent line {1}{2}", result.IntraTextSpacerTag, result.Position.Line, Environment.NewLine);
						break;
					case HitTestResultType.ViewTextAreaOverLine:
						text.AppendFormat("Over whitespace at the end of doreplacedent line {0}{1}", result.Position.Line, Environment.NewLine);
						break;
					default:
						if (result.VisualElement != null)
							text.AppendFormat("Over a '{0}' element{1}", result.VisualElement.GetType().FullName, Environment.NewLine);
						else
							text.AppendLine("No other hit test details available");
						break;
				}
			}
			else {
				text.AppendLine("Not over the SyntaxEditor");
			}

			resultsTextBox.Text = text.ToString();
		}

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

private void TraceSolutions()
		{
			var stringBuilder = new StringBuilder();

			var tableDifinition = new Dictionary<string, Func<SolutionInfo, string>>
			{
				{ "Unique name", s => s.Name },
				{ "Version", s => s.SolutionVersion.ToString() },
				{ "Installed on", s => s.InstalledOn.ToString() }
			};

			var columnFormat = new Dictionary<string, string>();

			// Calcule width of each column and write header
			foreach (var columnDefinition in tableDifinition)
			{
				var maxWidth = this.Solutions.Values.Max(solution => tableDifinition[columnDefinition.Key](solution).Length);
				var format = string.Format("{{0, -{0}}}", maxWidth);
				columnFormat[columnDefinition.Key] = format;

				stringBuilder.AppendFormat(format, columnDefinition.Key);
				stringBuilder.Append(" ");
			}
			stringBuilder.AppendLine();

			// Render rows
			foreach (var solution in this.Solutions.Values)
			{
				foreach (var columnDefinition in tableDifinition)
				{
					stringBuilder.AppendFormat(columnFormat[columnDefinition.Key], columnDefinition.Value(solution));
					stringBuilder.Append(" ");
				}
				stringBuilder.AppendLine();
			}

			ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Installed portal solutions on CRM {0}:{1}{2}", this.CrmVersion, Environment.NewLine, stringBuilder));
		}

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

private static void AppendFilenameToContentDisposition(Enreplacedy attachment, StringBuilder contentDisposition)
		{
			var filename = attachment.GetAttributeValue<string>("filename");

			if (string.IsNullOrEmpty(filename))
			{
				return;
			}

			// Escape any quotes in the filename. (There should rarely if ever be any, but still.)
			var escaped = filename.Replace(@"""", @"\""");

			// Quote the filename parameter value.
			contentDisposition.AppendFormat(@";filename=""{0}""", escaped);
		}

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

protected virtual void LogPaymentRequest(HttpContext context, PortalConfigurationDataAdapterDependencies dataAdapterDependencies, Tuple<Guid, string> quoteAndReturnUrl, Exception exception)
		{
			var log = new StringBuilder();

			log.AppendLine(GetType().FullName).AppendLine().AppendLine();
			log.AppendFormat("Exception: {0}", exception);

			LogPaymentRequest(context, dataAdapterDependencies, quoteAndReturnUrl, "Payment Exception", log.ToString());
		}

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

protected virtual void LogPaymentRequest(HttpContext context, PortalConfigurationDataAdapterDependencies dataAdapterDependencies, Tuple<Guid, string> quoteAndReturnUrl, IPaymentValidation validation)
		{
			var log = new StringBuilder();

			log.AppendLine(GetType().FullName).AppendLine();
			log.AppendLine(validation.Log);

			if (!string.IsNullOrEmpty(validation.ErrorMessage))
			{
				log.AppendLine().AppendFormat("Error message: {0}", validation.ErrorMessage).AppendLine();
			}

			LogPaymentRequest(
				context,
				dataAdapterDependencies,
				quoteAndReturnUrl,
				"Payment Log ({0})".FormatWith(validation.Success ? "Successful" : "Unsuccessful"),
				log.ToString());
		}

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

private static void AppendFilenameToContentDisposition(Enreplacedy annotation, StringBuilder contentDisposition)
		{
			var filename = annotation.GetAttributeValue<string>("filename");

			if (string.IsNullOrEmpty(filename))
			{
				return;
			}

			// Escape any quotes in the filename. (There should rarely if ever be any, but still.)
			var escaped = filename.Replace(@"""", @"\""");
			var encoded = HttpUtility.UrlEncode(escaped, System.Text.Encoding.UTF8);
			// Quote the filename parameter value.
			contentDisposition.AppendFormat(@";filename=""{0}""", encoded);
		}

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

private Dictionary<string, string> CreateResourceManagerStringOverrides()
		{
			var resources = new Dictionary<string, string>
			{
				{ "ActivityContainerControl.SubjectEllipsesText", ResourceManager.GetString("Visualization_SubjectEllipsesText") },
				{ "Web.Visualization.Axisreplacedle", ResourceManager.GetString("Visualization_Axisreplacedle") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping") },
				{ "Web.Visualization.EmptyAxisLabel", ResourceManager.GetString("Visualization_EmptyAxisLabel") },
				{ "Web.Visualization.Axisreplacedle.AVG", ResourceManager.GetString("Visualization_Axisreplacedle_AVG") },
				{ "Web.Visualization.Axisreplacedle.SUM", ResourceManager.GetString("Visualization_Axisreplacedle_SUM") },
				{ "Web.Visualization.Axisreplacedle.MIN", ResourceManager.GetString("Visualization_Axisreplacedle_MIN") },
				{ "Web.Visualization.Axisreplacedle.MAX", ResourceManager.GetString("Visualization_Axisreplacedle_MAX") },
				{ "Web.Visualization.Axisreplacedle.NONE", ResourceManager.GetString("Visualization_Axisreplacedle_NONE") },
				{ "Web.Visualization.Axisreplacedle.COUNT", ResourceManager.GetString("Visualization_Axisreplacedle_COUNT") },
				{ "Web.Visualization.Axisreplacedle.COUNTCOLUMN", ResourceManager.GetString("Visualization_Axisreplacedle_COUNTCOLUMN") },
				{ "Web.Visualization.Axisreplacedle.CurrencySymbol", ResourceManager.GetString("Visualization_Axisreplacedle_CurrencySymbol") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.DAY", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_DAY") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.FISCALPERIOD", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_FISCALPERIOD") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.FISCALYEAR", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_FISCALYEAR") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.MONTH", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_MONTH") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.QUARTER", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_QUARTER") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.WEEK", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_WEEK") },
				{ "Web.Visualization.Axisreplacedle.DateGrouping.YEAR", ResourceManager.GetString("Visualization_Axisreplacedle_DateGrouping_YEAR") },
				{ "Web.Visualization.Year.Quarter", ResourceManager.GetString("Visualization_Year_Quarter") },
				{ "Web.Visualization.Year.Week", ResourceManager.GetString("Visualization_Year_Week") },
				{ "Chart_NoData_Message", ResourceManager.GetString("Visualization_Chart_NoData_Message") }
			};

			var shortMonthCsv = new StringBuilder(string.Empty);
			for (int i = 1; i <= this.culture.Calendar.GetMonthsInYear(DateTime.Now.Year); i++)
			{
				DateTime month = new DateTime(DateTime.Now.Year, i, 1, this.culture.Calendar);
				shortMonthCsv.AppendFormat("{0},", month.ToString("MMM", this.culture));
			}
			resources.Add("Calendar_Short_Months", shortMonthCsv.ToString().TrimEnd(','));

			return resources;
		}

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

private static void AppendFilenameToContentDisposition(Enreplacedy salesLiteratureItem, StringBuilder contentDisposition)
		{
			var filename = salesLiteratureItem.GetAttributeValue<string>("filename");

			if (string.IsNullOrEmpty(filename))
			{
				return;
			}

			// Escape any quotes in the filename. (There should rarely if ever be any, but still.)
			var escaped = filename.Replace(@"""", @"\""");

			// Quote the filename parameter value.
			contentDisposition.AppendFormat(@";filename=""{0}""", escaped);
		}

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

internal static Uri GetNextPageLink(Uri requestUri, IEnumerable<KeyValuePair<string, string>> queryParameters, int pageSize)
		{
			var stringBuilder = new StringBuilder();
			var num = pageSize;
			foreach (var keyValuePair in queryParameters)
			{
				var key = keyValuePair.Key;
				var str1 = keyValuePair.Value;
				switch (key)
				{
					case "$top":
						int result1;
						if (int.TryParse(str1, out result1))
						{
							str1 = (result1 - pageSize).ToString(CultureInfo.InvariantCulture);
						}
						break;
					case "$skip":
						int result2;
						if (int.TryParse(str1, out result2))
						{
							num += result2;
						}
						continue;
				}
				var str2 = key.Length <= 0 || (int)key[0] != 36 ? Uri.EscapeDataString(key) : string.Format("${0}", Uri.EscapeDataString(key.Substring(1)));
				var str3 = Uri.EscapeDataString(str1);
				stringBuilder.Append(str2);
				stringBuilder.Append('=');
				stringBuilder.Append(str3);
				stringBuilder.Append('&');
			}
			stringBuilder.AppendFormat("$skip={0}", num);
			return new UriBuilder(requestUri)
			{
				Query = stringBuilder.ToString()
			}.Uri;
		}

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

private static void AppendFilenameToContentDisposition(Enreplacedy annotation, StringBuilder contentDisposition)
		{
			var filename = annotation.GetAttributeValue<string>("filename");

			if (string.IsNullOrEmpty(filename))
			{
				return;
			}

			// Escape any quotes in the filename. (There should rarely if ever be any, but still.)
			var escaped = filename.Replace(@"""", @"\""");

			// Quote the filename parameter value.
			contentDisposition.AppendFormat(@";filename=""{0}""", escaped);
		}

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

private static string GetVaryByRolesString(HttpContext context)
		{
			// If the role system is not enabled, fall back to varying cache by user.
			if (!Roles.Enabled)
			{
				return GetVaryByUserString(context);
			}

			var roles = context.User != null && context.User.Idenreplacedy != null && context.User.Idenreplacedy.IsAuthenticated
				? Roles.GetRolesForUser()
					.OrderBy(role => role)
					.Aggregate(new StringBuilder(), (sb, role) => sb.AppendFormat("[{0}]", role))
					.ToString()
				: string.Empty;

			return string.Format("IsAuthenticated={0},Roles={1},DisplayModes={2}",
				context.Request.IsAuthenticated,
				roles.GetHashCode(),
				GetVaryByDisplayModesString(context).GetHashCode());
		}

19 View Source File : ActivationByteHashExtractor.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr

public static string ToHexString(this byte[] source, int offset, int length)
        {
            StringBuilder stringBuilder = new StringBuilder(length * 2);
            for (int i = offset; i < offset + length; i++)
            {
                stringBuilder.AppendFormat("{0:x2}", source[i]);
            }

            return stringBuilder.ToString();
        }

19 View Source File : ILInstruction.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public override string ToString()
        {
            var ret = new StringBuilder();
            ret.AppendFormat("{0}", OpCode.ToString().PadLeft(16));
            if(Operand != null) ret.AppendFormat(" {0}", Operand);
            if(Annotation != null)
                ret.AppendFormat("    ; {0}", Annotation);
            return ret.ToString();
        }

19 View Source File : ILASTExpression.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public override string ToString()
        {
            var ret = new StringBuilder();
            ret.AppendFormat("{0}{1}(", ILCode.ToOpCode().Name, Type == null ? "" : ":" + Type.Value);
            if(Operand != null)
            {
                if(Operand is string)
                {
                    ASTConstant.EscapeString(ret, (string) Operand, true);
                }
                else if(Operand is IBasicBlock)
                {
                    ret.AppendFormat("Block_{0:x2}", ((IBasicBlock) Operand).Id);
                }
                else if(Operand is IBasicBlock[])
                {
                    var targets = ((IBasicBlock[]) Operand).Select(block => string.Format("Block_{0:x2}", block.Id));
                    ret.AppendFormat("[{0}]", string.Join(", ", targets));
                }
                else
                {
                    ret.Append(Operand);
                }
                if(Arguments.Length > 0)
                    ret.Append(";");
            }
            for(var i = 0; i < Arguments.Length; i++)
            {
                if(i != 0)
                    ret.Append(",");
                ret.Append(Arguments[i]);
            }
            ret.Append(")");
            return ret.ToString();
        }

19 View Source File : IRInstruction.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public override string ToString()
        {
            var ret = new StringBuilder();
            ret.AppendFormat("{0}", OpCode.ToString().PadLeft(16));
            if(Operand1 != null)
            {
                ret.AppendFormat(" {0}", Operand1);
                if(Operand2 != null)
                    ret.AppendFormat(", {0}", Operand2);
            }
            if(Annotation != null)
                ret.AppendFormat("    ; {0}", Annotation);
            return ret.ToString();
        }

19 View Source File : DarksVMDispatcher.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static unsafe string StackWalk(DarksVMContext ctx)
        {
            var ip = (uint) (ctx.Registers[DarksVMConstants.REG_IP].U8 - (ulong) ctx.Instance.Data.KoiSection);
            var bp = ctx.Registers[DarksVMConstants.REG_BP].U4;
            var sb = new StringBuilder();
            do
            {
                rand_state = rand_state * 1664525 + 1013904223;
                ulong key = rand_state | 1;
                sb.AppendFormat("|{0:x16}", ((ip * key) << 32) | (key & ~1UL));
                if(bp > 1)
                {
                    ip = (uint) (ctx.Stack[bp - 1].U8 - (ulong) ctx.Instance.Data.KoiSection);
                    var bpRef = ctx.Stack[bp].O as StackRef;
                    if(bpRef == null)
                        break;
                    bp = bpRef.StackPos;
                }
                else
                {
                    break;
                }
            } while(bp > 0);
            return sb.ToString(1, sb.Length - 1);
        }

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

private string ConvertExpression(Expression expression)
        {
            var binaryExpression = expression as BinaryExpression;
            if (binaryExpression != null)
            {
                return Convert(binaryExpression);
            }
            var Unary = expression as UnaryExpression;
            if (Unary != null)
            {
                return this.Convert(Unary);
            }
            var call = expression as MethodCallExpression;
            if (call != null)
            {
                return this.Convert(call);
            }
            var memberExpression = expression as MemberExpression;
            if (memberExpression != null)
            {
                return Convert(memberExpression);
            }
            var constantExpression = expression as ConstantExpression;
            if (constantExpression != null)
            {
                return this.Convert(constantExpression);
            }
            var array = expression as NewArrayExpression;
            if (array != null)
            {
                var sb = new StringBuilder();
                foreach (var arg in array.Expressions)
                {
                    sb.AppendFormat(",{0}", this.ConvertExpression(arg));
                }
                return sb.ToString().Trim(',');
            }
            if (expression.NodeType == ExpressionType.IsTrue)
            {
                return "1";
            }
            if (expression.NodeType == ExpressionType.IsFalse)
            {
                return "0";
            }
            throw new ArgumentException("Invalid lambda expression");
        }

See More Examples