Here are the examples of the csharp api System.Text.StringBuilder.Clear() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1589 Examples
19
View Source File : HealthMonitor.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private string RebuildArgList(string argList, string extras)
{
if (string.IsNullOrEmpty(extras))
return argList;
StringBuilder sb = new StringBuilder();
string s;
Dictionary<string, string> eArgs = Helper.ParseOptions(argList);
Dictionary<string, string> extraDict = Helper.ParseOptions(extras);
foreach (var key in extraDict.Keys)
{
if (eArgs.ContainsKey(key))
{
eArgs[key] = extraDict[key];
}
else
{
eArgs.Add(key, extraDict[key]);
}
}
extraDict.Clear();
extraDict = null;
foreach (var key in eArgs.Keys)
{
sb.AppendFormat("{0} {1} ", key, eArgs[key]);
}
s = sb.ToString().TrimEnd();
eArgs.Clear();
eArgs = null;
sb.Clear();
sb = null;
return s;
}
19
View Source File : IndexAndSearchHandler.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private string NormalizeTerm(string s)
{
StringBuilder sb = new StringBuilder();
foreach (var c in s)
{
if (char.IsLetterOrDigit(c) || c == ' ')
sb.Append(char.ToLower(c));
else if (char.IsSeparator(c))
sb.Append(' ');
}
s = sb.ToString();
sb.Clear();
sb = null;
return s;
}
19
View Source File : SozlukRequestHandlerBase.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public void CompleteRequest()
{
this.req.Complete();
this.req = null;
this.respData.Clear();
this.respData = null;
}
19
View Source File : Entry.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public string GetTransportString()
{
StringBuilder sb = new StringBuilder();
string s;
if (RepCount > 1)
sb.Append(MakeTag("Baslik", this.Baslik, "RepCount", RepCount));
else
sb.Append(MakeTag("Baslik", this.Baslik));
sb.Append(MakeTag("Suser", Suser));
sb.Append(MakeTag("Date", Date));
sb.Append(MakeTag("Desc", Content));
s = sb.ToString();
sb.Clear();
sb = null;
return s;
}
19
View Source File : Helper.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private static string HashWith(HashAlgorithm algo,string v)
{
string hash;
StringBuilder sb = new StringBuilder();
byte[] bytes = Encoding.ASCII.GetBytes(v);
bytes = algo.ComputeHash(bytes);
algo.Dispose();
for (int i = 0; i < bytes.Length; i++)
sb.Append(bytes[i].ToString("X2"));
hash = sb.ToString();
sb.Clear();
sb = null;
return hash;
}
19
View Source File : InternalTalk.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public void SendTalkData(Dictionary<string, string> data)
{
StringBuilder sb = new StringBuilder();
foreach (var key in data.Keys)
{
sb.AppendFormat("{0}={1};", key, data[key]);
}
SendPacket(sb.ToString());
sb.Clear();
sb = null;
}
19
View Source File : Edi.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
private static void GenSessionId()
{
StringBuilder sb = new StringBuilder();
string hx = "abcdefgh0123456789";
Random rnd = new Random();
for (int i=0;i<16;i++)
{
sb.Append(hx[rnd.Next(hx.Length)]);
}
sessionId = sb.ToString();
sb.Clear();
sb = null;
}
19
View Source File : SozlukDataStore.cs
License : MIT License
Project Creator : 0ffffffffh
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 : CelesteNetPlayerListComponent.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void RebuildList() {
if (MDraw.DefaultFont == null || Client == null || Channels == null)
return;
DataPlayerInfo[] all = Client.Data.GetRefs<DataPlayerInfo>();
List<Blob> list = new() {
new Blob {
Text = $"{all.Length} player{(all.Length == 1 ? "" : "s")}",
Color = ColorCountHeader
}
};
StringBuilder builder = new();
switch (Mode) {
case ListMode.Clreplacedic:
foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
if (string.IsNullOrWhiteSpace(player.DisplayName))
continue;
builder.Append(player.DisplayName);
DataChannelList.Channel channel = Channels.List.FirstOrDefault(c => c.Players.Contains(player.ID));
if (channel != null && !string.IsNullOrEmpty(channel.Name)) {
builder
.Append(" #")
.Append(channel.Name);
}
if (Client.Data.TryGetBoundRef(player, out DataPlayerState state))
AppendState(builder, state);
builder.AppendLine();
}
list.Add(new() {
Text = builder.ToString().Trim(),
ScaleFactor = 1f
});
break;
case ListMode.Channels:
HashSet<DataPlayerInfo> listed = new();
DataChannelList.Channel own = Channels.List.FirstOrDefault(c => c.Players.Contains(Client.PlayerInfo.ID));
if (own != null) {
list.Add(new() {
Text = own.Name,
Color = ColorChannelHeaderOwn
});
builder.Clear();
foreach (DataPlayerInfo player in own.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p)))
listed.Add(ListPlayerUnderChannel(builder, player));
list.Add(new() {
Text = builder.ToString().Trim(),
ScaleFactor = 0.5f
});
}
foreach (DataChannelList.Channel channel in Channels.List) {
if (channel == own)
continue;
list.Add(new() {
Text = channel.Name,
Color = ColorChannelHeader
});
builder.Clear();
foreach (DataPlayerInfo player in channel.Players.Select(p => GetPlayerInfo(p)).OrderBy(p => GetOrderKey(p)))
listed.Add(ListPlayerUnderChannel(builder, player));
list.Add(new() {
Text = builder.ToString().Trim(),
ScaleFactor = 1f
});
}
bool wrotePrivate = false;
builder.Clear();
foreach (DataPlayerInfo player in all.OrderBy(p => GetOrderKey(p))) {
if (listed.Contains(player) || string.IsNullOrWhiteSpace(player.DisplayName))
continue;
if (!wrotePrivate) {
wrotePrivate = true;
list.Add(new() {
Text = "!<private>",
Color = ColorChannelHeaderPrivate
});
}
builder.AppendLine(player.DisplayName);
}
if (wrotePrivate) {
list.Add(new() {
Text = builder.ToString().Trim(),
ScaleFactor = 1f
});
}
break;
}
List = list;
}
19
View Source File : QueryableSqlBuilderTests.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
[Fact]
public void ResolveSelectForEnreplacedyAndExcludeColumnsTest()
{
//排除单个列
var builder = CreateBuilder();
var sb = new StringBuilder();
Expression<Func<ArticleEnreplacedy, string>> exp = m => m.Content;
builder.QueryBody.SetSelectExclude(exp);
var columns = builder.ResolveSelectExcludeColumns();
builder.ResolveSelectForEnreplacedy(sb, 0, columns);
var sql = sb.ToString();
replacedert.Equal("[Id] AS [Id],[CategoryId] AS [CategoryId],[replacedle] AS [replacedle],[IsPublished] AS [Published],[PublishedTime] AS [PublishedTime],[Price] AS [Price],[Deleted] AS [Deleted],[DeletedBy] AS [DeletedBy],[Deleter] AS [Deleter],[DeletedTime] AS [DeletedTime],[CreatedBy] AS [CreatedBy],[Creator] AS [Creator],[CreatedTime] AS [CreatedTime],[ModifiedBy] AS [ModifiedBy],[Modifier] AS [Modifier],[ModifiedTime] AS [ModifiedTime],", sql);
//排除多个列
sb.Clear();
Expression<Func<ArticleEnreplacedy, dynamic>> exp1 = m => new { m.CategoryId, m.Content };
builder.QueryBody.SetSelectExclude(exp1);
columns = builder.ResolveSelectExcludeColumns();
builder.ResolveSelectForEnreplacedy(sb, 0, columns);
sql = sb.ToString();
replacedert.Equal("[Id] AS [Id],[replacedle] AS [replacedle],[IsPublished] AS [Published],[PublishedTime] AS [PublishedTime],[Price] AS [Price],[Deleted] AS [Deleted],[DeletedBy] AS [DeletedBy],[Deleter] AS [Deleter],[DeletedTime] AS [DeletedTime],[CreatedBy] AS [CreatedBy],[Creator] AS [Creator],[CreatedTime] AS [CreatedTime],[ModifiedBy] AS [ModifiedBy],[Modifier] AS [Modifier],[ModifiedTime] AS [ModifiedTime],", sql);
}
19
View Source File : QueryableSqlBuilderTests.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
[Fact]
public void ResolveSelectForEnreplacedyAndExcludeColumnsTest()
{
//排除单个列
var builder = CreateBuilder();
var sb = new StringBuilder();
Expression<Func<ArticleEnreplacedy, string>> exp = m => m.Content;
builder.QueryBody.SetSelectExclude(exp);
var columns = builder.ResolveSelectExcludeColumns();
builder.ResolveSelectForEnreplacedy(sb, 0, columns);
var sql = sb.ToString();
replacedert.Equal("`Id` AS `Id`,`CategoryId` AS `CategoryId`,`replacedle` AS `replacedle`,`IsPublished` AS `Published`,`PublishedTime` AS `PublishedTime`,`Price` AS `Price`,`Deleted` AS `Deleted`,`DeletedBy` AS `DeletedBy`,`Deleter` AS `Deleter`,`DeletedTime` AS `DeletedTime`,`CreatedBy` AS `CreatedBy`,`Creator` AS `Creator`,`CreatedTime` AS `CreatedTime`,`ModifiedBy` AS `ModifiedBy`,`Modifier` AS `Modifier`,`ModifiedTime` AS `ModifiedTime`,", sql);
//排除多个列
sb.Clear();
Expression<Func<ArticleEnreplacedy, dynamic>> exp1 = m => new { m.CategoryId, m.Content };
builder.QueryBody.SetSelectExclude(exp1);
columns = builder.ResolveSelectExcludeColumns();
builder.ResolveSelectForEnreplacedy(sb, 0, columns);
sql = sb.ToString();
replacedert.Equal("`Id` AS `Id`,`replacedle` AS `replacedle`,`IsPublished` AS `Published`,`PublishedTime` AS `PublishedTime`,`Price` AS `Price`,`Deleted` AS `Deleted`,`DeletedBy` AS `DeletedBy`,`Deleter` AS `Deleter`,`DeletedTime` AS `DeletedTime`,`CreatedBy` AS `CreatedBy`,`Creator` AS `Creator`,`CreatedTime` AS `CreatedTime`,`ModifiedBy` AS `ModifiedBy`,`Modifier` AS `Modifier`,`ModifiedTime` AS `ModifiedTime`,", sql);
}
19
View Source File : RedisClientEvents.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void After(InterceptorAfterEventArgs args)
{
string log;
if (args.Exception != null) log = $"{args.Exception.Message}";
else if (args.Value is Array array)
{
var sb = new StringBuilder().Append("[");
var itemindex = 0;
foreach (var item in array)
{
if (itemindex++ > 0) sb.Append(", ");
sb.Append(item.ToInvariantCultureToString());
}
log = sb.Append("]").ToString();
sb.Clear();
}
else
log = $"{args.Value.ToInvariantCultureToString()}";
_cli.OnNotice(null, new NoticeEventArgs(
NoticeType.Call,
args.Exception,
$"{(args.Command.WriteTarget ?? "Not connected").PadRight(21)} > {args.Command}\r\n{log}\r\n({args.ElapsedMilliseconds}ms)\r\n",
args.Value));
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static void Main(string[] args) {
fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
//sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
//sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements
//测试前清空数据
fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
fsql.Ado.ExecuteNonQuery("delete from efcore_song");
var sql = fsql.Select<Song>().Where(a => a.Id == int.Parse("55")).ToSql();
var sb = new StringBuilder();
Console.WriteLine("插入性能:");
//Insert(sb, 1000, 1);
//Console.Write(sb.ToString());
//sb.Clear();
//Insert(sb, 1000, 10);
//Console.Write(sb.ToString());
//sb.Clear();
Insert(sb, 1, 1000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 10000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 50000);
Console.Write(sb.ToString());
sb.Clear();
Insert(sb, 1, 100000);
Console.Write(sb.ToString());
sb.Clear();
Console.WriteLine("查询性能:");
Select(sb, 1000, 1);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1000, 10);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 1000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 10000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 50000);
Console.Write(sb.ToString());
sb.Clear();
Select(sb, 1, 100000);
Console.Write(sb.ToString());
sb.Clear();
Console.WriteLine("更新:");
Update(sb, 1000, 1);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1000, 10);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 1000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 10000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 50000);
Console.Write(sb.ToString());
sb.Clear();
Update(sb, 1, 100000);
Console.Write(sb.ToString());
sb.Clear();
Console.WriteLine("测试结束,按任意键退出...");
Console.ReadKey();
}
19
View Source File : DynamicProxy.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
{
if (type == null) return null;
var typeCSharpName = type.DisplayCsharp();
if (type.IsNotPublic)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
return null;
}
var matchedMemberInfos = new List<MemberInfo>();
var matchedAttributes = new List<DynamicProxyAttribute>();
var matchedAttributesFromServices = new List<FieldInfo[]>();
var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
var methodOverrideSb = new StringBuilder();
var sb = methodOverrideSb;
#region Common Code
Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
{
var sbt = new StringBuilder();
for (var a = attrsIndex; a < matchedAttributes.Count; a++)
{
sbt.Append([email protected]"{(proxyMethodName == "Before" ? [email protected]"
var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
__DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
{(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
{(proxyMethodName == "Before" ?
[email protected]"if (__DP_ARG___is_return == false)
{{
__DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? [email protected]"
if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
}}" :
$"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
}
return sbt.ToString();
};
Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
{
var sbt = new StringBuilder();
var taskType = returnType.ReturnTypeWithoutTask();
sbt.Append([email protected]"
{(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
(taskType.IsValueType || taskType.IsGenericParameter ?
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
) :
(returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
return sbt.ToString();
};
Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
{
return [email protected]"
if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? [email protected]"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : [email protected]"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
};
#endregion
#region Methods
var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var method in methods)
{
if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => method));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
if (method.IsVirtual == false || method.IsFinal)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
continue;
}
#if net40
var returnType = method.ReturnType;
var methodIsAsync = false;
#else
var returnType = method.ReturnType.ReturnTypeWithoutTask();
var methodIsAsync = method.ReturnType.IsTask();
//if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
// attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
//{
//}
#endif
var baseInvoke = type.IsInterface == false ? [email protected]"
try
{{
if (__DP_ARG___is_return == false)
{{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
{(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}" : "";
sb.Append([email protected]"
{(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
}}");
}
#endregion
var propertyOverrideSb = new StringBuilder();
sb = propertyOverrideSb;
#region Property
var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
foreach (var prop2 in props)
{
var getMethod = prop2.GetGetMethod(false);
var setMethod = prop2.GetSetMethod(false);
if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
{
if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
continue;
}
}
var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
var prop2AttributeAny = attrs.Any();
var getMethodAttributeAny = prop2AttributeAny;
var setMethodAttributeAny = prop2AttributeAny;
if (attrs.Any() == false && getMethod?.IsVirtual == true)
{
attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
getMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false && setMethod?.IsVirtual == true)
{
attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
setMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => prop2));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();
var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
if (propSetModification == propModification) propSetModification = "";
if (propGetModification == propModification) propGetModification = "";
//if (getMethod.IsAbstract) sb.Append("abstract ");
sb.Append([email protected]"
{propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
{{");
if (getMethod != null)
{
if (getMethodAttributeAny == false) sb.Append([email protected]"
{propGetModification} get
{{
return base.{prop2.Name}
}}");
else sb.Append([email protected]"
{propGetModification} get
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
}}");
}
if (setMethod != null)
{
if (setMethodAttributeAny == false) sb.Append([email protected]"
{propSetModification} set
{{
base.{prop2.Name} = value;
}}");
else sb.Append([email protected]"
{propSetModification} set
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
__DP_ARG___parameters.Add(""value"", value);
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false)
{{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
base.{prop2.Name} = value;
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
}}");
}
sb.Append([email protected]"
}}");
}
#endregion
string proxyCscode = "";
replacedembly proxyreplacedembly = null;
Type proxyType = null;
if (matchedMemberInfos.Any())
{
#region Constructors
sb = new StringBuilder();
var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
sb.Append(string.Join("", fromServicesTypes.Select(serviceType => [email protected]"
private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
foreach (var ctor in ctors)
{
var ctorParams = ctor.GetParameters();
sb.Append([email protected]"
{(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
(ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
string.Join(", ", fromServicesTypes.Select(serviceType => [email protected]"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
: base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
{{{string.Join("", fromServicesTypes.Select(serviceType => [email protected]"
{serviceType.Value} = parameter{serviceType.Value};"))}
}}");
}
for (var a = 0; a < matchedAttributesFromServices.Count; a++)
{
sb.Append([email protected]"
private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
{{{string.Join("", matchedAttributesFromServices[a].Select(fs => [email protected]"
__DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
}}");
}
#endregion
proxyCscode = [email protected]"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public clreplaced {clreplacedName} : {typeCSharpName}
{{
private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));
//这里要注释掉,如果重写的基类没有无参构造函数,会报错
//public {clreplacedName}({_metaName} meta)
//{{
// __DP_Meta = meta;
//}}
{sb.ToString()}
{methodOverrideSb.ToString()}
{propertyOverrideSb.ToString()}
}}";
proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
}
methodOverrideSb.Clear();
propertyOverrideSb.Clear();
sb.Clear();
return new DynamicProxyMeta(
type, ctors,
matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
}
19
View Source File : EventSourceReader.cs
License : MIT License
Project Creator : 3ventic
License : MIT License
Project Creator : 3ventic
private async Task ReaderAsync()
{
try
{
if (string.Empty != LastEventId)
{
if (Hc.DefaultRequestHeaders.Contains("Last-Event-Id"))
{
Hc.DefaultRequestHeaders.Remove("Last-Event-Id");
}
Hc.DefaultRequestHeaders.TryAddWithoutValidation("Last-Event-Id", LastEventId);
}
using (HttpResponseMessage response = await Hc.GetAsync(Uri, HttpCompletionOption.ResponseHeadersRead))
{
response.EnsureSuccessStatusCode();
if (response.Headers.TryGetValues("content-type", out IEnumerable<string> ctypes) || ctypes?.Contains("text/event-stream") == false)
{
throw new ArgumentException("Specified URI does not return server-sent events");
}
Stream = await response.Content.ReadreplacedtreamAsync();
using (var sr = new StreamReader(Stream))
{
string evt = DefaultEventType;
string id = string.Empty;
var data = new StringBuilder(string.Empty);
while (true)
{
string line = await sr.ReadLineAsync();
if (line == string.Empty)
{
// double newline, dispatch message and reset for next
if (data.Length > 0)
{
MessageReceived?.Invoke(this, new EventSourceMessageEventArgs(data.ToString().Trim(), evt, id));
}
data.Clear();
id = string.Empty;
evt = DefaultEventType;
continue;
}
else if (line.First() == ':')
{
// Ignore comments
continue;
}
int dataIndex = line.IndexOf(':');
string field;
if (dataIndex == -1)
{
dataIndex = line.Length;
field = line;
}
else
{
field = line.Substring(0, dataIndex);
dataIndex += 1;
}
string value = line.Substring(dataIndex).Trim();
switch (field)
{
case "event":
// Set event type
evt = value;
break;
case "data":
// Append a line to data using a single \n as EOL
data.Append($"{value}\n");
break;
case "retry":
// Set reconnect delay for next disconnect
int.TryParse(value, out ReconnectDelay);
break;
case "id":
// Set ID
LastEventId = value;
id = LastEventId;
break;
default:
// Ignore other fields
break;
}
}
}
}
}
catch (Exception ex)
{
Disconnect(ex);
}
}
19
View Source File : NotchSolutionDebugger.cs
License : MIT License
Project Creator : 5argon
License : MIT License
Project Creator : 5argon
void Update()
{
sb.Clear();
ClearRects();
switch (menu)
{
case Menu.Home:
export.gameObject.SetActive(true);
sb.AppendLine($"<b>-- PLEASE ROTATE THE DEVICE TO GET BOTH ORIENTATION'S DETAILS! --</b>\n");
var safeArea = RelativeToReal(NotchSolutionUtility.ShouldUseNotchSimulatorValue ? storedSimulatedSafeAreaRelative : NotchSolutionUtility.ScreenSafeAreaRelative);
PlaceRect(safeArea, Color.red);
if (Screen.orientation != NotchSolutionUtility.GetCurrentOrientation())
safeArea.Set(Screen.width - safeArea.x, Screen.height - safeArea.y, safeArea.width, safeArea.height);
sb.AppendLine($"Safe area : {safeArea}\n");
#if UNITY_2019_2_OR_NEWER
#if UNITY_EDITOR
var relativeCutouts = NotchSolutionUtility.ShouldUseNotchSimulatorValue ? storedSimulatedCutoutsRelative : NotchSolutionUtility.ScreenCutoutsRelative;
List<Rect> rectCutouts = new List<Rect>();
foreach (Rect rect in relativeCutouts) rectCutouts.Add(RelativeToReal(rect));
var cutouts = rectCutouts.ToArray();
#else
var cutouts = Screen.cutouts;
#endif
foreach (Rect r in cutouts) PlaceRect(r, Color.blue);
if (Screen.orientation != NotchSolutionUtility.GetCurrentOrientation())
{
foreach (Rect rect in cutouts) rect.Set(Screen.width - rect.x, Screen.height - rect.y, rect.width, rect.height);
}
sb.AppendLine($"Cutouts : {string.Join(" / ", cutouts.Select(x => x.ToString()))} \n");
#endif
sb.AppendLine($"Current resolution : {Screen.currentResolution}\n");
sb.AppendLine($"All Resolutions : {string.Join(" / ", Screen.resolutions.Select(x => x.ToString()))}\n");
sb.AppendLine($"DPI : {Screen.dpi} WxH : {Screen.width}x{Screen.height} Orientation : {Screen.orientation}\n");
var joinedProps = string.Join(" / ", typeof(SystemInfo).GetProperties(BindingFlags.Public | BindingFlags.Static).Select(x => $"{x.Name} : {x.GetValue(null)}"));
sb.AppendLine(joinedProps);
break;
case Menu.Extracting:
var screen = device.Screens.FirstOrDefault();
export.gameObject.SetActive(false);
if (screen.orientations.Count == 4)
{
string path = Application.persistentDataPath + "/" + device.Meta.friendlyName + ".device.json";
System.IO.File.WriteAllText(path, JsonUtility.ToJson(device));
sb.AppendLine("<b>Done</b>");
sb.AppendLine("");
sb.AppendLine($"File saved at <i>{path}</i>");
StartCoroutine(exportDone());
}
else sb.AppendLine("Extracting...");
break;
}
debugText.text = sb.ToString();
}
19
View Source File : XunitTraceListener.cs
License : Microsoft Public License
Project Creator : AArnott
License : Microsoft Public License
Project Creator : AArnott
public override void WriteLine(string? message)
{
if (!this.disposed)
{
this.lineInProgress.Append(message);
this.logger.WriteLine(this.lineInProgress.ToString());
this.lineInProgress.Clear();
}
}
19
View Source File : CsharpMemberProvider.cs
License : MIT License
Project Creator : Abc-Arbitrage
License : MIT License
Project Creator : Abc-Arbitrage
public IEnumerable<string> GetConstructorParameters(string constructorString)
{
var index = 0;
var openedBracket = 0;
while (constructorString[index] != '(')
index++;
var sb = new StringBuilder();
while (constructorString[index] != ')')
{
index++;
if (constructorString[index] == '<')
openedBracket++;
else if (constructorString[index] == '>')
openedBracket--;
if (openedBracket ==0 && (constructorString[index] == ',' || constructorString[index] == ')'))
{
yield return sb.ToString();
sb.Clear();
}
else
sb.Append(constructorString[index]);
}
}
19
View Source File : BaseMixedRealityProfileInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private static string GetSubProfileDropdownKey(SerializedProperty property)
{
if (property.objectReferenceValue == null)
{
throw new Exception("Can't get sub profile dropdown key for a property that is null.");
}
dropdownKeyBuilder.Clear();
dropdownKeyBuilder.Append("MRTK_SubProfile_ShowDropdown_");
dropdownKeyBuilder.Append(property.name);
dropdownKeyBuilder.Append("_");
dropdownKeyBuilder.Append(property.objectReferenceValue.GetType().Name);
return dropdownKeyBuilder.ToString();
}
19
View Source File : PhoneGenerator.cs
License : MIT License
Project Creator : abock
License : MIT License
Project Creator : abock
public IEnumerable<string> Generate(IEnumerable<string> args)
{
var builder = new StringBuilder();
foreach (var arg in args)
{
foreach (var c in arg)
builder.Append(Translate(c));
builder.Append('#');
yield return builder.ToString();
builder.Clear();
}
}
19
View Source File : QuestSkeletonSerializer.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private string SerializeSkeletalData()
{
var data = ovrSkeletonDataProvider.GetSkeletonPoseData();
stringBuilder.Clear();
if (!data.IsDataValid || !data.IsDataHighConfidence)
{
// Data is invalid or low confidence; we don't want to transmit garbage data to the remote machine
// Hide the renderer.
skinnedMeshRenderer.enabled = false;
stringBuilder.Append("0|");
}
else
{
// Data is valid.
// Show the renderer.
skinnedMeshRenderer.enabled = true;
stringBuilder.Append("1|");
//Set bone transform from SkeletonPoseData
for (var i = 0; i < allBones.Count; ++i)
{
allBones[i].transform.localRotation = data.BoneRotations[i].FromFlippedZQuatf();
stringBuilder.Append(allBones[i].transform.localEulerAngles.x);
stringBuilder.Append("|");
stringBuilder.Append(allBones[i].transform.localEulerAngles.y);
stringBuilder.Append("|");
stringBuilder.Append(allBones[i].transform.localEulerAngles.z);
stringBuilder.Append("|");
}
}
return stringBuilder.ToString();
}
19
View Source File : RecordCast.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator
public void Flush()
{
File.AppendAllText(Filename, Buffer.ToString());
Buffer.Clear();
}
19
View Source File : ExportLog.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public void Clear()
{
errorLog.Clear();
warningLog.Clear();
fullLog.Clear();
}
19
View Source File : SheetCopierManager.cs
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
License : GNU Lesser General Public License v3.0
Project Creator : acnicholas
public void CreateSheets()
{
if (ViewHosts.Count < 1)
{
return;
}
int sheetCount = 0;
int viewCount = 0;
View firstView = null;
summaryText.Clear();
using (var t = new Transaction(doc, "Copy Sheets"))
{
if (t.Start() == TransactionStatus.Started)
{
foreach (SheetCopierViewHost viewHost in ViewHosts)
{
if (viewHost.Type == ViewHostType.Sheet)
{
sheetCount++;
}
if (viewHost.Type == ViewHostType.Model)
{
viewCount++;
}
if (CreateAndPopulateNewSheet(viewHost, summaryText) && sheetCount == 1)
{
firstView = viewHost.Type == ViewHostType.Sheet ? viewHost.DestinationSheet : null;
}
}
if (TransactionStatus.Committed != t.Commit())
{
SCaddinsApp.WindowManager.ShowMessageBox("Copy Sheets Failure", "Transaction could not be committed");
}
else
{
// try to open the first view created
if (firstView != null)
{
var uiapp = new UIApplication(doc.Application);
uiapp.ActiveUIDoreplacedent.ActiveView = firstView;
}
}
}
}
SCaddinsApp.WindowManager.ShowMessageBox("Copy Sheets - Summary", summaryText.ToString());
}
19
View Source File : ReferenceNameBuilder.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
internal String Build()
{
var original = m_name.Length > 0 ? m_name.ToString() : "job";
var attempt = 1;
var suffix = default(String);
while (true)
{
if (attempt == 1)
{
suffix = String.Empty;
}
else if (attempt < 1000)
{
suffix = String.Format(CultureInfo.InvariantCulture, "_{0}", attempt);
}
else
{
throw new InvalidOperationException("Unable to create a unique name");
}
var candidate = original.Substring(0, Math.Min(original.Length, PipelineConstants.MaxNodeNameLength - suffix.Length)) + suffix;
if (m_distinctNames.Add(candidate))
{
m_name.Clear();
return candidate;
}
attempt++;
}
}
19
View Source File : VssHttpUriUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
[EditorBrowsable(EditorBrowsableState.Never)]
public static String ReplaceRouteValues(
String routeTemplate,
Dictionary<String, Object> routeValues,
RouteReplacementOptions routeReplacementOptions)
{
StringBuilder sbResult = new StringBuilder();
StringBuilder sbCurrentPathPart = new StringBuilder();
int paramStart = -1, paramLength = 0;
bool insideParam = false;
HashSet<string> unusedValues = new HashSet<string>(routeValues.Keys, StringComparer.OrdinalIgnoreCase);
Dictionary<string, object> caseIncensitiveRouteValues = new Dictionary<string, object>(routeValues, StringComparer.OrdinalIgnoreCase);
for (int i = 0; i < routeTemplate.Length; i++)
{
char c = routeTemplate[i];
if (insideParam)
{
if (c == '}')
{
insideParam = false;
String paramName = routeTemplate.Substring(paramStart, paramLength);
paramLength = 0;
if (paramName.StartsWith("*"))
{
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.WildcardAsQueryParams))
{
continue;
}
// wildcard route
paramName = paramName.Substring(1);
}
Object paramValue;
if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue))
{
if (paramValue != null)
{
sbCurrentPathPart.Append(paramValue.ToString());
unusedValues.Remove(paramName);
}
}
else if (routeReplacementOptions.HasFlag(RouteReplacementOptions.RequireExplicitRouteParams))
{
throw new ArgumentException("Missing route param " + paramName);
}
}
else
{
paramLength++;
}
}
else
{
if (c == '/')
{
if (sbCurrentPathPart.Length > 0)
{
sbResult.Append('/');
sbResult.Append(sbCurrentPathPart.ToString());
sbCurrentPathPart.Clear();
}
}
else if (c == '{')
{
if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '{')
{
// Escaped '{'
sbCurrentPathPart.Append(c);
i++;
}
else
{
insideParam = true;
paramStart = i + 1;
}
}
else if (c == '}')
{
sbCurrentPathPart.Append(c);
if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '}')
{
// Escaped '}'
i++;
}
}
else
{
sbCurrentPathPart.Append(c);
}
}
}
if (sbCurrentPathPart.Length > 0)
{
sbResult.Append('/');
sbResult.Append(sbCurrentPathPart.ToString());
}
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.EscapeUri))
{
sbResult = new StringBuilder(Uri.EscapeUriString(sbResult.ToString()));
}
if (routeReplacementOptions.HasFlag(RouteReplacementOptions.AppendUnusedAsQueryParams) && unusedValues.Count > 0)
{
bool isFirst = true;
foreach (String paramName in unusedValues)
{
Object paramValue;
if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue) && paramValue != null)
{
sbResult.Append(isFirst ? '?' : '&');
isFirst = false;
sbResult.Append(Uri.EscapeDataString(paramName));
sbResult.Append('=');
sbResult.Append(Uri.EscapeDataString(paramValue.ToString()));
}
}
}
return sbResult.ToString();
}
19
View Source File : FileLogger.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel))
return;
if (formatter == null)
throw new ArgumentNullException(nameof(formatter));
UpdatableState currentState = _state;
DateTimeOffset timestamp = _timestampGetter();
var message = FormatState(state, exception, formatter);
StringBuilder sb = s_stringBuilder;
s_stringBuilder = null;
if (sb == null)
sb = new StringBuilder();
foreach (KeyValuePair<(IFileLogEntryTextBuilder, bool), (ILogFileSettings, LogLevel)[]> fileGroup in currentState.FileGroups)
{
FileLogEntry entry = null;
for (int i = 0, n = fileGroup.Value.Length; i < n; i++)
{
(ILogFileSettings fileSettings, LogLevel minLevel) = fileGroup.Value[i];
if (logLevel < minLevel)
continue;
if (entry == null)
{
(IFileLogEntryTextBuilder textBuilder, bool includeScopes) = fileGroup.Key;
IExternalScopeProvider logScope = includeScopes ? currentState.ScopeProvider : null;
textBuilder.BuildEntryText(sb, CategoryName, logLevel, eventId, message, exception, logScope, timestamp);
if (sb.Length > 0)
{
entry = CreateLogEntry();
entry.Text = sb.ToString();
entry.Timestamp = timestamp;
sb.Clear();
}
else
break;
}
_processor.Enqueue(entry, fileSettings, currentState.Settings);
}
}
if (sb.Capacity > 1024)
sb.Capacity = 1024;
s_stringBuilder = sb;
}
19
View Source File : POParser.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
private bool TryReadPOString(string newLine, out string result)
{
_builder.Clear();
if (!TryReadPOStringPart(newLine))
{
result = null;
return false;
}
do { SeekNextToken(); }
while (_line != null && _line[_columnIndex] == '"' && TryReadPOStringPart(newLine));
result = _builder.ToString();
return true;
}
19
View Source File : POParser.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public POParseResult Parse(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException(nameof(reader));
_reader = reader;
_diagnostics = new DiagnosticCollection();
_catalog = new POCatalog();
_line = null;
_lineIndex = -1;
SeekNextToken();
try
{
if (!TryReadEntry(allowHeaderEntry: true, result: out IPOEntry entry))
return new POParseResult(_catalog, _diagnostics);
var isHeader = CheckHeader(entry);
if (isHeader)
ParseHeader((POSingularEntry)entry);
if (!HasFlags(Flags.ReadHeaderOnly))
{
if (!isHeader)
_catalog.Add(entry);
while (TryReadEntry(allowHeaderEntry: false, result: out entry))
_catalog.Add(entry);
}
return new POParseResult(_catalog, _diagnostics);
}
finally
{
_builder.Clear();
if (_builder.Capacity > 1024)
_builder.Capacity = 1024;
}
}
19
View Source File : POGenerator.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public void Generate(TextWriter writer, POCatalog catalog)
{
if (writer == null)
throw new ArgumentNullException(nameof(writer));
if (catalog == null)
throw new ArgumentNullException(nameof(catalog));
if (!HasFlags(Flags.IgnoreEncoding))
{
if (writer.Encoding.GetByteCount(" ") > 1)
throw new ArgumentException(Resources.EncodingNotSingleByte, nameof(writer));
if (catalog.Encoding == null || Encoding.GetEncoding(catalog.Encoding).WebName != writer.Encoding.WebName)
throw new ArgumentException(Resources.EncodingMismatch, nameof(writer));
}
_writer = writer;
_catalog = catalog;
_stringBreak = "\"" + _writer.NewLine + "\"";
_lineStartIndex = 0;
try
{
WriteEntry(CreateHeaderEntry(), _ => { });
for (int i = 0, n = catalog.Count; i < n; i++)
WriteEntry(catalog[i], w => w.WriteLine());
}
finally
{
_builder.Clear();
if (_builder.Capacity > 1024)
_builder.Capacity = 1024;
}
}
19
View Source File : POGenerator.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
private void ResetBuilder()
{
_builder.Clear();
_lineStartIndex = 0;
}
19
View Source File : Expression.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static Expression RenderExpression(StringReader reader, Func<string, string, object> parseValue)
{
var operands = new List<Expression>();
var name = new StringBuilder();
string op = null;
var union = false;
var unionAnd = false;
var unionOperandCount = 0;
while (true)
{
// pop the next character
var value = reader.Read();
// reached end of string?
if (value == -1) break;
var current = Convert.ToChar(value);
if (current == '\\')
{
// may be trying to escape a special character
var next = Convert.ToChar(reader.Peek());
if (@"*()\@".Contains(next.ToString()))
{
// read the next character as a literal value
reader.Read();
name.Append(current);
name.Append(next);
}
else
{
// not a special character, continue normally
name.Append(current);
}
}
else if (current == '(')
{
// start a recursive call to handle sub-expression
Expression operand = RenderExpression(reader, parseValue);
operands.Add(operand);
union = false;
unionOperandCount++;
}
else if (current == ')')
{
// reached end of sub-expression
if (union)
{
if (operands.Count <= unionOperandCount)
{
var operand = GetExpression(op, name.ToString(), operands, parseValue);
operands.Add(operand);
}
return unionAnd ? GetExpression("&", "&", operands, parseValue) : GetExpression("|", "|", operands, parseValue);
}
return GetExpression(op, name.ToString(), operands, parseValue);
}
else if ("&|!=<>~".Contains(current.ToString()))
{
if ((op != null | operands.Count > 0) && (current.ToString() == "&" | current.ToString() == "|"))
{
if (op != null)
{
var operand = GetExpression(op, name.ToString(), operands, parseValue);
operands.Add(operand);
unionOperandCount++;
name.Clear();
}
op = current.ToString();
if (union && unionAnd && current.ToString() == "|")
{
var unionOperand = GetExpression("&", "&", operands, parseValue);
operands.Clear();
operands.Add(unionOperand);
unionOperandCount = 1;
}
if (union && !unionAnd && current.ToString() == "&")
{
var unionOperand = GetExpression("|", "|", operands, parseValue);
operands.Clear();
operands.Add(unionOperand);
unionOperandCount = 1;
}
union = true;
unionAnd = current.ToString() == "&";
}
else
{
// encountered an operator
op = current.ToString();
name.Append(current);
// check if this is a 2 character operator
if (reader.Peek() > -1)
{
var next = Convert.ToChar(reader.Peek());
if ("=".Contains(next.ToString()))
{
// read the second character
reader.Read();
op += next;
name.Append(next);
}
}
}
}
else
{
// this is a character in a literal value
name.Append(current);
}
}
if (union)
{
if (operands.Count <= unionOperandCount)
{
var operand = GetExpression(op, name.ToString(), operands, parseValue);
operands.Add(operand);
}
return unionAnd ? GetExpression("&", "&", operands, parseValue) : GetExpression("|", "|", operands, parseValue);
}
// reached end of expression
return GetExpression(op, name.ToString(), operands, parseValue);
}
19
View Source File : AduPasswordBox.cs
License : GNU General Public License v3.0
Project Creator : aduskin
License : GNU General Public License v3.0
Project Creator : aduskin
private string ConvertToPreplacedwordChar(int length)
{
if (mPreplacedwordBuilder != null)
{
mPreplacedwordBuilder.Clear();
}
else
{
mPreplacedwordBuilder = new StringBuilder();
}
for (var i = 0; i < length; i++)
{
mPreplacedwordBuilder.Append(this.PreplacedwordChar);
}
return mPreplacedwordBuilder.ToString();
}
19
View Source File : Model.cs
License : MIT License
Project Creator : advancedmonitoring
License : MIT License
Project Creator : advancedmonitoring
private static void UpdateDirectory(string path)
{
var localSb = new StringBuilder();
localSb.AppendLine(path);
_currentFiles++;
var sddlString = "Unable obtain SDDL";
try
{
sddlString = Directory.GetAccessControl(path).GetSecurityDescriptorSddlForm(AccessControlSections.All);
}
catch
{
// ignore
}
localSb.AppendLine(sddlString);
_sb.AppendLine(localSb.ToString());
foreach (var dir in DirectorySearcher.MyGetDirectories(path))
{
try
{
if (_isRecursing)
UpdateDirectory(dir);
else
{
localSb.Clear();
localSb.AppendLine(dir);
_currentFiles++;
localSb.AppendLine(Directory.GetAccessControl(dir).GetSecurityDescriptorSddlForm(AccessControlSections.All));
_sb.AppendLine(localSb.ToString());
}
}
catch
{
// ignore
}
_ww.Percentage = (int)((_currentFiles + 0.0) * 100.0 / (_maxFiles + 0.0));
if (_ww.AbortEvent.WaitOne(0))
return;
}
if (_isFileInclude)
foreach (var file in DirectorySearcher.MyGetFiles(path))
{
try
{
localSb.Clear();
localSb.AppendLine(file);
_currentFiles++;
localSb.AppendLine(File.GetAccessControl(file).GetSecurityDescriptorSddlForm(AccessControlSections.All));
_sb.AppendLine(localSb.ToString());
}
catch
{
// ignore
}
_ww.Percentage = (int)((_currentFiles + 0.0) * 100.0 / (_maxFiles + 0.0));
if (_ww.AbortEvent.WaitOne(0))
return;
}
}
19
View Source File : Model.cs
License : MIT License
Project Creator : advancedmonitoring
License : MIT License
Project Creator : advancedmonitoring
private static void UpdateRegKey(RegistryKey key)
{
var localSb = new StringBuilder();
localSb.AppendLine(key.Name);
_currentFiles++;
var sddlString = "Unable obtain SDDL";
try
{
sddlString = key.GetAccessControl().GetSecurityDescriptorSddlForm(AccessControlSections.All);
}
catch
{
// ignore
}
localSb.AppendLine(sddlString);
_sb.AppendLine(localSb.ToString());
if (key.SubKeyCount != 0)
foreach (var sub in key.GetSubKeyNames())
{
try
{
var oKey = key.OpenSubKey(sub);
if (oKey != null)
if (_isRecursing)
UpdateRegKey(oKey);
else
{
localSb.Clear();
localSb.AppendLine(oKey.Name);
_currentFiles++;
localSb.AppendLine(
oKey.GetAccessControl().GetSecurityDescriptorSddlForm(AccessControlSections.All));
_sb.AppendLine(localSb.ToString());
}
}
catch
{
// ignored
}
_ww.Percentage = (int) ((_currentFiles + 0.0) * 100.0 / (_maxFiles + 0.0));
if (_ww.AbortEvent.WaitOne(0))
return;
}
}
19
View Source File : Profiler.cs
License : The Unlicense
Project Creator : aeroson
License : The Unlicense
Project Creator : aeroson
private void OnGUI()
{
if (!show)
return;
stringBuilder.Clear();
foreach (var pair in sampleNameToGUIText.OrderBy((pair) => pair.Key))
{
stringBuilder.AppendLine(pair.Key + " " + pair.Value);
}
GUILayout.Label(stringBuilder.ToString());
}
19
View Source File : MyPageBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void LogRequestInfo()
{
if (!LogRecorder.LogMonitor)
return;
var args = new StringBuilder();
args.Append("Headers:");
foreach (var head in Request.Headers.AllKeys)
{
args.Append($"[{head}]{Request[head]}");
}
LogRecorder.MonitorTrace(args.ToString());
args.Clear();
args.Append("QueryString:");
foreach (var head in Request.QueryString.AllKeys)
{
args.Append($"[{head}]{Request[head]}");
}
LogRecorder.MonitorTrace(args.ToString());
args.Clear();
args.Append("Form:");
foreach (var head in Request.Form.AllKeys)
{
args.Append($"[{head}]{Request[head]}");
}
LogRecorder.MonitorTrace(args.ToString());
args.Clear();
args.Append("Cookies:");
foreach (var head in Request.Cookies.AllKeys)
{
args.Append($"[{head}]{Request[head]}");
}
LogRecorder.MonitorTrace(args.ToString());
}
19
View Source File : RedisClientEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public bool ZScore(byte[] setId, byte[] dataId, out int h, out int l)
{
if (setId == null)
{
throw new ArgumentNullException("setId");
}
var command = new[] { Commands.ZScore, setId, dataId };
h = 0;
if (!this.SendCommand(command))
{
Status = -1;
LastError = string.Join(" ", "ZScore", Encoding.UTF8.GetString(setId), ByteCommond.BytesToLong(dataId));
l = 0;
return false;
}
var line = ReadSingleLine();
if (line.type != 2)
{
Status = 2;
l = 0;
return false;
}
StringBuilder sb = new StringBuilder();
foreach (char by in line.bValue)
{
if (by == '.')
{
h = int.Parse(sb.ToString());
sb.Clear();
}
else
{
sb.Append(by);
}
}
l = int.Parse(sb.ToString());
return true;
}
19
View Source File : CSVConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private static List<List<string>> Split(string values)
{
var result = new List<List<string>>();
var line = new List<string>();
var sb = new StringBuilder();
var inQuotation = false; //在引号中
var preQuotation = false; //前一个也是引号
var preSeparator = true; //前面是做字段分隔符号吗
bool isClose = false;
foreach (var c in values)
{
if (c == '\"')
{
if (inQuotation)
{
if (preQuotation) //连续引号当成正常的引号
{
sb.Append('\"');
preQuotation = false;
}
else //否则得看下一个,如果还是引号则认为正常引号,是引号当成引号来使用,其它情况不符合CVS的文件标准
{
preQuotation = true;
}
}
else if (preSeparator) //分隔符后的引号者才是字段内容起止
{
inQuotation = true;
preSeparator = false;
}
else
{
sb.Append(c);
}
continue;
}
if (preQuotation) //可中止
{
preQuotation = false;
inQuotation = false;
isClose = true;
line.Add(sb.ToString());
sb.Clear();
}
else if (inQuotation) //所有都是普通内容
{
sb.Append(c);
continue;
}
switch (c)
{
case ',':
if (isClose)
{
isClose = false;
}
else
{
if (sb.Length == 0)
{
line.Add(null);
}
else
{
line.Add(sb.ToString());
sb.Clear();
}
}
preSeparator = true;
continue;
case '\r':
case '\n':
if (isClose)
{
isClose = false;
}
else
{
if (sb.Length == 0)
{
line.Add(null);
}
else
{
line.Add(sb.ToString());
sb.Clear();
}
}
if (line.Count > 0)
{
result.Add(line);
line = new List<string>();
}
preSeparator = true;
continue;
case ' ':
case '\t':
break;
default:
if (preSeparator)
preSeparator = false;
break;
}
sb.Append(c);
}
if (sb.Length != 0)
{
line.Add(sb.ToString());
sb.Clear();
result.Add(line);
}
else if (line.Count > 0)
{
line.Add(null);
result.Add(line);
}
return result;
}
19
View Source File : CSVConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private static int Split(string values, Action<List<string>, bool, int> action)
{
var cnt = 0;
var first = true;
var line = new List<string>();
var sb = new StringBuilder();
var inQuotation = false; //在引号中
var preQuotation = false; //前一个也是引号
var preSeparator = true;//前面是做字段分隔符号吗
int empty = 0;
foreach (var c in values)
{
if (empty > 100)
break;
if (c == '\"')
{
empty = 0;
if (inQuotation)
{
if (preQuotation)//连续引号当成正常的引号
{
sb.Append('\"');
preQuotation = false;
}
else//否则得看下一个,如果还是引号则认为正常引号,是引号当成引号来使用,其它情况不符合CVS的文件标准
{
preQuotation = true;
}
continue;
}
if (preSeparator)//分隔符后的引号者才是字段内容起止
{
inQuotation = true;
preSeparator = false;
sb.Clear();
continue;
}
}
else if (preQuotation)//字段可中止
{
preQuotation = false;
inQuotation = false;
}
else if (inQuotation)//所有都是普通内容
{
sb.Append(c);
continue;
}
switch (c)
{
case ',':
if (sb.Length == 0)
{
line.Add(null);
}
else
{
line.Add(sb.ToString());
sb.Clear();
}
preSeparator = true;
continue;
case '\r':
continue;
case '\n':
if (sb.Length != 0)
{
line.Add(sb.ToString());
sb.Clear();
}
if (line.Count > 0 && line.Any(p => p != null))
{
if (preSeparator)
line.Add(null);
action(line, first, ++cnt);
line = new List<string>();
}
else
{
++empty;
continue;
}
first = false;
preSeparator = true;
empty = 0;
continue;
}
empty = 0;
if (preSeparator && !char.IsWhiteSpace(c))
{
preSeparator = false;
}
sb.Append(c);
}
if (sb.Length != 0)
{
line.Add(sb.ToString());
sb.Clear();
}
if (line.Count > 0 && line.Any(p => p != null))
{
line.Add(null);
action(line, first, ++cnt);
}
return cnt;
}
19
View Source File : StringHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static string[] SpliteWord(string word)
{
if (string.IsNullOrEmpty(word))
return null;
var words = new List<string>();
var sb = new StringBuilder();
foreach (var ch in word)
{
switch (ch)
{
case '_':
case '-':
case '\\':
case '/':
case '~':
case '!':
case '@':
case '$':
case '%':
case '&':
case '*':
case '|':
case '^':
case '.':
case ',':
case '?':
case '+':
case '=':
case '[':
case ']':
case '(':
case ')':
case '>':
case '<':
case '}':
case '{':
if (sb.Length > 0)
{
words.Add(sb.ToString());
sb.Clear();
}
continue;
}
if (ch >= 'A' && ch <= 'Z' && sb.Length > 0)
{
words.Add(sb.ToString());
sb.Clear();
}
sb.Append(ch);
}
if (sb.Length > 0)
{
words.Add(sb.ToString());
}
return words.ToArray();
}
19
View Source File : MonitorItem.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public string End()
{
InMonitor = false;
try
{
MonitorData pre = null;
while (Stack.StackCount > 0)
{
Stack.Current.Coll(pre);
Stack.Current.EndMessage();
Write(Stack.Current.replacedle, ItemType.End);
pre = Stack.Current;
Stack.Pop();
}
Stack.Current.Coll(pre);
Stack.FixValue.EndMessage();
Write(Stack.FixValue.replacedle ?? "Monitor", ItemType.End);
return Texter.ToString();
}
catch (Exception ex)
{
LogRecorderX.SystemTrace(LogLevel.Error, "EndMonitor", ex);
return null;
}
finally
{
Texter.Clear();
}
}
19
View Source File : CSVReader.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private static List<List<string>> Split(string values)
{
var result = new List<List<string>>();
List<string> line = null;
var sb = new StringBuilder();
var inQuotation = false; //在引号中
var preQuotation = false; //前一个也是引号
foreach (var c in values)
{
switch (c)
{
case ',':
if (!inQuotation || preQuotation)
{
preQuotation = false;
inQuotation = false;
if (line == null)
{
line = new List<string>();
result.Add(line);
}
line.Add(sb.ToString());
sb.Clear();
}
else
{
sb.Append(',');
}
continue;
case '\"':
if (inQuotation)
{
if (preQuotation)
{
sb.Append('\"');
preQuotation = false; //连续引号当成正常的引号
continue;
}
//否则得看下一个,如果还是引号则认为正常引号,是引号当成引号来使用,其它情况不符合CVS的文件标准
preQuotation = true;
continue;
}
inQuotation = true;
continue;
case '\r':
case '\n':
if (!inQuotation || preQuotation)
{
if (line != null)
{
line.Add(sb.ToString());
}
sb.Clear();
line = null;
inQuotation = false;
preQuotation = false;
}
else
{
sb.Append(c);
}
continue;
default:
if (preQuotation)
{
sb.Append('\"');
preQuotation = false;
continue;
}
break;
}
sb.Append(c);
}
return result;
}
19
View Source File : RedisClientEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public bool ZScore(byte[] setId, byte[] dataId, out int h, out int l)
{
if (setId == null)
{
throw new ArgumentNullException("setId");
}
var command = new[] { Commands.ZScore, setId, dataId };
h = 0;
if (!SendCommand(command))
{
Status = -1;
LastError = string.Join(" ", "ZScore", Encoding.UTF8.GetString(setId), dataId.BytesToLong());
l = 0;
return false;
}
var line = ReadSingleLine();
if (line.type != 2)
{
Status = 2;
l = 0;
return false;
}
StringBuilder sb = new StringBuilder();
foreach (char by in line.bValue)
{
if (by == '.')
{
h = int.Parse(sb.ToString());
sb.Clear();
}
else
{
sb.Append(by);
}
}
l = int.Parse(sb.ToString());
return true;
}
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 ProcessModuleWow64Safe[] ModulesWow64Safe(this Process p)
{
if (ModuleCache.Count > 100)
ModuleCache.Clear();
const int LIST_MODULES_ALL = 3;
const int MAX_PATH = 260;
var hModules = new IntPtr[1024];
uint cb = (uint)IntPtr.Size*(uint)hModules.Length;
uint cbNeeded;
if (!WinAPI.EnumProcessModulesEx(p.Handle, hModules, cb, out cbNeeded, LIST_MODULES_ALL))
throw new Win32Exception();
uint numMods = cbNeeded / (uint)IntPtr.Size;
int hash = p.StartTime.GetHashCode() + p.Id + (int)numMods;
if (ModuleCache.ContainsKey(hash))
return ModuleCache[hash];
var ret = new List<ProcessModuleWow64Safe>();
// everything below is fairly expensive, which is why we cache!
var sb = new StringBuilder(MAX_PATH);
for (int i = 0; i < numMods; i++)
{
sb.Clear();
if (WinAPI.GetModuleFileNameEx(p.Handle, hModules[i], sb, (uint)sb.Capacity) == 0)
throw new Win32Exception();
string fileName = sb.ToString();
sb.Clear();
if (WinAPI.GetModuleBaseName(p.Handle, hModules[i], sb, (uint)sb.Capacity) == 0)
throw new Win32Exception();
string baseName = sb.ToString();
var moduleInfo = new WinAPI.MODULEINFO();
if (!WinAPI.GetModuleInformation(p.Handle, hModules[i], out moduleInfo, (uint)Marshal.SizeOf(moduleInfo)))
throw new Win32Exception();
ret.Add(new ProcessModuleWow64Safe()
{
FileName = fileName,
BaseAddress = moduleInfo.lpBaseOfDll,
ModuleMemorySize = (int)moduleInfo.SizeOfImage,
EntryPointAddress = moduleInfo.EntryPoint,
ModuleName = baseName
});
}
ModuleCache.Add(hash, ret.ToArray());
return ret.ToArray();
}
19
View Source File : TechLogFileReader.cs
License : MIT License
Project Creator : akpaevj
License : MIT License
Project Creator : akpaevj
private ReadOnlySpan<char> ReadRawItem(CancellationToken cancellationToken = default)
{
InitializeStream();
string line = null;
while (!cancellationToken.IsCancellationRequested)
{
line = _streamReader.ReadLine();
// This is the end of the event or the end of the stream
if (line is null || _data.Length > 0 && Regex.IsMatch(line, @"^\d\d:\d\d\.", RegexOptions.Compiled))
break;
if (line.Length > 0)
_data.AppendLine(line);
_lastEventEndPosition = Position;
}
if (_data.Length == 0)
return null;
var result = $"{_fileDateTime}:{_data}";
_data.Clear();
if (line != null)
_data.AppendLine(line);
return result.replacedpan();
}
19
View Source File : DebugViewXNA.cs
License : MIT License
Project Creator : Alan-FGR
License : MIT License
Project Creator : Alan-FGR
private void DrawDebugPanel()
{
int fixtureCount = 0;
for (int i = 0; i < World.BodyList.Count; i++)
{
fixtureCount += World.BodyList[i].FixtureList.Count;
}
int x = (int)DebugPanelPosition.X;
int y = (int)DebugPanelPosition.Y;
#if XBOX
_debugPanelSb = new StringBuilder();
#else
_debugPanelSb.Clear();
#endif
_debugPanelSb.AppendLine("Objects:");
_debugPanelSb.Append("- Bodies: ").AppendLine(World.BodyList.Count.ToString());
_debugPanelSb.Append("- Fixtures: ").AppendLine(fixtureCount.ToString());
_debugPanelSb.Append("- Contacts: ").AppendLine(World.ContactList.Count.ToString());
_debugPanelSb.Append("- Joints: ").AppendLine(World.JointList.Count.ToString());
_debugPanelSb.Append("- Controllers: ").AppendLine(World.ControllerList.Count.ToString());
_debugPanelSb.Append("- Proxies: ").AppendLine(World.ProxyCount.ToString());
DrawString(x, y, _debugPanelSb.ToString());
#if XBOX
_debugPanelSb = new StringBuilder();
#else
_debugPanelSb.Clear();
#endif
_debugPanelSb.AppendLine("Update time:");
_debugPanelSb.Append("- Body: ").AppendLine(string.Format("{0} ms", World.SolveUpdateTime / TimeSpan.TicksPerMillisecond));
_debugPanelSb.Append("- Contact: ").AppendLine(string.Format("{0} ms", World.ContactsUpdateTime / TimeSpan.TicksPerMillisecond));
_debugPanelSb.Append("- CCD: ").AppendLine(string.Format("{0} ms", World.ContinuousPhysicsTime / TimeSpan.TicksPerMillisecond));
_debugPanelSb.Append("- Joint: ").AppendLine(string.Format("{0} ms", World.Island.JointUpdateTime / TimeSpan.TicksPerMillisecond));
_debugPanelSb.Append("- Controller: ").AppendLine(string.Format("{0} ms", World.ControllersUpdateTime / TimeSpan.TicksPerMillisecond));
_debugPanelSb.Append("- Total: ").AppendLine(string.Format("{0} ms", World.UpdateTime / TimeSpan.TicksPerMillisecond));
DrawString(x + 110, y, _debugPanelSb.ToString());
}
19
View Source File : ExtensionMethods.cs
License : GNU General Public License v3.0
Project Creator : Albo1125
License : GNU General Public License v3.0
Project Creator : Albo1125
public static List<string> WrapText(this string text, double pixels, string fontFamily, float emSize, out double actualHeight)
{
string[] originalLines = text.Split(new string[] { " " },
StringSplitOptions.None);
List<string> wrappedLines = new List<string>();
StringBuilder actualLine = new StringBuilder();
double actualWidth = 0;
actualHeight = 0;
foreach (var item in originalLines)
{
System.Windows.Media.FormattedText formatted = new System.Windows.Media.FormattedText(item,
CultureInfo.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new System.Windows.Media.Typeface(fontFamily), emSize, System.Windows.Media.Brushes.Black);
actualWidth += formatted.Width;
actualHeight = formatted.Height;
if (actualWidth > pixels)
{
wrappedLines.Add(actualLine.ToString());
actualLine.Clear();
actualWidth = 0;
actualLine.Append(item + " ");
actualWidth += formatted.Width;
}
else if (item == Environment.NewLine || item=="\n")
{
wrappedLines.Add(actualLine.ToString());
actualLine.Clear();
actualWidth = 0;
}
else
{
actualLine.Append(item + " ");
}
}
if (actualLine.Length > 0)
wrappedLines.Add(actualLine.ToString());
return wrappedLines;
}
19
View Source File : Context.cs
License : MIT License
Project Creator : alexanderdna
License : MIT License
Project Creator : alexanderdna
private async Task readAsync()
{
// How it works:
// Messages are serialized as strings delimited by '\n' character.
// They are read from the network stream and sometimes we can't
// just read one whole message string in one ReadAsync call.
// So we will add read characters to a string builder and call it
// a complete message when encountering a '\n' character. Then
// we clear the builder and add what would be the beginning of the
// next message.
if (ShouldDisconnect is false && Client.Available > 0)
{
var stream = Client.GetStream();
int nRead = await stream.ReadAsync(inBuffer.AsMemory(0, inBuffer.Length));
if (nRead == 0) return;
// replaceduming messages consist of only ASCII characters.
// This will speed up reading because Encoding.UTF8.GetString is not used.
for (int i = 0; i < nRead; ++i)
{
inBufferreplacedtring[i] = (char)(inBuffer[i] & 0x7f);
}
// Read characters may consist of: part of 1 message, 1 message or many messages.
int pos, posNewLine = 0;
do
{
pos = -1;
for (int i = posNewLine; i < nRead; ++i)
{
if (inBufferreplacedtring[i] == '\n')
{
pos = i;
break;
}
}
if (pos >= 0)
{
// Delimiter found. Try to complete the latest message and clear sb.
sb.Append(inBufferreplacedtring, posNewLine, pos - posNewLine);
// Message is too long. Disconnect the peer now because we don't want any troubles.
if (sb.Length > MaxMessageLength)
{
sb.Clear();
ShouldDisconnect = true;
break;
}
posNewLine = pos + 1;
var msgJson = sb.ToString();
try
{
var msg = Message.Deserialize(msgJson);
inMessageQueue.Enqueue(msg);
}
catch (Newtonsoft.Json.JsonException)
{
ShouldDisconnect = true;
}
sb.Length = 0;
}
else
{
// Delimiter not found. Add what we have read to sb and wait for more data to be received.
sb.Append(inBufferreplacedtring, posNewLine, nRead - posNewLine);
// Message is too long. Disconnect the peer now because we don't want any troubles.
if (sb.Length > MaxMessageLength)
{
sb.Clear();
ShouldDisconnect = true;
break;
}
}
} while (pos >= 0 && pos < nRead);
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : alexanderdna
License : MIT License
Project Creator : alexanderdna
private static string readPreplacedphrase(System.Text.StringBuilder sb)
{
sb.Clear();
while (true)
{
var key = Console.ReadKey(intercept: true);
if (key.Modifiers != 0) continue;
if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine();
break;
}
else if (key.Key == ConsoleKey.Escape)
{
Console.WriteLine();
return null;
}
else if (key.Key == ConsoleKey.Backspace)
{
Console.WriteLine();
return string.Empty;
}
else if (key.KeyChar >= 20 && key.KeyChar < 256)
{
Console.Write('*');
sb.Append(key.KeyChar);
}
}
return sb.ToString();
}
See More Examples