Here are the examples of the csharp api System.Text.StringBuilder.Remove(int, int) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1035 Examples
19
View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private string ResolveGroup()
{
var buffer = new StringBuilder();
foreach (var item in _groupExpressions)
{
var result = new GroupExpressionResovle(item).Resovle();
buffer.Append($"{result},");
}
var sql = string.Empty;
if (buffer.Length > 0)
{
buffer.Remove(buffer.Length - 1, 1);
sql = $" GROUP BY {buffer}";
}
return sql;
}
19
View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 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
View Source File : GroupBySqlBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public void ResolveSort(StringBuilder sqlBuilder)
{
if (_queryBody.Sorts.IsNullOrEmpty())
return;
var startLength = sqlBuilder.Length;
sqlBuilder.Append(" ORDER BY");
foreach (var sort in _queryBody.Sorts)
{
if (sort.Mode == QuerySortMode.Lambda)
{
ResolveSort(sqlBuilder, sort.Lambda.Body, sort.Type);
}
else
{
sqlBuilder.AppendFormat(" {0} {1},", sort.Sql, sort.Type == SortType.Asc ? "ASC" : "DESC");
}
}
if (startLength + 9 == sqlBuilder.Length)
{
sqlBuilder.Remove(sqlBuilder.Length - 9, 9);
}
else if (startLength + 9 < sqlBuilder.Length)
{
sqlBuilder.Remove(sqlBuilder.Length - 1, 1);
}
}
19
View Source File : QueryableSqlBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public void ResolveSelect(StringBuilder sqlBuilder)
{
var select = _queryBody.Select;
//先解析出要排除的列
var excludeColumns = ResolveSelectExcludeColumns();
if (select == null)
{
//解析所有实体
ResolveSelectForEnreplacedy(sqlBuilder, 0, excludeColumns);
}
else if (select.Mode == QuerySelectMode.Sql)
{
//SQL语句
sqlBuilder.Append(select.Sql);
}
else if (select.Mode == QuerySelectMode.Lambda)
{
//表达式
var exp = select.Include.Body;
switch (exp.NodeType)
{
//返回的整个实体
case ExpressionType.Parameter:
ResolveSelectForEnreplacedy(sqlBuilder, 0, excludeColumns);
break;
//返回的某个列
case ExpressionType.MemberAccess:
ResolveSelectForMember(sqlBuilder, exp as MemberExpression, select.Include, excludeColumns);
if (sqlBuilder.Length > 0 && sqlBuilder[^1] == ',')
{
sqlBuilder.Remove(sqlBuilder.Length - 1, 1);
}
break;
//自定义的返回对象
case ExpressionType.New:
ResolveSelectForNew(sqlBuilder, exp as NewExpression, select.Include, excludeColumns);
break;
}
}
//移除末尾的逗号
if (sqlBuilder.Length > 0 && sqlBuilder[^1] == ',')
{
sqlBuilder.Remove(sqlBuilder.Length - 1, 1);
}
}
19
View Source File : QueryableSqlBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public void ResolveSort(StringBuilder sqlBuilder)
{
if (_queryBody.Sorts.IsNullOrEmpty())
return;
var startLength = sqlBuilder.Length;
sqlBuilder.Append(" ORDER BY");
foreach (var sort in _queryBody.Sorts)
{
if (sort.Mode == QuerySortMode.Lambda)
{
ResolveSort(sqlBuilder, sort.Lambda.Body, sort.Lambda, sort.Type);
}
else
{
sqlBuilder.AppendFormat(" {0} {1},", sort.Sql, sort.Type == SortType.Asc ? "ASC" : "DESC");
}
}
if (startLength + 9 == sqlBuilder.Length)
{
sqlBuilder.Remove(sqlBuilder.Length - 9, 9);
}
else if (startLength + 9 < sqlBuilder.Length)
{
sqlBuilder.Remove(sqlBuilder.Length - 1, 1);
}
}
19
View Source File : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH
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 : ExpressionResolver.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static void ResolveWhere(QueryBody queryBody, StringBuilder sqlBuilder, IQueryParameters parameters)
{
sqlBuilder.Append("WHERE ");
//记录下当前sqlBuilder的长度,用于解析完成后比对
var length = sqlBuilder.Length;
//解析where条件
if (queryBody.Wheres.NotNullAndEmpty())
{
foreach (var w in queryBody.Wheres)
{
switch (w.Mode)
{
case QueryWhereMode.Lambda:
Resolve(queryBody, w.Lambda.Body, w.Lambda, sqlBuilder, parameters);
break;
case QueryWhereMode.SubQuery:
Resolve(queryBody, w.SubQueryColumn.Body, w.SubQueryColumn, sqlBuilder, parameters);
var subSql = w.SubQueryable.ToListSql(parameters);
sqlBuilder.AppendFormat("{0} ({1})", w.SubQueryOperator, subSql);
break;
case QueryWhereMode.Sql:
sqlBuilder.AppendFormat("({0})", w.Sql);
break;
}
//通过比对长度判断是否有附加有效条件
if (length != sqlBuilder.Length)
sqlBuilder.Append(" AND ");
}
}
//解析软删除
ResolveWhereForSoftDelete(queryBody, sqlBuilder);
//解析租户
ResolveWhereForTenant(queryBody, sqlBuilder);
/*
* 1、当没有过滤条件时,需要移除WHERE关键字,此时sqlBuilder是以"WHERE "结尾,只需删除最后面的6位即可
* 2、当有过滤条件时,需要移除最后面的AND关键字,此时sqlBuilder是以" AND "结尾,也是只需删除最后面的5位即可
*/
var removeLength = length == sqlBuilder.Length ? 6 : 5;
sqlBuilder.Remove(sqlBuilder.Length - removeLength, removeLength);
}
19
View Source File : CrudSqlBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void BuildInsertSql()
{
var sb = new StringBuilder();
sb.Append("INSERT INTO {0} ");
sb.Append("(");
var valuesSql = new StringBuilder();
var primaryKey = _descriptor.PrimaryKey;
var dbAdapter = _descriptor.DbContext.Adapter;
foreach (var col in _descriptor.Columns)
{
//排除自增主键
if (col.IsPrimaryKey && (primaryKey.IsInt || primaryKey.IsLong))
continue;
dbAdapter.AppendQuote(sb, col.Name);
sb.Append(",");
dbAdapter.AppendParameter(valuesSql, col.PropertyName);
//针对PostgreSQL数据库的json和jsonb类型字段的处理
if (dbAdapter.Provider == DbProvider.PostgreSQL)
{
if (col.TypeName.EqualsIgnoreCase("jsonb"))
{
valuesSql.Append("::jsonb");
}
else if (col.TypeName.EqualsIgnoreCase("json"))
{
valuesSql.Append("::json");
}
}
valuesSql.Append(",");
}
//删除最后一个","
sb.Remove(sb.Length - 1, 1);
sb.Append(") VALUES");
//设置批量删除
_sql.SetBatchAdd(sb.ToString());
sb.Append("(");
//删除最后一个","
if (valuesSql.Length > 0)
valuesSql.Remove(valuesSql.Length - 1, 1);
sb.Append(valuesSql);
sb.Append(")");
if (dbAdapter.Provider != DbProvider.PostgreSQL)
{
sb.Append(";");
}
_sql.SetAdd(sb.ToString());
}
19
View Source File : CrudSqlBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void BuildUpdateSql()
{
var sb = new StringBuilder();
sb.Append("UPDATE {0} SET");
_sql.SetUpdate(sb.ToString());
var dbAdapter = _descriptor.DbContext.Adapter;
var primaryKey = _descriptor.PrimaryKey;
if (!primaryKey.IsNo)
{
var columns = _descriptor.Columns.Where(m => !m.IsPrimaryKey);
foreach (var col in columns)
{
sb.AppendFormat("{0}={1}", dbAdapter.AppendQuote(col.Name), dbAdapter.AppendParameter(col.PropertyName));
//针对PostgreSQL数据库的json和jsonb类型字段的处理
if (dbAdapter.Provider == DbProvider.PostgreSQL)
{
if (col.TypeName.EqualsIgnoreCase("jsonb"))
{
sb.Append("::jsonb");
}
else if (col.TypeName.EqualsIgnoreCase("json"))
{
sb.Append("::json");
}
}
sb.Append(",");
}
sb.Remove(sb.Length - 1, 1);
sb.AppendFormat(" WHERE {0}={1};", dbAdapter.AppendQuote(primaryKey.ColumnName), dbAdapter.AppendParameter(primaryKey.PropertyName));
_sql.SetUpdateSingle(sb.ToString());
}
}
19
View Source File : GroupBySqlBuilder.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
private void ResolveGroupBy(StringBuilder sqlBuilder)
{
if (_queryBody.GroupBy.Body.NodeType != ExpressionType.New)
{
throw new ArgumentException("分组表达式必须使用匿名函数方式");
}
var newExp = _queryBody.GroupBy.Body as NewExpression;
sqlBuilder.Append(" GROUP BY");
for (var i = 0; i < newExp!.Arguments.Count; i++)
{
var arg = newExp.Arguments[i];
switch (arg.NodeType)
{
case ExpressionType.MemberAccess:
var memExp = arg as MemberExpression;
if (memExp!.Expression.Type.IsString())
{
//字符串的Length属性
var columnName = _queryBody.GetColumnName(memExp.Expression);
sqlBuilder.AppendFormat(" {0},", _queryBody.DbAdapter.FunctionMapper(memExp.Member.Name, columnName));
}
else if (DbConstants.ENreplacedY_INTERFACE_TYPE.IsImplementType(memExp.Expression.Type))
{
//解析列信息,如:m.T1.Id
var columnName = _queryBody.GetColumnName(memExp);
sqlBuilder.AppendFormat(" {0},", columnName);
}
break;
case ExpressionType.Call:
if (arg is MethodCallExpression callExp)
{
var columnName = _queryBody.GetColumnName(callExp!.Object);
var args = ExpressionResolver.Arguments2Object(callExp.Arguments);
sqlBuilder.AppendFormat(" {0},", _dbAdapter.FunctionMapper(callExp.Method.Name, columnName, callExp.Object!.Type, args));
}
break;
}
}
//移除末尾的逗号
if (sqlBuilder[^1] == ',')
{
sqlBuilder.Remove(sqlBuilder.Length - 1, 1);
}
}
19
View Source File : SourceStringBuilder.cs
License : MIT License
Project Creator : 31
License : MIT License
Project Creator : 31
public void BlockPrefix(string delimiter, Action writeInner)
{
_indentPrefix.Append(delimiter);
writeInner();
_indentPrefix.Remove(_indentPrefix.Length - delimiter.Length, delimiter.Length);
}
19
View Source File : SerializableDictionary.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
public override string ToString() {
StringBuilder toReturn = new StringBuilder();
List<TKey> keys = Keys.ToList<TKey>();
List<TValue> values = Values.ToList<TValue>();
toReturn.Append("[");
for (int i = 0; i < keys.Count; i++) {
toReturn.Append("{");
toReturn.Append(keys[i].ToString());
toReturn.Append(" : ");
toReturn.Append(values[i].ToString());
toReturn.Append("}, \n");
}
toReturn.Remove(toReturn.Length-3, 3);
toReturn.Append("]");
return toReturn.ToString();
}
19
View Source File : JsonWriter.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public void Reset ()
{
has_reached_end = false;
ctx_stack.Clear ();
context = new WriterContext ();
ctx_stack.Push (context);
if (inst_string_builder != null)
inst_string_builder.Remove (0, inst_string_builder.Length);
}
19
View Source File : Lexer.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public bool NextToken ()
{
StateHandler handler;
fsm_context.Return = false;
while (true) {
handler = fsm_handler_table[state - 1];
if (! handler (fsm_context))
throw new JsonException (input_char);
if (end_of_input)
return false;
if (fsm_context.Return) {
string_value = string_buffer.ToString ();
string_buffer.Remove (0, string_buffer.Length);
token = fsm_return_table[state - 1];
if (token == (int) ParserToken.Char)
token = input_char;
state = fsm_context.NextState;
return true;
}
state = fsm_context.NextState;
}
}
19
View Source File : WexApi.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
static string BuildPostData(NameValueDictionary d)
{
var s = new StringBuilder();
foreach (var key in d.Keys)
{
var value = d[key];
s.AppendFormat("{0}={1}", key, WebUtility.UrlEncode(value));
s.Append("&");
}
if (s.Length > 0) s.Remove(s.Length - 1, 1);
return s.ToString();
}
19
View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aadreja
License : Apache License 2.0
Project Creator : aadreja
internal static StringBuilder RemoveLastComma(this StringBuilder pString)
{
if (pString[pString.Length - 1] == ',')
{
pString.Remove(pString.Length - 1, 1);
}
return pString;
}
19
View Source File : HighlightingColor.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "CSS usually uses lowercase, and all possible values are English-only")]
public virtual string ToCss()
{
StringBuilder b = new StringBuilder();
if (Foreground != null) {
Color? c = Foreground.GetColor(null);
if (c != null) {
b.AppendFormat(CultureInfo.InvariantCulture, "color: #{0:x2}{1:x2}{2:x2}; ", c.Value.R, c.Value.G, c.Value.B);
}
}
if (FontWeight != null) {
b.Append("font-weight: ");
b.Append(FontWeight.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (FontStyle != null) {
b.Append("font-style: ");
b.Append(FontStyle.Value.ToString().ToLowerInvariant());
b.Append("; ");
}
if (Underline != null) {
b.Append("text-decoration: ");
b.Append(Underline.Value ? "underline" : "none");
b.Append("; ");
}
if (Strikethrough != null) {
if (Underline == null)
b.Append("text-decoration: ");
b.Remove(b.Length - 1, 1);
b.Append(Strikethrough.Value ? " line-through" : " none");
b.Append("; ");
}
return b.ToString();
}
19
View Source File : IndentationReformatter.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
public void Step(IDoreplacedentAccessor doc, IndentationSettings set)
{
string line = doc.Text;
if (set.LeaveEmptyLines && line.Length == 0) return; // leave empty lines empty
line = line.TrimStart();
StringBuilder indent = new StringBuilder();
if (line.Length == 0) {
// Special treatment for empty lines:
if (blockComment || (inString && verbatim))
return;
indent.Append(block.InnerIndent);
indent.Append(Repeat(set.IndentString, block.OneLineBlock));
if (block.Continuation)
indent.Append(set.IndentString);
if (doc.Text != indent.ToString())
doc.Text = indent.ToString();
return;
}
if (TrimEnd(doc))
line = doc.Text.TrimStart();
Block oldBlock = block;
bool startInComment = blockComment;
bool startInString = (inString && verbatim);
#region Parse char by char
lineComment = false;
inChar = false;
escape = false;
if (!verbatim) inString = false;
lastRealChar = '\n';
char lastchar = ' ';
char c = ' ';
char nextchar = line[0];
for (int i = 0; i < line.Length; i++) {
if (lineComment) break; // cancel parsing current line
lastchar = c;
c = nextchar;
if (i + 1 < line.Length)
nextchar = line[i + 1];
else
nextchar = '\n';
if (escape) {
escape = false;
continue;
}
#region Check for comment/string chars
switch (c) {
case '/':
if (blockComment && lastchar == '*')
blockComment = false;
if (!inString && !inChar) {
if (!blockComment && nextchar == '/')
lineComment = true;
if (!lineComment && nextchar == '*')
blockComment = true;
}
break;
case '#':
if (!(inChar || blockComment || inString))
lineComment = true;
break;
case '"':
if (!(inChar || lineComment || blockComment)) {
inString = !inString;
if (!inString && verbatim) {
if (nextchar == '"') {
escape = true; // skip escaped quote
inString = true;
} else {
verbatim = false;
}
} else if (inString && lastchar == '@') {
verbatim = true;
}
}
break;
case '\'':
if (!(inString || lineComment || blockComment)) {
inChar = !inChar;
}
break;
case '\\':
if ((inString && !verbatim) || inChar)
escape = true; // skip next character
break;
}
#endregion
if (lineComment || blockComment || inString || inChar) {
if (wordBuilder.Length > 0)
block.LastWord = wordBuilder.ToString();
wordBuilder.Length = 0;
continue;
}
if (!Char.IsWhiteSpace(c) && c != '[' && c != '/') {
if (block.Bracket == '{')
block.Continuation = true;
}
if (Char.IsLetterOrDigit(c)) {
wordBuilder.Append(c);
} else {
if (wordBuilder.Length > 0)
block.LastWord = wordBuilder.ToString();
wordBuilder.Length = 0;
}
#region Push/Pop the blocks
switch (c) {
case '{':
block.ResetOneLineBlock();
blocks.Push(block);
block.StartLine = doc.LineNumber;
if (block.LastWord == "switch") {
block.Indent(set.IndentString + set.IndentString);
/* oldBlock refers to the previous line, not the previous block
* The block we want is not available anymore because it was never pushed.
* } else if (oldBlock.OneLineBlock) {
// Inside a one-line-block is another statement
// with a full block: indent the inner full block
// by one additional level
block.Indent(set, set.IndentString + set.IndentString);
block.OuterIndent += set.IndentString;
// Indent current line if it starts with the '{' character
if (i == 0) {
oldBlock.InnerIndent += set.IndentString;
}*/
} else {
block.Indent(set);
}
block.Bracket = '{';
break;
case '}':
while (block.Bracket != '{') {
if (blocks.Count == 0) break;
block = blocks.Pop();
}
if (blocks.Count == 0) break;
block = blocks.Pop();
block.Continuation = false;
block.ResetOneLineBlock();
break;
case '(':
case '[':
blocks.Push(block);
if (block.StartLine == doc.LineNumber)
block.InnerIndent = block.OuterIndent;
else
block.StartLine = doc.LineNumber;
block.Indent(Repeat(set.IndentString, oldBlock.OneLineBlock) +
(oldBlock.Continuation ? set.IndentString : "") +
(i == line.Length - 1 ? set.IndentString : new String(' ', i + 1)));
block.Bracket = c;
break;
case ')':
if (blocks.Count == 0) break;
if (block.Bracket == '(') {
block = blocks.Pop();
if (IsSingleStatementKeyword(block.LastWord))
block.Continuation = false;
}
break;
case ']':
if (blocks.Count == 0) break;
if (block.Bracket == '[')
block = blocks.Pop();
break;
case ';':
case ',':
block.Continuation = false;
block.ResetOneLineBlock();
break;
case ':':
if (block.LastWord == "case"
|| line.StartsWith("case ", StringComparison.Ordinal)
|| line.StartsWith(block.LastWord + ":", StringComparison.Ordinal)) {
block.Continuation = false;
block.ResetOneLineBlock();
}
break;
}
if (!Char.IsWhiteSpace(c)) {
// register this char as last char
lastRealChar = c;
}
#endregion
}
#endregion
if (wordBuilder.Length > 0)
block.LastWord = wordBuilder.ToString();
wordBuilder.Length = 0;
if (startInString) return;
if (startInComment && line[0] != '*') return;
if (doc.Text.StartsWith("//\t", StringComparison.Ordinal) || doc.Text == "//")
return;
if (line[0] == '}') {
indent.Append(oldBlock.OuterIndent);
oldBlock.ResetOneLineBlock();
oldBlock.Continuation = false;
} else {
indent.Append(oldBlock.InnerIndent);
}
if (indent.Length > 0 && oldBlock.Bracket == '(' && line[0] == ')') {
indent.Remove(indent.Length - 1, 1);
} else if (indent.Length > 0 && oldBlock.Bracket == '[' && line[0] == ']') {
indent.Remove(indent.Length - 1, 1);
}
if (line[0] == ':') {
oldBlock.Continuation = true;
} else if (lastRealChar == ':' && indent.Length >= set.IndentString.Length) {
if (block.LastWord == "case" || line.StartsWith("case ", StringComparison.Ordinal) || line.StartsWith(block.LastWord + ":", StringComparison.Ordinal))
indent.Remove(indent.Length - set.IndentString.Length, set.IndentString.Length);
} else if (lastRealChar == ')') {
if (IsSingleStatementKeyword(block.LastWord)) {
block.OneLineBlock++;
}
} else if (lastRealChar == 'e' && block.LastWord == "else") {
block.OneLineBlock = Math.Max(1, block.PreviousOneLineBlock);
block.Continuation = false;
oldBlock.OneLineBlock = block.OneLineBlock - 1;
}
if (doc.IsReadOnly) {
// We can't change the current line, but we should accept the existing
// indentation if possible (=if the current statement is not a multiline
// statement).
if (!oldBlock.Continuation && oldBlock.OneLineBlock == 0 &&
oldBlock.StartLine == block.StartLine &&
block.StartLine < doc.LineNumber && lastRealChar != ':') {
// use indent StringBuilder to get the indentation of the current line
indent.Length = 0;
line = doc.Text; // get untrimmed line
for (int i = 0; i < line.Length; ++i) {
if (!Char.IsWhiteSpace(line[i]))
break;
indent.Append(line[i]);
}
// /* */ multiline comments have an extra space - do not count it
// for the block's indentation.
if (startInComment && indent.Length > 0 && indent[indent.Length - 1] == ' ') {
indent.Length -= 1;
}
block.InnerIndent = indent.ToString();
}
return;
}
if (line[0] != '{') {
if (line[0] != ')' && oldBlock.Continuation && oldBlock.Bracket == '{')
indent.Append(set.IndentString);
indent.Append(Repeat(set.IndentString, oldBlock.OneLineBlock));
}
// this is only for blockcomment lines starting with *,
// all others keep their old indentation
if (startInComment)
indent.Append(' ');
if (indent.Length != (doc.Text.Length - line.Length) ||
!doc.Text.StartsWith(indent.ToString(), StringComparison.Ordinal) ||
Char.IsWhiteSpace(doc.Text[indent.Length])) {
doc.Text = indent.ToString() + line;
}
}
19
View Source File : DateFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string DateToRfc822(DateTime? date)
{
if (date == null)
{
return null;
}
if (date.Value.Kind == DateTimeKind.Utc)
{
return date.Value.ToString("ddd, dd MMM yyyy HH:mm:ss Z", CultureInfo.InvariantCulture);
}
var builder = new StringBuilder(date.Value.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture));
builder.Remove(builder.Length - 3, 1);
return builder.ToString();
}
19
View Source File : ISymbolExtensions.cs
License : MIT License
Project Creator : adrianoc
License : MIT License
Project Creator : adrianoc
public static string replacedtringNewArrayExpression(this IEnumerable<IParameterSymbol> self)
{
if (!self.Any())
{
return "new ParamData[0]";
}
var sb = new StringBuilder();
var arrayExp = self.Aggregate(sb,
(acc, curr) =>
{
var elementType = (curr.Type as IArrayTypeSymbol)?.ElementType ?? curr.Type;
var isArray = curr.Type is IArrayTypeSymbol ? "true" : "false";
var isTypeParameter = elementType.Kind == SymbolKind.TypeParameter ? "true" : "false";
acc.Append($",new ParamData {{ IsArray = {isArray}, FullName = \"{elementType.FullyQualifiedName()}\", IsTypeParameter = {isTypeParameter} }}");
return acc;
},
final => final.Remove(0, 1)).Insert(0, "new [] {").Append('}');
return arrayExp.ToString();
}
19
View Source File : AnarchyExtensions.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public static string ValidateUnityTags(string text)
{
StringBuilder builder = new StringBuilder(text);
Stack<Tag> tags = new Stack<Tag>();
var matches = Regex.Matches(text, @"<(\/?)(\w+)(?:=.+?)?>");
foreach (Match match in matches)
{
var tag = new Tag(
match.Groups[2].Value,
string.IsNullOrEmpty(match.Groups[1].Value));
if (tag.IsOpeningTag)
{
tags.Push(tag);
}
else
{
if (tags.Count > 0 && tags.Peek().TagName == tag.TagName)
{
tags.Pop();
}
else
{
builder.Remove(match.Index, match.Length);
}
}
}
while (tags.Count > 0)
{
builder.Append(tags.Pop().ClosingTag);
}
return builder.ToString();
}
19
View Source File : ProcessExtensions.cs
License : GNU General Public License v3.0
Project Creator : aglab2
License : GNU General Public License v3.0
Project Creator : aglab2
public static bool ReadString(this Process process, IntPtr addr, ReadStringType type, StringBuilder sb)
{
var bytes = new byte[sb.Capacity];
SizeT read;
if (!WinAPI.ReadProcessMemory(process.Handle, addr, bytes, (SizeT)bytes.Length, out read)
|| read != (SizeT)bytes.Length)
return false;
if (type == ReadStringType.AutoDetect)
{
if (read.ToUInt64() >= 2 && bytes[1] == '\x0')
sb.Append(Encoding.Unicode.GetString(bytes));
else
sb.Append(Encoding.UTF8.GetString(bytes));
}
else if (type == ReadStringType.UTF8)
sb.Append(Encoding.UTF8.GetString(bytes));
else if (type == ReadStringType.UTF16)
sb.Append(Encoding.Unicode.GetString(bytes));
else
sb.Append(Encoding.ASCII.GetString(bytes));
for (int i = 0; i < sb.Length; i++)
{
if (sb[i] == '\0')
{
sb.Remove(i, sb.Length - i);
break;
}
}
return true;
}
19
View Source File : AppConsole.cs
License : GNU General Public License v3.0
Project Creator : agolaszewski
License : GNU General Public License v3.0
Project Creator : agolaszewski
public string Read(out ConsoleKey? intteruptedKey, Func<char, bool> allowTypeFn, params ConsoleKey[] interruptKeys)
{
intteruptedKey = null;
StringBuilder stringBuilder = new StringBuilder();
ConsoleKeyInfo keyInfo;
bool returnToPreviousLine = false;
do
{
keyInfo = Console.ReadKey();
if (interruptKeys.Contains(keyInfo.Key))
{
intteruptedKey = keyInfo.Key;
return stringBuilder.ToString();
}
switch (keyInfo.Key)
{
case (ConsoleKey.Backspace):
{
if (stringBuilder.Length > 0)
{
if (returnToPreviousLine)
{
Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
returnToPreviousLine = false;
}
stringBuilder = stringBuilder.Remove(stringBuilder.Length - 1, 1);
int oldL = Console.CursorLeft;
int oldT = Console.CursorTop;
PositionWrite(" ", oldL, oldT);
Console.SetCursorPosition(oldL, oldT);
if (Console.CursorLeft == 0)
{
returnToPreviousLine = true;
}
}
else
{
Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop);
}
break;
}
case (ConsoleKey.Enter):
{
break;
}
default:
{
if (allowTypeFn(keyInfo.KeyChar))
{
stringBuilder.Append(keyInfo.KeyChar);
returnToPreviousLine = false;
}
else
{
PositionWrite(" ", Console.CursorLeft - 1, Console.CursorTop);
Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
}
break;
}
}
}
while (keyInfo.Key != ConsoleKey.Enter);
return stringBuilder.ToString();
}
19
View Source File : ArrayData.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
License : GNU Affero General Public License v3.0
Project Creator : aianlinb
public override string ToString() {
if (Value == null)
return "{null}";
var s = new StringBuilder("[");
foreach (var f in Value) {
s.Append(f?.ToString() ?? "{null}");
if (Value is uint or ulong)
s.Append('U');
if (Value is long or ulong)
s.Append('L');
else if (Value is float)
s.Append('F');
else if (Value is double)
s.Append('D');
s.Append(", ");
}
if (s.Length > 2)
s.Remove(s.Length - 2, 2);
s.Append(']');
return s.ToString();
}
19
View Source File : DragDropTarget.cs
License : MIT License
Project Creator : aillieo
License : MIT License
Project Creator : aillieo
public override string GetDebugString()
{
sb.Remove(0, sb.Length);
for (int i = 0; i < attachedItems.Count; ++ i)
{
sb.AppendLine(attachedItems[i].gameObject.name);
}
return string.Format("<b>matchingChannel</b> = B{0}\n<b>attachedItems</b> = \n[\n{1}]", Convert.ToString(matchingChannel, 2),sb.ToString());
}
19
View Source File : HtmlFromXamlConverter.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.replacedert(xamlReader.NodeType == XmlNodeType.Element);
bool elementContentStarted = false;
if (xamlReader.IsEmptyElement)
{
if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
{
// Output STYLE attribute and clear inlineStyle buffer.
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
inlineStyle.Remove(0, inlineStyle.Length);
}
elementContentStarted = true;
}
else
{
while (ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement)
{
switch (xamlReader.NodeType)
{
case XmlNodeType.Element:
if (xamlReader.Name.Contains("."))
{
AddComplexProperty(xamlReader, inlineStyle);
}
else
{
if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0)
{
// Output STYLE attribute and clear inlineStyle buffer.
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
inlineStyle.Remove(0, inlineStyle.Length);
}
elementContentStarted = true;
WriteElement(xamlReader, htmlWriter, inlineStyle);
}
Debug.replacedert(xamlReader.NodeType == XmlNodeType.EndElement || xamlReader.NodeType == XmlNodeType.Element && xamlReader.IsEmptyElement);
break;
case XmlNodeType.Comment:
if (htmlWriter != null)
{
if (!elementContentStarted && inlineStyle.Length > 0)
{
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
}
htmlWriter.WriteComment(xamlReader.Value);
}
elementContentStarted = true;
break;
case XmlNodeType.CDATA:
case XmlNodeType.Text:
case XmlNodeType.SignificantWhitespace:
if (htmlWriter != null)
{
if (!elementContentStarted && inlineStyle.Length > 0)
{
htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString());
}
htmlWriter.WriteString(xamlReader.Value);
}
elementContentStarted = true;
break;
}
}
Debug.replacedert(xamlReader.NodeType == XmlNodeType.EndElement);
}
}
19
View Source File : HtmlFromXamlConverter.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev
private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle)
{
Debug.replacedert(xamlReader.NodeType == XmlNodeType.Element);
// Clear string builder for the inline style
inlineStyle.Remove(0, inlineStyle.Length);
if (!xamlReader.HasAttributes)
{
return;
}
bool borderSet = false;
while (xamlReader.MoveToNextAttribute())
{
string css = null;
switch (xamlReader.Name)
{
// Character fomatting properties
// ------------------------------
case "Background":
css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";";
break;
case "FontFamily":
css = "font-family:" + xamlReader.Value + ";";
break;
case "FontStyle":
css = "font-style:" + xamlReader.Value.ToLower(CultureInfo.InvariantCulture) + ";";
break;
case "FontWeight":
css = "font-weight:" + xamlReader.Value.ToLower(CultureInfo.InvariantCulture) + ";";
break;
case "FontStretch":
break;
case "FontSize":
css = "font-size:" + xamlReader.Value + ";";
break;
case "Foreground":
css = "color:" + ParseXamlColor(xamlReader.Value) + ";";
break;
case "TextDecorations":
css = "text-decoration:underline;";
break;
case "TextEffects":
break;
case "Emphasis":
break;
case "StandardLigatures":
break;
case "Variants":
break;
case "Capitals":
break;
case "Fraction":
break;
// Paragraph formatting properties
// -------------------------------
case "Padding":
css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";";
break;
case "Margin":
css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";";
break;
case "BorderThickness":
css = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";";
borderSet = true;
break;
case "BorderBrush":
css = "border-color:" + ParseXamlColor(xamlReader.Value) + ";";
borderSet = true;
break;
case "LineHeight":
break;
case "TextIndent":
css = "text-indent:" + xamlReader.Value + ";";
break;
case "TextAlignment":
css = "text-align:" + xamlReader.Value + ";";
break;
case "IsKeptTogether":
break;
case "IsKeptWithNext":
break;
case "ColumnBreakBefore":
break;
case "PageBreakBefore":
break;
case "FlowDirection":
break;
// Table attributes
// ----------------
case "Width":
css = "width:" + xamlReader.Value + ";";
break;
case "ColumnSpan":
htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value);
break;
case "RowSpan":
htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value);
break;
// Hyperlink Attributes
case "NavigateUri" :
htmlWriter.WriteAttributeString("HREF", xamlReader.Value);
break;
}
if (css != null)
{
inlineStyle.Append(css);
}
}
if (borderSet)
{
inlineStyle.Append("border-style:solid;mso-element:para-border-div;");
}
// Return the xamlReader back to element level
xamlReader.MoveToElement();
Debug.replacedert(xamlReader.NodeType == XmlNodeType.Element);
}
19
View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
private string CleanText(string replaceWith = null)
{
MatchCollection matches = null;
var result = "";
while ((matches = StringyFyExp.Matches(sb.ToString())).Count > 0)
{
var exp = matches[0];
result = exp.Value.Replace("</Stringify>", "").TrimEnd(']').Substring(@"<Stringify>\[".Length - 1);
sb = sb.Remove(exp.Index, exp.Value.Length);
if (replaceWith != null)
sb = sb.Insert(exp.Index, replaceWith);
}
return result;
}
19
View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
internal void CleanDecoder(string replaceWith)
{
if (!EndWithDecoder())
sb.Append(replaceWith);
else
{
MatchCollection matches = null;
var result = new string[0];
while ((matches = DataEncodeExp.Matches(sb.ToString())).Count > 0)
{
var m = matches[0];
result = m.Value.Replace("</DataEncode>", "").TrimEnd(']').Substring(@"<DataEncode>\[".Length - 1).Split('|'); // get the key
sb = sb.Remove(m.Index, m.Value.Length);
if (replaceWith.Contains("String["))
{
var spt = replaceWith.Split(new string[] { "]," }, StringSplitOptions.None).Where(x => !string.IsNullOrEmpty(x));
var i = 0;
var value = "";
foreach (var str in spt)
{
i++;
var xValue = str.Trim().Replace("String[", "").TrimEnd("]");
var rValue = xValue.TrimStart('%').TrimEnd("%");
var codedValue = new DataCipher(result.First(), result.Last().ConvertValue<int>().ConvertValue<DataCipherKeySize>()).Encrypt(rValue);
if (xValue.StartsWith("%"))
codedValue = "%" + codedValue;
if (xValue.EndsWith("%"))
codedValue += "%";
value += $"String[{codedValue}]{(i == spt.Count() ? "" : ",")}";
}
sb.Insert(m.Index, value);
}
else if (replaceWith.Contains("Date["))
{
var spt = replaceWith.Split(new string[] { "]," }, StringSplitOptions.None).Where(x => !string.IsNullOrEmpty(x));
var i = 0;
var value = "";
foreach (var str in spt)
{
i++;
var xValue = str.Trim().Replace("Date[", "").TrimEnd("]");
var rValue = xValue.TrimStart('%').TrimEnd("%");
var codedValue = new DataCipher(result.First(), result.Last().ConvertValue<int>().ConvertValue<DataCipherKeySize>()).Encrypt(rValue);
if (xValue.StartsWith("%"))
codedValue = "%" + codedValue;
if (xValue.EndsWith("%"))
codedValue += "%";
value += $"Date[{codedValue}]{(i == spt.Count() ? "" : ",")}";
}
sb.Insert(m.Index, value);
}
else
sb = sb.Insert(m.Index, new DataCipher(result.First(), result.Last().ConvertValue<int>().ConvertValue<DataCipherKeySize>()).Encrypt(replaceWith));
}
}
}
19
View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
public string GetInvert()
{
if (sb.Length <= 4)
return string.Empty;
var key = "NOT ";
var str = sb.ToString().Substring(sb.Length - key.Length);
if (str == key)
{
sb = sb.Remove(sb.Length - key.Length, key.Length);
return " " + key;
}
return string.Empty;
}
19
View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
private void validateBinaryExpression(BinaryExpression b, Expression exp)
{
if (b != null && exp != null)
{
var StringifyText = StringyFyExp.Matches(sb.ToString()).Cast<Match>().FirstOrDefault();
var isEnum = StringifyText != null;
if ((exp.NodeType == ExpressionType.MemberAccess || exp.NodeType == ExpressionType.Not)
&& b.NodeType != ExpressionType.Equal
&& b.NodeType != ExpressionType.NotEqual && (exp.Type == typeof(bool) || exp.Type == typeof(bool?)))
{
if (exp.NodeType != ExpressionType.Not)
sb.Append(" = " + (DataBaseTypes == DataBaseTypes.PostgreSql ? "true" : "1"));
else
sb.Append(" = " + (DataBaseTypes == DataBaseTypes.PostgreSql ? "false" : "0"));
}
}
else
{
MatchCollection matches = BoolExp.Matches(sb.ToString());
var result = "";
var i = 0;
var length = matches.Count - 1;
while ((matches = BoolExp.Matches(sb.ToString())).Count > 0)
{
var m = matches[0];
result = m.Value.Replace("</bool>", "").TrimEnd(']').Substring(@"<bool>\[".Length - 1);
var addValue = m.Index + boolString.Length + 3 <= sb.Length ? sb.ToString().Substring(m.Index, boolString.Length + 3) : string.Empty;
sb = sb.Remove(m.Index, m.Value.Length);
if (!addValue.Contains("="))
{
var value = result.Replace("T", "");
var add = result.Contains("T");
if ((b == null || i < length || m.Index + m.Value.Length < sb.ToString().Length - 1))
sb = sb.Insert(m.Index, (!add ? " = " : "") + (value.ConvertValue<int>() == 0 ? DataBaseTypes == DataBaseTypes.PostgreSql ? "false" : "0" : DataBaseTypes == DataBaseTypes.PostgreSql ? "true" : "1"));
}
i++;
}
}
}
19
View Source File : LinqToSql.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
protected object VisitMember(MemberExpression m, bool columnOnly)
{
try
{
if (m.Expression != null && m.Expression.NodeType == ExpressionType.Constant && (_overridedNodeType == null))
{
VisitConstantFixed(m.Expression as ConstantExpression, m.Member?.Name);
return m;
}
else if (m.Expression?.ToString().Contains("DisplayClreplaced") ?? false || m.Expression == null)
{
var hasValueAttr = m.ToString().EndsWith(".HasValue");
bool isNot = sb.ToString().EndsWith("NOT ");
var value = ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke());
var column = value;
if (isNot)
{
var invert = GetInvert();
column = $"(CASE WHEN {value} = {boolString.Replace("#", "0T")} THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "0")}";
}
else if (hasValueAttr)
{
column = $"(CASE WHEN {value} = {boolString.Replace("#", "0T")} THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "1")}";
}
CleanDecoder(column);
return m;
}
else if (m.Expression != null && (m.Expression.NodeType == ExpressionType.Parameter || (m.ToString().EndsWith(".HasValue") && m.Expression.NodeType == ExpressionType.MemberAccess)) && (_overridedNodeType == null))
{
var hasValueAttr = m.ToString().EndsWith(".HasValue");
_overridedNodeType = null;
var cl = hasValueAttr ? (m.Expression as MemberExpression).Expression.Type : m.Expression.Type;
var prop = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.Name == (hasValueAttr ? (m.Expression as MemberExpression).Member.Name : m.Member.Name));
var name = prop.GetPropertyName();
var table = cl.TableName().GetName(DataBaseTypes);
var columnName = string.Format("{0}.[{1}]", table, name).CleanValidSqlName(DataBaseTypes);
var dataEncode = prop.GetCustomAttribute<DataEncode>();
if (columnOnly)
return columnName;
bool isNot = sb.ToString().EndsWith("NOT ");
if (prop.PropertyType.IsEnum && prop.ContainAttribute<Stringify>())
{
if (!SavedTypes.ContainsKey(prop.FullName))
SavedTypes.TryAdd(prop.FullName, prop.PropertyType);
columnName += stringyFy.Replace("#", prop.FullName);
}
if (isNot)
{
var invert = GetInvert();
if (!hasValueAttr)
columnName = $"(CASE WHEN {columnName} = {boolString.Replace("#", "0T")} THEN {boolString.Replace("#", "1T")} ELSE {boolString.Replace("#", "0T")} END) {boolString.Replace("#", "0")}";
else
columnName = $"(CASE WHEN {columnName} IS NULL THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "0")}";
}
else if (hasValueAttr)
{
columnName = $"(CASE WHEN {columnName} IS NULL THEN {boolString.Replace("#", "0T")} ELSE {boolString.Replace("#", "1T")} END) {boolString.Replace("#", "1")}";
}
else if (prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?))
columnName = columnName + boolString.Replace("#", "1");
if (dataEncode != null)
columnName = columnName + dataEncodeString.Replace("#", dataEncode.Key + "|" + ((int)dataEncode.KeySize).ToString());
sb.Append(columnName);
return m;
}
else if (m.Expression != null && (m.Expression.NodeType == ExpressionType.MemberAccess))
{
_overridedNodeType = null;
var key = string.Join("", m.ToString().Split('.').Take(m.ToString().Split('.').Length - 1));
var cl = m.Expression.Type;
if (cl.IsInterface)
{
var pr = (m.Expression as MemberExpression).Expression.Type;
var tb = m.Expression.ToString().Split('.').Last();
cl = DeepCloner.GetProperty(pr, tb)?.PropertyType ?? cl;
}
var prop = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.Name == m.Member.Name);
var name = prop.GetPropertyName();
var table = cl.TableName();
var randomTableName = JoinClauses.ContainsKey(key) ? JoinClauses[key].Item1 : RandomKey();
var primaryId = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.ContainAttribute<PrimaryKey>()).GetPropertyName();
var columnName = string.Format("[{0}].[{1}]", randomTableName, name).CleanValidSqlName(DataBaseTypes);
if (columnOnly)
return columnName;
sb.Append(columnName);
if (JoinClauses.ContainsKey(key))
return m;
// Ok lets build inner join
var parentType = (m.Expression as MemberExpression).Expression.Type;
var parentTable = parentType.TableName();
prop = DeepCloner.GetFastDeepClonerProperties(parentType).FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == cl);
var v = "";
if (prop != null)
{
v += string.Format("LEFT JOIN {0} {1} ON [{2}].[{3}] = {4}.[{5}]", table.GetName(DataBaseTypes), randomTableName, randomTableName, primaryId, parentTable.GetName(DataBaseTypes), prop.GetPropertyName()).CleanValidSqlName(DataBaseTypes);
}
else
{
prop = DeepCloner.GetFastDeepClonerProperties(cl).FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == parentType);
if (prop != null)
v += string.Format("LEFT JOIN {0} {1} ON [{2}].[{3}] = {4}.[{5}]", table.GetName(DataBaseTypes), randomTableName, randomTableName, prop.GetPropertyName(), parentTable.GetName(DataBaseTypes), primaryId).CleanValidSqlName(DataBaseTypes);
}
if (string.IsNullOrEmpty(v))
{
sb = sb.Remove(sb.Length - columnName.Length, columnName.Length);
CleanDecoder(ValuetoSql(GetValue(m)));
}
else
{
JoinClauses.TryAdd(key, new Tuple<string, string>(randomTableName, v));
}
return m;
}
else if (m.Expression != null && _overridedNodeType == ExpressionType.MemberAccess)
{
_overridedNodeType = null;
var key = string.Join("", m.ToString().Split('.').Take(m.ToString().Split('.').Length - 1));
var cl = m.Expression.Type;
if (cl.IsInterface)
{
var pr = (m.Expression as MemberExpression).Expression.Type.GetActualType();
var tb = m.Expression.ToString().Split('.').Last();
cl = DeepCloner.GetProperty(pr, tb)?.PropertyType ?? cl;
}
var prop = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.Name == m.Member.Name);
var table = cl.TableName();
var randomTableName = JoinClauses.ContainsKey(key) ? JoinClauses[key].Item1 : RandomKey();
var primaryId = DeepCloner.GetFastDeepClonerProperties(cl).First(x => x.ContainAttribute<PrimaryKey>()).GetPropertyName();
if (JoinClauses.ContainsKey(key))
return m;
// Ok lets build inner join
var parentType = (m as MemberExpression).Type.GetActualType();
var parentTable = parentType.TableName();
prop = DeepCloner.GetFastDeepClonerProperties(parentType).FirstOrDefault(x => x.ContainAttribute<ForeignKey>() && x.GetCustomAttribute<ForeignKey>().Type == cl);
var v = "";
if (prop != null)
{
v += string.Format("INNER JOIN {0} {1} ON {2}.[{3}] = [{4}].[{5}]", parentTable.GetName(DataBaseTypes), randomTableName, table.GetName(DataBaseTypes), primaryId, randomTableName, prop.GetPropertyName()).CleanValidSqlName(DataBaseTypes);
}
else
{
throw new EnreplacedyException(string.Format("Expression STRUCTURE IS NOT SUPPORTED MEMBER{0} for EnreplacedyWorker", m.Member.Name));
}
if (!string.IsNullOrEmpty(v))
JoinClauses.TryAdd(key, new Tuple<string, string>(randomTableName, v));
return m;
}
}
catch
{
throw new EnreplacedyException(string.Format("Expression '{0}' is not supported", m.ToString()));
}
if (m.Type.IsInternalType() && m.Expression.NodeType == ExpressionType.Call)
{
CleanDecoder(ValuetoSql(Expression.Lambda(m).Compile().DynamicInvoke()));
return m;
}
throw new EnreplacedyException(string.Format("The member '{0}' is not supported", m.Member.Name));
}
19
View Source File : TestWriter.cs
License : MIT License
Project Creator : AlexGhiondea
License : MIT License
Project Creator : AlexGhiondea
public string ToTestCode()
{
StringBuilder code = new StringBuilder();
code.AppendLine("Validate(");
foreach (var item in Segments)
{
code.AppendLine($"{item.ToTestCode()}, ");
}
code = code.Remove(code.Length - 4, 2); //remove the last ", "
code.AppendLine(");");
return code.ToString();
}
19
View Source File : CSharpLanguage.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
public override string GetFieldModifierString(FieldModifier modifier, bool forCode)
{
if (modifier == FieldModifier.None) {
if (forCode)
return "";
else
return "None";
}
StringBuilder builder = new StringBuilder(30);
if ((modifier & FieldModifier.Hider) != 0)
builder.Append(forCode ? "new " : "New, ");
if ((modifier & FieldModifier.Constant) != 0)
builder.Append(forCode ? "const " : "Const, ");
if ((modifier & FieldModifier.Static) != 0)
builder.Append(forCode ? "static " : "Static, ");
if ((modifier & FieldModifier.Readonly) != 0)
builder.Append(forCode ? "readonly " : "Readonly, ");
if ((modifier & FieldModifier.Volatile) != 0)
builder.Append(forCode ? "volatile " : "Volatile, ");
if (forCode)
builder.Remove(builder.Length - 1, 1);
else
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
19
View Source File : CSharpLanguage.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
public override string GetOperationModifierString(OperationModifier modifier, bool forCode)
{
if (modifier == OperationModifier.None) {
if (forCode)
return "";
else
return "None";
}
StringBuilder builder = new StringBuilder(30);
if ((modifier & OperationModifier.Hider) != 0)
builder.Append(forCode ? "new " : "New, ");
if ((modifier & OperationModifier.Static) != 0)
builder.Append(forCode ? "static " : "Static, ");
if ((modifier & OperationModifier.Virtual) != 0)
builder.Append(forCode ? "virtual " : "Virtual, ");
if ((modifier & OperationModifier.Abstract) != 0)
builder.Append(forCode ? "abstract " : "Abstract, ");
if ((modifier & OperationModifier.Sealed) != 0)
builder.Append(forCode ? "sealed " : "Sealed, ");
if ((modifier & OperationModifier.Override) != 0)
builder.Append(forCode ? "override " : "Override, ");
if (forCode)
builder.Remove(builder.Length - 1, 1);
else
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
19
View Source File : JavaLanguage.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
public override string GetFieldModifierString(FieldModifier modifier, bool forCode)
{
if (modifier == FieldModifier.None) {
if (forCode)
return "";
else
return "None";
}
StringBuilder builder = new StringBuilder(20);
if ((modifier & FieldModifier.Static) != 0)
builder.Append(forCode ? "static " : "Static, ");
if ((modifier & FieldModifier.Readonly) != 0)
builder.Append(forCode ? "readonly " : "Readonly, ");
if ((modifier & FieldModifier.Volatile) != 0)
builder.Append(forCode ? "volatile " : "Volatile, ");
if (forCode)
builder.Remove(builder.Length - 1, 1);
else
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
19
View Source File : JavaLanguage.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
public override string GetOperationModifierString(OperationModifier modifier, bool forCode)
{
if (modifier == OperationModifier.None) {
if (forCode)
return "";
else
return "None";
}
StringBuilder builder = new StringBuilder(20);
if ((modifier & OperationModifier.Static) != 0)
builder.Append(forCode ? "static " : "Static, ");
if ((modifier & OperationModifier.Sealed) != 0)
builder.Append(forCode ? "final " : "Final, ");
if ((modifier & OperationModifier.Abstract) != 0)
builder.Append(forCode ? "abstract " : "Abstract, ");
if (forCode)
builder.Remove(builder.Length - 1, 1);
else
builder.Remove(builder.Length - 2, 2);
return builder.ToString();
}
19
View Source File : StringFormatter.cs
License : MIT License
Project Creator : alexis-
License : MIT License
Project Creator : alexis-
public static string WordWrap(string str, int width, WordWrappingMethod method)
{
if (str == null)
return "";
if (width <= 0)
throw new ArgumentOutOfRangeException("width");
if (method == WordWrappingMethod.Optimal)
return new OptimalWordWrappedString(str, width).ToString();
// Simple word wrapping method that simply fills lines as
// much as possible and then breaks. Creates a not so nice
// layout.
StringBuilder dest = new StringBuilder(str.Length);
StringBuilder word = new StringBuilder();
int spaceLeft = width;
using (StringReader reader = new StringReader(str))
{
int ch;
do
{
while ((ch = reader.Read()) != -1 && ch != ' ')
{
word.Append((char)ch);
if (ch == '\n')
spaceLeft = width;
}
if (word.Length > spaceLeft)
{
while (word.Length > width)
{
dest.Append('\n');
dest.Append(word.ToString(0, width));
word.Remove(0, width);
spaceLeft = width;
}
dest.Append('\n');
dest.Append(word);
spaceLeft = width - word.Length;
word.Length = 0;
}
else
{
dest.Append(word);
spaceLeft -= word.Length;
word.Length = 0;
}
if (ch != -1 && spaceLeft > 0)
{
dest.Append(' ');
spaceLeft--;
}
}
while (ch != -1);
}
return dest.ToString();
}
19
View Source File : Util.cs
License : Apache License 2.0
Project Creator : AlexWan
License : Apache License 2.0
Project Creator : AlexWan
public static uint CalculateChecksum(IEnumerable<JToken> bids, IEnumerable<JToken> asks)
{
var bidOrdersCount = 0;
var askOrdersCount = 0;
var stringBuilder = new StringBuilder();
var bidsEnumerator = bids.GetEnumerator();
var asksEnumerator = asks.GetEnumerator();
bool bidsFinished = false;
bool asksFinished = false;
while((bidOrdersCount < orderCountLimit && askOrdersCount < orderCountLimit) ||
(bidsFinished && asksFinished))
{
if (bidsEnumerator.MoveNext())
{
var bidPrice = bidsEnumerator.Current[0].Value<decimal>();
var bidSize = bidsEnumerator.Current[1].Value<decimal>();
stringBuilder.AppendFormat(
"{0}:{1}:",
bidPrice.ToString("f1",CultureInfo.InvariantCulture),
bidSize.ToString(CultureInfo.InvariantCulture));
bidOrdersCount++;
}
else
{
bidsFinished = true;
}
if (asksEnumerator.MoveNext())
{
var askPrice = asksEnumerator.Current[0].Value<decimal>();
var askSize = asksEnumerator.Current[1].Value<decimal>();
stringBuilder.AppendFormat(
"{0}:{1}:",
askPrice.ToString("f1",CultureInfo.InvariantCulture),
askSize.ToString(CultureInfo.InvariantCulture));
askOrdersCount++;
}
else
{
asksFinished = true;
}
}
stringBuilder.Remove(stringBuilder.Length - 1, 1);
var resultString = stringBuilder.ToString();
byte[] bytes = new byte[resultString.Length * sizeof(char)];
System.Buffer.BlockCopy(resultString.ToCharArray(), 0, bytes, 0, bytes.Length);
var result = Crc32(resultString);
return result;
}
19
View Source File : GeneralObject.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public override string ToString()
{
var s = new StringBuilder();
var properties = GetType().GetProperties();
foreach (var p in properties)
{
// TODO: Optimize this replaced
var mappableAttribute = (ObjectStringMappableAttribute)p.GetCustomAttributes(typeof(ObjectStringMappableAttribute), false).FirstOrDefault();
int? key = mappableAttribute?.Key;
object defaultValue = mappableAttribute?.DefaultValue;
object value = p.GetValue(this);
if (key != null && key > 0 && value != defaultValue)
s.Append($"{key},{GetAppropriateStringRepresentation(p.GetValue(this))},");
}
s.Remove(s.Length - 1, 1); // Remove last comma
return s.ToString();
}
19
View Source File : StringBuilderExtensions.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public static StringBuilder Remove(this StringBuilder s, int startingIndex) => s.Remove(startingIndex, s.Length - startingIndex);
19
View Source File : StringBuilderExtensions.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public static StringBuilder RemoveLast(this StringBuilder s, int characterCount) => s.Remove(s.Length - characterCount, characterCount);
19
View Source File : StringExtensions.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
public static string Combine(this string[] s, string separator)
{
if (s.Length == 0)
return "";
var str = new StringBuilder();
for (int i = 0; i < s.Length; i++)
str = str.Append(s[i] + separator);
str = str.Remove(str.Length - separator.Length, separator.Length);
return str.ToString();
}
19
View Source File : LevelObjectFactory.cs
License : MIT License
Project Creator : AlFasGD
License : MIT License
Project Creator : AlFasGD
protected virtual string GetValidObjectIDs()
{
var s = new StringBuilder();
for (int i = 0; i < ObjectIDs.Length; i++)
s.Append($"{ObjectIDs[i]}, ");
s.Remove(s.Length - 2, 2);
return s.ToString();
}
19
View Source File : DefaultAopClient.cs
License : Apache License 2.0
Project Creator : alipay
License : Apache License 2.0
Project Creator : alipay
public static string CreateLinkStringUrlencode(Dictionary<string, string> dicArray, Encoding code)
{
StringBuilder prestr = new StringBuilder();
foreach (KeyValuePair<string, string> temp in dicArray)
{
prestr.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value, code) + "&");
}
//去掉最後一個&字符
int nLen = prestr.Length;
prestr.Remove(nLen - 1, 1);
return prestr.ToString();
}
19
View Source File : CreateDeviceClientMethod.cs
License : MIT License
Project Creator : alonf
License : MIT License
Project Creator : alonf
private void CreateDeviceClientMethod(string methodName, AttributeSyntax attributeSyntax)
{
AppendLine($"private Microsoft.Azure.Devices.Client.DeviceClient {methodName}()");
using (Block())
{
var parameterNameList = new List<string>();
if (attributeSyntax?.ArgumentList != null)
{
AppendLine();
AppendLine("#pragma warning disable CS4014");
AppendLine();
foreach (var argument in attributeSyntax.ArgumentList.Arguments)
{
var attreplacedignment = $"the{argument.NameEquals}";
parameterNameList.Add(argument.NameEquals?.ToString().TrimEnd('=', ' ', '\t').Trim());
var attExpression = argument.Expression.ToString();
CreateVariablereplacedignmentLineFromAttributeParameter(attreplacedignment, attExpression);
}
AppendLine();
AppendLine("#pragma warning restore CS4014");
AppendLine();
}
else
{
parameterNameList.Add(nameof(DeviceAttribute.ConnectionString));
AppendLine("var theConnectionString=System.Environment.GetEnvironmentVariable(\"ConnectionString\");");
}
var createDeviceError = new StringBuilder();
string clientOptionsPropertyName = GetClientOptionsPropertyName();
var hasTransportSettingsAttributes = HandleTransportSettingsAttributes();
string authenticationMethodPropertyName = GetAuthenticationMethodPropertyName();
var creationFunctionEntry = new StringBuilder();
if (parameterNameList.Contains(nameof(DeviceAttribute.ConnectionString)))
{
createDeviceError.Append("ConnectionString ");
creationFunctionEntry.Append("cs_");
}
if (parameterNameList.Contains(nameof(DeviceAttribute.Hostname)))
{
createDeviceError.Append("Hostname ");
creationFunctionEntry.Append("hn_");
}
if (parameterNameList.Contains(nameof(DeviceAttribute.GatewayHostname)))
{
createDeviceError.Append("GatewayHostname ");
creationFunctionEntry.Append("gw_");
}
if (parameterNameList.Contains(nameof(DeviceAttribute.TransportType)))
{
createDeviceError.Append("TransportType ");
creationFunctionEntry.Append("tt_");
}
if (parameterNameList.Contains(nameof(DeviceAttribute.DeviceId)))
{
createDeviceError.Append("DeviceId ");
creationFunctionEntry.Append("did_");
}
if (hasTransportSettingsAttributes)
{
createDeviceError.Append("ITransportSettings[] ");
creationFunctionEntry.Append("ts_");
}
if (authenticationMethodPropertyName is not null)
{
createDeviceError.Append("AuthenticationMethod ");
creationFunctionEntry.Append("am_");
}
if (clientOptionsPropertyName is not null)
{
createDeviceError.Append("ClientOptions ");
creationFunctionEntry.Append("co_");
}
if (creationFunctionEntry.Length == 0) //no parameters
{
Location location = null;
if (attributeSyntax != null)
{
location = Location.Create(attributeSyntax.SyntaxTree, attributeSyntax.Span);
}
_diagnosticsManager.Report(DiagnosticId.DeviceParametersError, location);
return;
}
Append("var deviceClient = ");
creationFunctionEntry.Remove(creationFunctionEntry.Length - 1, 1); //remove the last _
//for debug:
//AppendLine($"//{creationFunctionEntry}");
switch (creationFunctionEntry.ToString())
{
case "cs":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)});");
break;
case "cs_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, {clientOptionsPropertyName});");
break;
case "cs_ts":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, transportSettings);");
break;
case "cs_ts_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, transportSettings, {clientOptionsPropertyName});");
break;
case "cs_tt":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.TransportType)});");
break;
case "cs_tt_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.TransportType)}, {clientOptionsPropertyName});");
break;
case "cs_did":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)});");
break;
case "cs_did_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)}, {clientOptionsPropertyName});");
break;
case "cs_tt_did":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)}, the{nameof(DeviceAttribute.TransportType)});");
break;
case "cs_did_ts":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)}, transportSettings);");
break;
case "cs_did_ts_co":
AppendLine(
$"DeviceClient.CreateFromConnectionString(the{nameof(DeviceAttribute.ConnectionString)}, the{nameof(DeviceAttribute.DeviceId)}, transportSettings, {clientOptionsPropertyName});");
break;
case "hn_gw_tt_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, the{nameof(DeviceAttribute.TransportType)});");
break;
case "hn_gw_tt_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, the{nameof(DeviceAttribute.TransportType)}, {clientOptionsPropertyName});");
break;
case "hn_gw_ts_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, transportSettings);");
break;
case "hn_gw_ts_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, transportSettings, {clientOptionsPropertyName});");
break;
case "hn_gw_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName});");
break;
case "hn_gw_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, the{nameof(DeviceAttribute.GatewayHostname)}, {authenticationMethodPropertyName}, {clientOptionsPropertyName});");
break;
case "hn_tt_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, the{nameof(DeviceAttribute.TransportType)});");
break;
case "hn_tt_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, the{nameof(DeviceAttribute.TransportType)}, {clientOptionsPropertyName});");
break;
case "hn_ts_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, transportSettings);");
break;
case "hn_ts_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, transportSettings, {clientOptionsPropertyName});");
break;
case "hn_am":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName});");
break;
case "hn_am_co":
AppendLine(
$"DeviceClient.Create(the{nameof(DeviceAttribute.Hostname)}, {authenticationMethodPropertyName}, {clientOptionsPropertyName});");
break;
default:
Location location = null;
if (attributeSyntax != null)
{
location = Location.Create(attributeSyntax.SyntaxTree, attributeSyntax.Span);
}
_diagnosticsManager.Report(DiagnosticId.ParametersMismatch, location, createDeviceError.ToString());
AppendLine(" null;");
break;
}
AppendLine("return deviceClient;");
}
}
19
View Source File : TextGenerator.cs
License : MIT License
Project Creator : alonf
License : MIT License
Project Creator : alonf
public void TrimEnd(int n = 1)
{
_sb.Remove(_sb.Length - n, n);
}
19
View Source File : ProcessedReceivedData.cs
License : GNU General Public License v3.0
Project Creator : alvaroyurrita
License : GNU General Public License v3.0
Project Creator : alvaroyurrita
public void _ComPort_SerialDataReceived(ComPort ReceivingComPort, ComPortSerialDataEventArgs args)
{
ReceiveDataBuffer.Append(args.SerialData);
if (rx_Changed != null) rx_Changed(args.SerialData);
CriticalProcessingReceivedData.Enter();
try
{
string delimiter = _delimiter.ToString();
string CompareBuffer = ReceiveDataBuffer.ToString();
foreach (var cmd in PresetStrings)
{
if (CompareBuffer.EndsWith(cmd.Command + delimiter))
{
if (!cmd.Active)
{
if (PresetStringReceived != null)
{
cmd.Active = true;
PresetStringReceived(cmd, cmd.Active);
}
}
}
else
{
if (cmd.Active)
{
if (PresetStringReceived != null)
{
cmd.Active = false;
PresetStringReceived(cmd, cmd.Active);
}
}
}
}
if (ReceiveDataBuffer.Length > 400) ReceiveDataBuffer.Remove(0, 256);
}
catch (Exception e)
{
ErrorLog.Error("Error Processsing Data Received - {0}", e.Message);
}
CriticalProcessingReceivedData.Leave();
}
19
View Source File : DeepL_Website.cs
License : GNU General Public License v3.0
Project Creator : AndrasMumm
License : GNU General Public License v3.0
Project Creator : AndrasMumm
public async Task ForceTranslate()
{
double spanDiff = MaxDelaySeconds - MinDelaySeconds;
double waitIntervalMs = MaxDelaySeconds + (RandomNumbers.NextDouble() * spanDiff) * 1000;
double timeWeNeedToWait = waitIntervalMs - DateTime.Now.Subtract(_LastTimeTranslated).Milliseconds;
if (timeWeNeedToWait > 0)
{
Thread.Sleep((int)Math.Floor(timeWeNeedToWait));
}
try
{
await _Sem.WaitAsync();
RequestListManipMutex.WaitOne();
_CurrentlyTranslating = _Requests;
_Requests = new List<TranslationRequest>();
RequestListManipMutex.ReleaseMutex();
await EnsureSetupState();
_TranslationCount++;
_ID++;
// construct json content
long r = (long)(DateTime.UtcNow - Epoch).TotalMilliseconds;
long n = 1;
var builder = new StringBuilder();
builder.Append("{\"jsonrpc\":\"2.0\",\"method\": \"LMT_handle_jobs\",\"params\":{\"jobs\":[");
List<UntranslatedTextInfo> untranslatedTextInfos = new List<UntranslatedTextInfo>();
foreach (var translationRequest in _CurrentlyTranslating)
{
List<TranslationPart> parts = NewlineSplitter
.Split(translationRequest.Text)
.Select(x => new TranslationPart { Value = x, IsTranslatable = !NewlineSplitter.IsMatch(x) })
.ToList();
var usableParts = parts
.Where(x => x.IsTranslatable)
.Select(x => x.Value)
.ToArray();
for (int i = 0; i < usableParts.Length; i++)
{
var usablePart = usableParts[i];
builder.Append("{\"kind\":\"default\",\"preferred_num_beams\":1,\"raw_en_sentence\":\""); // yes.. "en" no matter what source language is used
builder.Append(JsonHelper.Escape(usablePart));
var addedContext = new HashSet<string>();
builder.Append("\",\"raw_en_context_before\":[");
bool addedAnyBefore = false;
foreach (var contextBefore in translationRequest.PreContext)
{
if (!addedContext.Contains(contextBefore))
{
builder.Append("\"");
builder.Append(JsonHelper.Escape(contextBefore));
builder.Append("\"");
builder.Append(",");
addedAnyBefore = true;
}
}
for (int j = 0; j < i; j++)
{
if (!addedContext.Contains(usableParts[j]))
{
builder.Append("\"");
builder.Append(JsonHelper.Escape(usableParts[j]));
builder.Append("\"");
builder.Append(",");
addedAnyBefore = true;
}
}
if (addedAnyBefore)
{
builder.Remove(builder.Length - 1, 1);
}
builder.Append("],\"raw_en_context_after\":[");
bool addedAnyAfter = false;
for (int j = i + 1; j < usableParts.Length; j++)
{
if (!addedContext.Contains(usableParts[j]))
{
builder.Append("\"");
builder.Append(JsonHelper.Escape(usableParts[j]));
builder.Append("\"");
builder.Append(",");
addedAnyAfter = true;
}
}
foreach (var contextAfter in translationRequest.PostContext)
{
if (!addedContext.Contains(contextAfter))
{
builder.Append("\"");
builder.Append(JsonHelper.Escape(contextAfter));
builder.Append("\"");
builder.Append(",");
addedAnyAfter = true;
}
}
if (addedAnyAfter)
{
builder.Remove(builder.Length - 1, 1);
}
//builder.Append("],\"quality\":\"fast\"},");
builder.Append("]},");
n += usablePart.Count(c => c == 'i');
}
untranslatedTextInfos.Add(new UntranslatedTextInfo { TranslationParts = parts, UntranslatedText = translationRequest.Text });
}
builder.Remove(builder.Length - 1, 1); // remove final ","
var timestamp = r + (n - r % n);
builder.Append("],\"lang\":{\"user_preferred_langs\":[\"");
builder.Append("en".ToUpperInvariant());
builder.Append("\",\"");
builder.Append("zh".ToUpperInvariant());
builder.Append("\"],\"source_lang_user_selected\":\"");
builder.Append("zh".ToUpperInvariant());
builder.Append("\",\"target_lang\":\"");
builder.Append("en".ToUpperInvariant());
builder.Append("\"},\"priority\":1,\"commonJobParams\":{\"formality\":null},\"timestamp\":");
builder.Append(timestamp.ToString(CultureInfo.InvariantCulture));
builder.Append("},\"id\":");
builder.Append(_ID);
builder.Append("}");
var content = builder.ToString();
var stringContent = new StringContent(content);
using var request = new HttpRequestMessage(HttpMethod.Post, HttpsServicePointTemplateUrl);
AddHeaders(request, stringContent, RequestType.Translation);
request.Content = stringContent;
// create request
using var response = await _Client.SendAsync(request);
response.ThrowIfBlocked();
response.EnsureSuccessStatusCode();
var str = await response.Content.ReadreplacedtringAsync();
ExtractTranslation(str, untranslatedTextInfos);
_LastTimeTranslated = DateTime.Now;
}
catch (BlockedException)
{
Reset();
throw;
}
finally
{
_Sem.Release();
}
}
19
View Source File : JsonHelper.cs
License : GNU General Public License v3.0
Project Creator : AndrasMumm
License : GNU General Public License v3.0
Project Creator : AndrasMumm
public static string Unescape(string str)
{
if (str == null) return null;
var builder = new StringBuilder(str);
bool escapeNext = false;
for (int i = 0; i < builder.Length; i++)
{
var c = builder[i];
if (escapeNext)
{
bool found = true;
char escapeWith = default(char);
switch (c)
{
case 'b':
escapeWith = '\b';
break;
case 'f':
escapeWith = '\f';
break;
case 'n':
escapeWith = '\n';
break;
case 'r':
escapeWith = '\r';
break;
case 't':
escapeWith = '\t';
break;
case '"':
escapeWith = '\"';
break;
case '\\':
escapeWith = '\\';
break;
case 'u':
escapeWith = 'u';
break;
default:
found = false;
break;
}
// remove previous char and go one back
if (found)
{
if (escapeWith == 'u')
{
// unicode crap, lets handle the next 4 characters manually
int code = int.Parse(new string(new char[] { builder[i + 1], builder[i + 2], builder[i + 3], builder[i + 4] }), NumberStyles.HexNumber);
var replacingChar = (char)code;
builder.Remove(--i, 6);
builder.Insert(i, replacingChar);
}
else
{
// found proper escaping
builder.Remove(--i, 2);
builder.Insert(i, escapeWith);
}
}
escapeNext = false;
}
else if (c == '\\')
{
escapeNext = true;
}
}
return builder.ToString();
}
See More Examples