Here are the examples of the csharp api System.Collections.Generic.IEnumerable.ToArray() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
25251 Examples
19
Source : UCGeneratedCode.cs
with MIT License
from 2881099
with MIT License
from 2881099
void InitTemplates()
{
string path = Path.Combine(Environment.CurrentDirectory, "Templates");
string[] dir = Directory.GetDirectories(path);
DirectoryInfo fdir = new DirectoryInfo(path);
FileInfo[] file = fdir.GetFiles("*.tpl");
if (file.Length != 0 || dir.Length != 0)
{
foreach (FileInfo f in file)
{
lst.Add(f);
}
}
if (lst.Count >= 1)
{
comboBoxEx1.DataSource = lst.Select(a => a.Name).ToArray();
comboBoxEx1.SelectedIndex = 0;
editorTemplates.Load(lst.FirstOrDefault().FullName);
}
}
19
Source : FrmBatch.cs
with MIT License
from 2881099
with MIT License
from 2881099
void LoadTableList()
{
dbTableInfos = G.GetTablesByDatabase(_node.Parent.DataKey, _node.Text);
listBoxAdv1.DataSource = dbTableInfos.Select(a => a.Name).ToArray();
}
19
Source : FrmRazorTemplates.cs
with MIT License
from 2881099
with MIT License
from 2881099
void loadTemplates()
{
string path = Path.Combine(Environment.CurrentDirectory, "Templates");
string[] dir = Directory.GetDirectories(path);
DirectoryInfo fdir = new DirectoryInfo(path);
FileInfo[] file = fdir.GetFiles("*.tpl");
if (file.Length != 0 || dir.Length != 0)
{
foreach (FileInfo f in file)
{
lst.Add(f);
}
}
if (lst.Count >= 1)
{
comboBoxEx1.DataSource = lst.Select(a => a.Name).ToArray();
comboBoxEx1.SelectedIndex = 0;
}
}
19
Source : ImClient.cs
with MIT License
from 2881099
with MIT License
from 2881099
public void SendMessage(Guid senderClientId, IEnumerable<Guid> receiveClientId, object message, bool receipt = false)
{
receiveClientId = receiveClientId.Distinct().ToArray();
Dictionary<string, ImSendEventArgs> redata = new Dictionary<string, ImSendEventArgs>();
foreach (var uid in receiveClientId)
{
string server = SelectServer(uid);
if (redata.ContainsKey(server) == false) redata.Add(server, new ImSendEventArgs(server, senderClientId, message, receipt));
redata[server].ReceiveClientId.Add(uid);
}
var messageJson = JsonConvert.SerializeObject(message);
foreach (var sendArgs in redata.Values)
{
OnSend?.Invoke(this, sendArgs);
_redis.Publish($"{_redisPrefix}Server{sendArgs.Server}",
JsonConvert.SerializeObject((senderClientId, sendArgs.ReceiveClientId, messageJson, sendArgs.Receipt)));
}
}
19
Source : InternalExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
{
if (type == null) return null;
if (type == typeof(void)) return "void";
if (type.IsGenericParameter) return type.Name;
if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
var sb = new StringBuilder();
var nestedType = type;
while (nestedType.IsNested)
{
sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
nestedType = nestedType.DeclaringType;
}
if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
sb.Insert(0, ".").Insert(0, nestedType.Namespace);
if (type.IsGenericType == false)
return sb.Append(type.Name).ToString();
var genericParameters = type.GetGenericArguments();
if (type.IsNested && type.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any() == false)
return sb.Append(type.Name).ToString();
sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
var genericTypeIndex = 0;
foreach (var genericType in genericParameters)
{
if (genericTypeIndex++ > 0) sb.Append(", ");
sb.Append(DisplayCsharp(genericType, true));
}
return sb.Append(">").ToString();
}
19
Source : InternalExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
static string DisplayCsharp(this MethodInfo method, bool isOverride)
{
if (method == null) return null;
var sb = new StringBuilder();
if (method.IsPublic) sb.Append("public ");
if (method.Isreplacedembly) sb.Append("internal ");
if (method.IsFamily) sb.Append("protected ");
if (method.IsPrivate) sb.Append("private ");
if (method.IsPrivate) sb.Append("private ");
if (method.IsStatic) sb.Append("static ");
if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);
var genericParameters = method.GetGenericArguments();
if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any())
sb.Append("<")
.Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
.Append(">");
sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");
return sb.ToString();
}
19
Source : DynamicProxyExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
internal static string DisplayCsharp(this MethodInfo method, bool isOverride)
{
if (method == null) return null;
var sb = new StringBuilder();
if (method.IsPublic) sb.Append("public ");
if (method.Isreplacedembly) sb.Append("internal ");
if (method.IsFamily) sb.Append("protected ");
if (method.IsPrivate) sb.Append("private ");
if (method.IsPrivate) sb.Append("private ");
if (method.IsStatic) sb.Append("static ");
if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);
var genericParameters = method.GetGenericArguments();
if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any())
sb.Append("<")
.Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
.Append(">");
sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");
return sb.ToString();
}
19
Source : DynamicProxyMeta.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static object CreateInstanceDefault(Type type)
{
if (type == null) return null;
if (type == typeof(string)) return default(string);
if (type.IsArray) return Array.CreateInstance(type, 0);
var ctorParms = InternalGetTypeConstructor0OrFirst(type, true)?.GetParameters();
if (ctorParms == null || ctorParms.Any() == false) return Activator.CreateInstance(type, null);
return Activator.CreateInstance(type, ctorParms.Select(a => a.ParameterType.IsInterface || a.ParameterType.IsAbstract || a.ParameterType == typeof(string) ? null : Activator.CreateInstance(a.ParameterType, null)).ToArray());
}
19
Source : TypeExtension.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static string ToInterface(this MethodInfo method, bool isAlign = true)
{
if (method == null) return null;
var sb = new StringBuilder();
//if (method.IsPublic) sb.Append("public ");
//if (method.Isreplacedembly) sb.Append("internal ");
//if (method.IsFamily) sb.Append("protected ");
//if (method.IsPrivate) sb.Append("private ");
//if (method.IsPrivate) sb.Append("private ");
//if (method.IsStatic) sb.Append("static ");
//if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
//if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
if (isAlign)
sb.Append(" ");
sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);
var genericParameters = method.GetGenericArguments();
if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any())
sb.Append("<")
.Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
.Append(">");
sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))).Append(")");
if (isAlign)
sb.Append(";\r\n\r\n");
return sb.ToString();
}
19
Source : TypeExtension.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static string ToProxy(this MethodInfo method)
{
if (method == null) return null;
var sb = new StringBuilder();
sb.Append(" public ");
var returnType = method.ReturnType;
var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
var isAsync = isGenericAsync || isNoResultAsync;
if (isAsync)
sb.Append("async ");
var funcInfo = method.ToInterface(false);
sb.AppendLine(funcInfo);
sb.AppendLine(" {");
var isResult = false;
if (isAsync)
{
sb.AppendLine($" await _context.BeforeAsync(typeof(RedisClient).GetMethod({method.Name}))");
}
else
{
sb.AppendLine($" _context.Before(typeof(RedisClient).GetMethod({method.Name}))");
}
if (isAsync)
{
if (isNoResultAsync)
sb.Append(" await _redisClient.").Append(method.Name);
else
{
isResult = true;
sb.Append(" var result = await _redisClient.").Append(method.Name);
}
}
else
{
if (returnType == typeof(void))
{
sb.Append(" _redisClient.").Append(method.Name);
}
else
{
isResult = true;
sb.Append(" var result = _redisClient.").Append(method.Name);
}
}
var genericParameters = method.GetGenericArguments();
if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any())
sb.Append("<")
.Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
.Append(">");
sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");
if (isAsync)
{
sb.AppendLine($" await _context.AfterAsync(typeof(RedisClient).GetMethod({method.Name}))");
}
else
{
sb.AppendLine($" _context.After(typeof(RedisClient).GetMethod({method.Name}))");
}
if (isResult)
sb.AppendLine(" return result;");
sb.Append(" }\r\n\r\n");
return sb.ToString();
}
19
Source : KeysTests.cs
with MIT License
from 2881099
with MIT License
from 2881099
[Fact]
public void Del()
{
var keys = Enumerable.Range(0, 10).Select(a => Guid.NewGuid().ToString()).ToArray();
cli.MSet(keys.ToDictionary(a => a, a => (object)a));
replacedert.Equal(10, cli.Del(keys));
}
19
Source : DbSetSync.cs
with MIT License
from 2881099
with MIT License
from 2881099
int DbContextBetchUpdatePriv(EnreplacedyState[] ups, bool isLiveUpdate) {
if (ups.Any() == false) return 0;
var uplst1 = ups[ups.Length - 1];
var uplst2 = ups.Length > 1 ? ups[ups.Length - 2] : null;
if (_states.TryGetValue(uplst1.Key, out var lstval1) == false) return -999;
var lstval2 = default(EnreplacedyState);
if (uplst2 != null && _states.TryGetValue(uplst2.Key, out lstval2) == false) throw new Exception($"特别错误:更新失败,数据未被跟踪:{_fsql.GetEnreplacedyString(_enreplacedyType, uplst2.Value)}");
var cuig1 = _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst1.Value, lstval1.Value, true);
var cuig2 = uplst2 != null ? _fsql.CompareEnreplacedyValueReturnColumns(_enreplacedyType, uplst2.Value, lstval2.Value, true) : null;
List<EnreplacedyState> data = null;
string[] cuig = null;
if (uplst2 != null && string.Compare(string.Join(",", cuig1), string.Join(",", cuig2)) != 0) {
//最后一个不保存
data = ups.ToList();
data.RemoveAt(ups.Length - 1);
cuig = cuig2;
} else if (isLiveUpdate) {
//立即保存
data = ups.ToList();
cuig = cuig1;
}
if (data?.Count > 0) {
if (cuig.Length == _table.Columns.Count)
return ups.Length == data.Count ? -998 : -997;
var updateSource = data.Select(a => a.Value).ToArray();
var update = this.OrmUpdate(null).SetSource(updateSource).IgnoreColumns(cuig);
var affrows = update.ExecuteAffrows();
foreach (var newval in data) {
if (_states.TryGetValue(newval.Key, out var tryold))
_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, tryold.Value);
if (newval.OldValue != null)
_fsql.MapEnreplacedyValue(_enreplacedyType, newval.Value, newval.OldValue);
}
return affrows;
}
//等待下次对比再保存
return 0;
}
19
Source : DynamicProxy.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
{
if (type == null) return null;
var typeCSharpName = type.DisplayCsharp();
if (type.IsNotPublic)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
return null;
}
var matchedMemberInfos = new List<MemberInfo>();
var matchedAttributes = new List<DynamicProxyAttribute>();
var matchedAttributesFromServices = new List<FieldInfo[]>();
var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
var methodOverrideSb = new StringBuilder();
var sb = methodOverrideSb;
#region Common Code
Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
{
var sbt = new StringBuilder();
for (var a = attrsIndex; a < matchedAttributes.Count; a++)
{
sbt.Append($@"{(proxyMethodName == "Before" ? $@"
var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
__DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
{(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
{(proxyMethodName == "Before" ?
$@"if (__DP_ARG___is_return == false)
{{
__DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
}}" :
$"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
}
return sbt.ToString();
};
Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
{
var sbt = new StringBuilder();
var taskType = returnType.ReturnTypeWithoutTask();
sbt.Append($@"
{(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
(taskType.IsValueType || taskType.IsGenericParameter ?
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
) :
(returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
return sbt.ToString();
};
Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
{
return $@"
if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
};
#endregion
#region Methods
var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var method in methods)
{
if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => method));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
if (method.IsVirtual == false || method.IsFinal)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
continue;
}
#if net40
var returnType = method.ReturnType;
var methodIsAsync = false;
#else
var returnType = method.ReturnType.ReturnTypeWithoutTask();
var methodIsAsync = method.ReturnType.IsTask();
//if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
// attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
//{
//}
#endif
var baseInvoke = type.IsInterface == false ? $@"
try
{{
if (__DP_ARG___is_return == false)
{{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
{(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}" : "";
sb.Append($@"
{(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
}}");
}
#endregion
var propertyOverrideSb = new StringBuilder();
sb = propertyOverrideSb;
#region Property
var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
foreach (var prop2 in props)
{
var getMethod = prop2.GetGetMethod(false);
var setMethod = prop2.GetSetMethod(false);
if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
{
if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
continue;
}
}
var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
var prop2AttributeAny = attrs.Any();
var getMethodAttributeAny = prop2AttributeAny;
var setMethodAttributeAny = prop2AttributeAny;
if (attrs.Any() == false && getMethod?.IsVirtual == true)
{
attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
getMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false && setMethod?.IsVirtual == true)
{
attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
setMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => prop2));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();
var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
if (propSetModification == propModification) propSetModification = "";
if (propGetModification == propModification) propGetModification = "";
//if (getMethod.IsAbstract) sb.Append("abstract ");
sb.Append($@"
{propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
{{");
if (getMethod != null)
{
if (getMethodAttributeAny == false) sb.Append($@"
{propGetModification} get
{{
return base.{prop2.Name}
}}");
else sb.Append($@"
{propGetModification} get
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
}}");
}
if (setMethod != null)
{
if (setMethodAttributeAny == false) sb.Append($@"
{propSetModification} set
{{
base.{prop2.Name} = value;
}}");
else sb.Append($@"
{propSetModification} set
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
__DP_ARG___parameters.Add(""value"", value);
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false)
{{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
base.{prop2.Name} = value;
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
}}");
}
sb.Append($@"
}}");
}
#endregion
string proxyCscode = "";
replacedembly proxyreplacedembly = null;
Type proxyType = null;
if (matchedMemberInfos.Any())
{
#region Constructors
sb = new StringBuilder();
var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
sb.Append(string.Join("", fromServicesTypes.Select(serviceType => $@"
private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
foreach (var ctor in ctors)
{
var ctorParams = ctor.GetParameters();
sb.Append($@"
{(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
(ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
string.Join(", ", fromServicesTypes.Select(serviceType => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
: base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
{{{string.Join("", fromServicesTypes.Select(serviceType => $@"
{serviceType.Value} = parameter{serviceType.Value};"))}
}}");
}
for (var a = 0; a < matchedAttributesFromServices.Count; a++)
{
sb.Append($@"
private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
{{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
__DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
}}");
}
#endregion
proxyCscode = $@"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public clreplaced {clreplacedName} : {typeCSharpName}
{{
private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));
//这里要注释掉,如果重写的基类没有无参构造函数,会报错
//public {clreplacedName}({_metaName} meta)
//{{
// __DP_Meta = meta;
//}}
{sb.ToString()}
{methodOverrideSb.ToString()}
{propertyOverrideSb.ToString()}
}}";
proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
}
methodOverrideSb.Clear();
propertyOverrideSb.Clear();
sb.Clear();
return new DynamicProxyMeta(
type, ctors,
matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
}
19
Source : TypeExtension.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static string DisplayCsharp(this Type type, bool isNameSpace = true)
{
if (type == null) return null;
if (type == typeof(void)) return "void";
if (type.IsGenericParameter) return type.Name;
if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
var sb = new StringBuilder();
var nestedType = type;
while (nestedType.IsNested)
{
sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
nestedType = nestedType.DeclaringType;
}
if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
sb.Insert(0, ".").Insert(0, nestedType.Namespace);
if (type.IsGenericType == false)
return sb.Append(type.Name).ToString();
var genericParameters = type.GetGenericArguments();
if (type.IsNested && type.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any() == false)
return sb.Append(type.Name).ToString();
sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
var genericTypeIndex = 0;
foreach (var genericType in genericParameters)
{
if (genericTypeIndex++ > 0) sb.Append(", ");
sb.Append(DisplayCsharp(genericType, true));
}
return sb.Append(">").ToString();
}
19
Source : TypeExtension.cs
with MIT License
from 2881099
with MIT License
from 2881099
public static string ToMethod(this MethodInfo method)
{
if (method == null) return null;
var sb = new StringBuilder();
sb.Append(" public static ");
var returnType = method.ReturnType;
var isNoResultAsync = returnType == typeof(Task) || returnType == typeof(ValueTask);
var isGenericAsync = returnType.IsGenericType && (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) || returnType.GetGenericTypeDefinition() == typeof(Task<>));
var isAsync = isGenericAsync || isNoResultAsync;
var isResult = false;
if (isAsync)
sb.Append("async ");
var funcInfo = method.ToInterface(false);
sb.AppendLine(funcInfo);
sb.AppendLine(" {");
if (isAsync)
{
if (isNoResultAsync)
sb.Append(" await _redisClient.").Append(method.Name);
else
{
isResult = true;
sb.Append(" var result = await _redisClient.").Append(method.Name);
}
}
else
{
if (returnType == typeof(void))
{
sb.Append(" _redisClient.").Append(method.Name);
}
else
{
isResult = true;
sb.Append(" var result = _redisClient.").Append(method.Name);
}
}
var genericParameters = method.GetGenericArguments();
if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any())
sb.Append("<")
.Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
.Append(">");
sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => $" {a.Name}"))).AppendLine(");");
if (isResult)
sb.AppendLine(" return result;");
sb.Append(" }\r\n\r\n");
return sb.ToString();
}
19
Source : CommandFlagsTests.cs
with MIT License
from 2881099
with MIT License
from 2881099
[Fact]
public void Command()
{
string UFString(string text)
{
if (text.Length <= 1) return text.ToUpper();
else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
}
var rt = cli.Command();
//var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename");
var flags = new List<string>();
var flags7 = new List<string>();
var diccmd = new Dictionary<string, (string[], string[])>();
var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 =>
{
var a = a1 as object[];
var cmd = a[0].ToString();
var plen = int.Parse(a[1].ToString());
var firstKey = int.Parse(a[3].ToString());
var lastKey = int.Parse(a[4].ToString());
var stepCount = int.Parse(a[5].ToString());
var aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray();
var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray();
flags.AddRange(aflags);
flags7.AddRange(fopts);
diccmd.Add(cmd.ToUpper(), (aflags, fopts));
var parms = "";
if (plen > 1)
{
for (var x = 1; x < plen; x++)
{
if (x == firstKey) parms += "string key, ";
else parms += $"string arg{x}, ";
}
parms = parms.Remove(parms.Length - 2);
}
if (plen < 0)
{
for (var x = 1; x < -plen; x++)
{
if (x == firstKey)
{
if (firstKey != lastKey) parms += "string[] keys, ";
else parms += "string key, ";
}
else
{
if (firstKey != lastKey) parms += $"string[] arg{x}, ";
else parms += $"string arg{x}, ";
}
}
if (parms.Length > 0)
parms = parms.Remove(parms.Length - 2);
}
return $@"
//{string.Join(", ", a[2] as object[])}
//{string.Join(", ", a[6] as object[])}
public void {UFString(cmd)}({parms}) {{ }}";
}));
flags = flags.Distinct().ToList();
flags7 = flags7.Distinct().ToList();
var sboptions = new StringBuilder();
foreach (var cmd in CommandSets._allCommands)
{
if (diccmd.TryGetValue(cmd, out var tryv))
{
sboptions.Append($@"
[""{cmd}""] = new CommandSets(");
for (var x = 0; x < tryv.Item1.Length; x++)
{
if (x > 0) sboptions.Append(" | ");
sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}");
}
sboptions.Append(", ");
for (var x = 0; x < tryv.Item2.Length; x++)
{
if (x > 0) sboptions.Append(" | ");
sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}");
}
sboptions.Append(", LocalStatus.none),");
}
else
{
sboptions.Append($@"
[""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), ");
}
}
var optioncode = sboptions.ToString();
}
19
Source : DynamicProxyExtensions.cs
with MIT License
from 2881099
with MIT License
from 2881099
internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
{
if (type == null) return null;
if (type == typeof(void)) return "void";
if (type.IsGenericParameter) return type.Name;
if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
var sb = new StringBuilder();
var nestedType = type;
while (nestedType.IsNested)
{
sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
nestedType = nestedType.DeclaringType;
}
if (isNameSpace && string.IsNullOrEmpty(nestedType.Namespace) == false)
sb.Insert(0, ".").Insert(0, nestedType.Namespace);
if (type.IsGenericType == false)
return sb.Append(type.Name).ToString();
var genericParameters = type.GetGenericArguments();
if (type.IsNested && type.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any() == false)
return sb.Append(type.Name).ToString();
sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
var genericTypeIndex = 0;
foreach (var genericType in genericParameters)
{
if (genericTypeIndex++ > 0) sb.Append(", ");
sb.Append(DisplayCsharp(genericType, true));
}
return sb.Append(">").ToString();
}
19
Source : ShareHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public static string GetShareUrl(Config config, int index)
{
try
{
string url = string.Empty;
VmessItem item = config.vmess[index];
if (item.configType == (int)EConfigType.Vmess)
{
VmessQRCode vmessQRCode = new VmessQRCode
{
v = item.configVersion.ToString(),
ps = item.remarks.TrimEx(), //备注也许很长 ;
add = item.address,
port = item.port.ToString(),
id = item.id,
aid = item.alterId.ToString(),
scy = item.security,
net = item.network,
type = item.headerType,
host = item.requestHost,
path = item.path,
tls = item.streamSecurity,
sni = item.sni
};
url = Utils.ToJson(vmessQRCode);
url = Utils.Base64Encode(url);
url = string.Format("{0}{1}", Global.vmessProtocol, url);
}
else if (item.configType == (int)EConfigType.Shadowsocks)
{
string remark = string.Empty;
if (!Utils.IsNullOrEmpty(item.remarks))
{
remark = "#" + Utils.UrlEncode(item.remarks);
}
url = string.Format("{0}:{1}@{2}:{3}",
item.security,
item.id,
item.address,
item.port);
url = Utils.Base64Encode(url);
url = string.Format("{0}{1}{2}", Global.ssProtocol, url, remark);
}
else if (item.configType == (int)EConfigType.Socks)
{
string remark = string.Empty;
if (!Utils.IsNullOrEmpty(item.remarks))
{
remark = "#" + Utils.UrlEncode(item.remarks);
}
url = string.Format("{0}:{1}@{2}:{3}",
item.security,
item.id,
item.address,
item.port);
url = Utils.Base64Encode(url);
url = string.Format("{0}{1}{2}", Global.socksProtocol, url, remark);
}
else if (item.configType == (int)EConfigType.Trojan)
{
string remark = string.Empty;
if (!Utils.IsNullOrEmpty(item.remarks))
{
remark = "#" + Utils.UrlEncode(item.remarks);
}
string query = string.Empty;
if (!Utils.IsNullOrEmpty(item.sni))
{
query = string.Format("?sni={0}", Utils.UrlEncode(item.sni));
}
url = string.Format("{0}@{1}:{2}",
item.id,
GetIpv6(item.address),
item.port);
url = string.Format("{0}{1}{2}{3}", Global.trojanProtocol, url, query, remark);
}
else if (item.configType == (int)EConfigType.VLESS)
{
string remark = string.Empty;
if (!Utils.IsNullOrEmpty(item.remarks))
{
remark = "#" + Utils.UrlEncode(item.remarks);
}
var dicQuery = new Dictionary<string, string>();
if (!Utils.IsNullOrEmpty(item.flow))
{
dicQuery.Add("flow", item.flow);
}
if (!Utils.IsNullOrEmpty(item.security))
{
dicQuery.Add("encryption", item.security);
}
else
{
dicQuery.Add("encryption", "none");
}
if (!Utils.IsNullOrEmpty(item.streamSecurity))
{
dicQuery.Add("security", item.streamSecurity);
}
else
{
dicQuery.Add("security", "none");
}
if (!Utils.IsNullOrEmpty(item.sni))
{
dicQuery.Add("sni", item.sni);
}
if (!Utils.IsNullOrEmpty(item.network))
{
dicQuery.Add("type", item.network);
}
else
{
dicQuery.Add("type", "tcp");
}
switch (item.network)
{
case "tcp":
if (!Utils.IsNullOrEmpty(item.headerType))
{
dicQuery.Add("headerType", item.headerType);
}
else
{
dicQuery.Add("headerType", "none");
}
if (!Utils.IsNullOrEmpty(item.requestHost))
{
dicQuery.Add("host", Utils.UrlEncode(item.requestHost));
}
break;
case "kcp":
if (!Utils.IsNullOrEmpty(item.headerType))
{
dicQuery.Add("headerType", item.headerType);
}
else
{
dicQuery.Add("headerType", "none");
}
if (!Utils.IsNullOrEmpty(item.path))
{
dicQuery.Add("seed", Utils.UrlEncode(item.path));
}
break;
case "ws":
if (!Utils.IsNullOrEmpty(item.requestHost))
{
dicQuery.Add("host", Utils.UrlEncode(item.requestHost));
}
if (!Utils.IsNullOrEmpty(item.path))
{
dicQuery.Add("path", Utils.UrlEncode(item.path));
}
break;
case "http":
case "h2":
dicQuery["type"] = "http";
if (!Utils.IsNullOrEmpty(item.requestHost))
{
dicQuery.Add("host", Utils.UrlEncode(item.requestHost));
}
if (!Utils.IsNullOrEmpty(item.path))
{
dicQuery.Add("path", Utils.UrlEncode(item.path));
}
break;
case "quic":
if (!Utils.IsNullOrEmpty(item.headerType))
{
dicQuery.Add("headerType", item.headerType);
}
else
{
dicQuery.Add("headerType", "none");
}
dicQuery.Add("quicSecurity", Utils.UrlEncode(item.requestHost));
dicQuery.Add("key", Utils.UrlEncode(item.path));
break;
case "grpc":
if (!Utils.IsNullOrEmpty(item.path))
{
dicQuery.Add("serviceName", Utils.UrlEncode(item.path));
if (item.headerType == Global.GrpcgunMode || item.headerType == Global.GrpcmultiMode)
{
dicQuery.Add("mode", Utils.UrlEncode(item.headerType));
}
}
break;
}
string query = "?" + string.Join("&", dicQuery.Select(x => x.Key + "=" + x.Value).ToArray());
url = string.Format("{0}@{1}:{2}",
item.id,
GetIpv6(item.address),
item.port);
url = string.Format("{0}{1}{2}{3}", Global.vlessProtocol, url, query, remark);
}
else
{
}
return url;
}
catch
{
return "";
}
}
19
Source : GodotOnReadySourceGenerator.cs
with MIT License
from 31
with MIT License
from 31
public void Execute(GeneratorExecutionContext context)
{
// If this isn't working, run 'dotnet build-server shutdown' first.
if (Environment
.GetEnvironmentVariable($"Debug{nameof(GodotOnReadySourceGenerator)}") == "true")
{
Debugger.Launch();
}
var receiver = context.SyntaxReceiver as OnReadyReceiver ?? throw new Exception();
INamedTypeSymbol GetSymbolByName(string fullName) =>
context.Compilation.GetTypeByMetadataName(fullName)
?? throw new Exception($"Can't find {fullName}");
var onReadyGetSymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyGetAttribute");
var onReadySymbol = GetSymbolByName("GodotOnReady.Attributes.OnReadyAttribute");
var generateDataSelectorEnumSymbol =
GetSymbolByName("GodotOnReady.Attributes.GenerateDataSelectorEnumAttribute");
var resourceSymbol = GetSymbolByName("Godot.Resource");
var nodeSymbol = GetSymbolByName("Godot.Node");
List<PartialClreplacedAddition> additions = new();
var clreplacedSymbols = receiver.AllClreplacedes
.Select(clreplacedDecl =>
{
INamedTypeSymbol? clreplacedSymbol = context.Compilation
.GetSemanticModel(clreplacedDecl.SyntaxTree)
.GetDeclaredSymbol(clreplacedDecl);
if (clreplacedSymbol is null)
{
context.ReportDiagnostic(
Diagnostic.Create(
new DiagnosticDescriptor(
"GORSG0001",
"Inspection",
$"Unable to find declared symbol for {clreplacedDecl}. Skipping.",
"GORSG.Parsing",
DiagnosticSeverity.Warning,
true
),
clreplacedDecl.GetLocation()
)
);
}
return clreplacedSymbol;
})
.Distinct(SymbolEqualityComparer.Default)
.OfType<INamedTypeSymbol>();
foreach (var clreplacedSymbol in clreplacedSymbols)
{
foreach (var attribute in clreplacedSymbol.GetAttributes()
.Where(a => Equal(a.AttributeClreplaced, generateDataSelectorEnumSymbol)))
{
var fields = clreplacedSymbol.GetMembers()
.OfType<IFieldSymbol>()
.Where(f => f.IsReadOnly && f.IsStatic)
.ToArray();
additions.Add(new DataSelectorEnumAddition(
fields,
new AttributeSite(clreplacedSymbol, attribute)));
}
var members = Enumerable
.Concat(
clreplacedSymbol.GetMembers().OfType<IPropertySymbol>().Select(MemberSymbol.Create),
clreplacedSymbol.GetMembers().OfType<IFieldSymbol>().Select(MemberSymbol.Create))
.ToArray();
foreach (var member in members)
{
foreach (var attribute in member.Symbol
.GetAttributes()
.Where(a => Equal(a.AttributeClreplaced, onReadyGetSymbol)))
{
var site = new MemberAttributeSite(
member,
new AttributeSite(clreplacedSymbol, attribute));
if (site.AttributeSite.Attribute.NamedArguments.Any(
a => a.Key == "Property" && a.Value.Value is string { Length: > 0 }))
{
additions.Add(new OnReadyGetNodePropertyAddition(site));
}
else if (member.Type.IsOfBaseType(nodeSymbol))
{
additions.Add(new OnReadyGetNodeAddition(site));
}
else if (member.Type.IsOfBaseType(resourceSymbol))
{
additions.Add(new OnReadyGetResourceAddition(site));
}
else
{
string issue =
$"The type '{member.Type}' of '{member.Symbol}' is not supported." +
" Expected a Resource or Node subclreplaced.";
context.ReportDiagnostic(
Diagnostic.Create(
new DiagnosticDescriptor(
"GORSG0002",
"Inspection",
issue,
"GORSG.Parsing",
DiagnosticSeverity.Error,
true
),
member.Symbol.Locations.FirstOrDefault()
)
);
}
}
}
foreach (var methodSymbol in clreplacedSymbol.GetMembers().OfType<IMethodSymbol>())
{
foreach (var attribute in methodSymbol
.GetAttributes()
.Where(a => Equal(a.AttributeClreplaced, onReadySymbol)))
{
additions.Add(new OnReadyAddition(methodSymbol, attribute, clreplacedSymbol));
}
}
}
foreach (var clreplacedAdditionGroup in additions.GroupBy(a => a.Clreplaced))
{
SourceStringBuilder source = CreateInitializedSourceBuilder();
if (clreplacedAdditionGroup.Key is not { } clreplacedSymbol) continue;
source.NamespaceBlockBraceIfExists(clreplacedSymbol.GetSymbolNamespaceName(), () =>
{
source.Line("public partial clreplaced ", clreplacedAdditionGroup.Key.Name);
source.BlockBrace(() =>
{
foreach (var addition in clreplacedAdditionGroup)
{
addition.DeclarationWriter?.Invoke(source);
}
if (clreplacedAdditionGroup.Any(a => a.ConstructorStatementWriter is not null))
{
source.Line();
source.Line("public ", clreplacedAdditionGroup.Key.Name, "()");
source.BlockBrace(() =>
{
foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
{
addition.ConstructorStatementWriter?.Invoke(source);
}
source.Line("Constructor();");
});
source.Line("partial void Constructor();");
}
if (clreplacedAdditionGroup.Any(a => a.OnReadyStatementWriter is not null))
{
source.Line();
source.Line("public override void _Ready()");
source.BlockBrace(() =>
{
source.Line("base._Ready();");
// OrderBy is a stable sort.
// Sort by Order, then by discovery order (implicitly).
foreach (var addition in clreplacedAdditionGroup.OrderBy(a => a.Order))
{
addition.OnReadyStatementWriter?.Invoke(source);
}
});
}
});
foreach (var addition in clreplacedAdditionGroup)
{
addition.OutsideClreplacedStatementWriter?.Invoke(source);
}
});
string escapedNamespace =
clreplacedAdditionGroup.Key.GetSymbolNamespaceName()?.Replace(".", "_") ?? "";
context.AddSource(
$"Partial_{escapedNamespace}_{clreplacedAdditionGroup.Key.Name}",
source.ToString());
}
}
19
Source : SlnWriter.cs
with MIT License
from 3F
with MIT License
from 3F
public void Write(IEnumerable<ISection> sections)
{
sections = sections.Select(s => s.Clone()).ToArray();
Validate(sections);
WritableSections(sections).ForEach(s => Write(s));
}
19
Source : XProjectEnv.cs
with MIT License
from 3F
with MIT License
from 3F
public IXProject[] XProjectsByGuid(string guid)
{
return Projects?.Where(p => p.ProjectGuid == guid).ToArray();
}
19
Source : XProjectEnv.cs
with MIT License
from 3F
with MIT License
from 3F
public IXProject[] XProjectsByName(string name, IConfPlatform cfg)
{
return Projects?.Where(
p => Eq(p.Projecreplacedem.projectConfig, cfg) && p.ProjectName == name
)
.ToArray();
}
19
Source : XProjectEnv.cs
with MIT License
from 3F
with MIT License
from 3F
public IXProject[] XProjectsByName(string name)
{
return Projects?.Where(p => p.ProjectName == name).ToArray();
}
19
Source : XProjectEnv.cs
with MIT License
from 3F
with MIT License
from 3F
public IEnumerable<IXProject> replacedign(IEnumerable<Project> projects = null)
{
return (projects ?? ValidProjects).Select(p => AddOrGet(p)).ToArray();
}
19
Source : XProjectEnv.cs
with MIT License
from 3F
with MIT License
from 3F
public void UnloadAll(bool throwIfErr = true)
{
LSender.Send(this, $"Release all loaded projects for current environment (total: {PrjCollection.LoadedProjects.Count})", Message.Level.Debug);
if(PrjCollection.LoadedProjects.Count < 1) { // nothing to release, thus we need only to reset xp collection
xpProjects.Clear();
return;
}
foreach(var xp in Projects.ToArray())
{
if(!Unload(xp) && throwIfErr) {
throw new UnloadException<IXProject>($"Failed unload: '{xp.ProjectGuid}:{xp.Projecreplacedem.projectConfig}'", xp);
}
}
LSender.Send(this, $"Collection now contains '{PrjCollection.LoadedProjects.Count}' loaded projects.", Message.Level.Debug);
}
19
Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r
with GNU General Public License v3.0
from 3xpl01tc0d3r
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
19
Source : MainWindow.xaml.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
private void ButtonRestoreViewport_Click(object sender, RoutedEventArgs e)
{
string[] scoords = Properties.Settings.Default.ViewPortPos.Split(';');
try
{
IEnumerable<double> coords = scoords.Select(s => double.Parse(s));
viewport.Camera.Position = new Vector3(coords.Take(3).ToArray()).ToPoint3D();
viewport.Camera.LookDirection = new Vector3(coords.Skip(3).ToArray()).ToVector3D();
viewport.Camera.UpDirection = new System.Windows.Media.Media3D.Vector3D(0, 0, 1);
}
catch
{
ButtonResetViewport_Click(null, null);
}
}
19
Source : AssetBundleManager.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public string[] ComputeUpdatereplacedets()
{
List<string> keyList = new List<string>();
foreach (KeyValuePair<string, replacedetBundleData> item in serverreplacedetBundleConfig.replacedetBundleDataDict)
{
if (!localreplacedetBundleConfig.replacedetBundleDataDict.ContainsKey(item.Key))
{
keyList.Add(item.Key);
}
if (item.Value.replacedetBundleHash != localreplacedetBundleConfig.replacedetBundleDataDict[item.Key].replacedetBundleHash)
{
keyList.Add(item.Key);
}
if (item.Value.replacedetBundleCRC != localreplacedetBundleConfig.replacedetBundleDataDict[item.Key].replacedetBundleCRC)
{
keyList.Add(item.Key);
}
}
return keyList.Distinct().ToArray();
}
19
Source : LastNames.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static IDictionary<Continent, string[]> RemoveDuplicates(Dictionary<Continent, string[]> perContinent)
{
var result = new Dictionary<Continent, string[]>();
foreach (var continent in perContinent.Keys)
{
result[continent] = perContinent[continent].Distinct().ToArray();
}
return result;
}
19
Source : LoremFuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public string GenerateSentence(int? nbOfWords = null)
{
nbOfWords = nbOfWords ?? 6;
if(nbOfWords < MinNumberOfWordsInASentence)
{
throw new ArgumentOutOfRangeException(nameof(nbOfWords), "A sentence must have more than 1 word.");
}
var words = GenerateWords(nbOfWords.Value).ToArray();
var firstWordCapitalized = words.First().FirstCharToUpper();
words[0] = firstWordCapitalized;
var sentence = $"{string.Join(" ", words)}.";
return sentence;
}
19
Source : ReflectionExtensions.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public static ConstructorInfo GetConstructorWithBiggestNumberOfParameters(this Type type)
{
var constructors = type.GetConstructorsOrderedByNumberOfParametersDesc().ToArray();
if (!constructors.Any())
{
return null;
}
return constructors.First();
}
19
Source : Fuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static Maybe<int> LastChanceToFindNotAlreadyProvidedInteger(SortedSet<object> alreadyProvidedValues, int? minValue, int? maxValue, IFuzz fuzzer)
{
minValue = minValue ?? int.MinValue;
maxValue = maxValue ?? int.MaxValue;
var allPossibleValues = Enumerable.Range(minValue.Value, maxValue.Value).ToArray();
var remainingCandidates = allPossibleValues.Except<int>(alreadyProvidedValues.Cast<int>()).ToArray();
if (remainingCandidates.Any())
{
var pickOneFrom = fuzzer.PickOneFrom<int>(remainingCandidates);
return new Maybe<int>(pickOneFrom);
}
return new Maybe<int>();
}
19
Source : Fuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static Maybe<long> LastChanceToFindNotAlreadyProvidedLong(ref long? minValue, ref long? maxValue, SortedSet<object> alreadyProvidedValues, IFuzz fuzzer)
{
minValue = minValue ?? long.MinValue;
maxValue = maxValue ?? long.MaxValue;
var allPossibleValues = GenerateAllPossibleOptions(minValue.Value, maxValue.Value);
var remainingCandidates = allPossibleValues.Except<long>(alreadyProvidedValues.Cast<long>()).ToArray();
if (remainingCandidates.Any())
{
var index = fuzzer.GenerateInteger(0, remainingCandidates.Length - 1);
var randomRemainingNumber = remainingCandidates[index];
return new Maybe<long>(randomRemainingNumber);
}
return new Maybe<long>();
}
19
Source : Fuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static Maybe<int> LastChanceToFindAge(SortedSet<object> alreadyProvidedValues, int minAge, int maxAge, IFuzz fuzzer)
{
var allPossibleValues = Enumerable.Range(minAge, maxAge - minAge).ToArray();
var remainingCandidates = allPossibleValues.Except(alreadyProvidedValues.Cast<int>()).ToArray();
if (remainingCandidates.Any())
{
var pickOneFrom = fuzzer.PickOneFrom<int>(remainingCandidates);
return new Maybe<int>(pickOneFrom);
}
return new Maybe<int>();
}
19
Source : Fuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private static Maybe<T> LastChanceToFindNotAlreadyPickedValue<T>(SortedSet<object> alreadyProvidedValues, IList<T> candidates, IFuzz fuzzer)
{
var allPossibleValues = candidates.ToArray();
var remainingCandidates = allPossibleValues.Except<T>(alreadyProvidedValues.Cast<T>()).ToArray();
if (remainingCandidates.Any())
{
var index = fuzzer.GenerateInteger(0, remainingCandidates.Length - 1);
var pickOneFrom = remainingCandidates[index];
return new Maybe<T>(pickOneFrom);
}
return new Maybe<T>();
}
19
Source : NoDuplicationFuzzersShould.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
[Test]
public void Be_able_to_pick_always_different_values_from_a_medium_size_list_of_int()
{
var fuzzer = new Fuzzer(noDuplication: true);
var candidates = Enumerable.Range(-10000, 10000).ToArray();
CheckThatNoDuplicationIsMadeWhileGenerating(fuzzer, candidates.LongLength, () =>
{
return fuzzer.PickOneFrom(candidates);
});
}
19
Source : Tlv.cs
with MIT License
from 499116344
with MIT License
from 499116344
private static byte[] GetBytes(string hexString)
{
return Enumerable
.Range(0, hexString.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
.ToArray();
}
19
Source : GeographyExpert.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public static string[] GiveMeCitiesOf(Country country)
{
return CitiesOfTheWorld
.Where(cw => cw.Country == country)
.Select(x => x.CityName)
.Distinct()
.ToArray();
}
19
Source : GeographyExpert.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
public static StateProvinceArea[] GiveMeStateProvinceAreaOf(Country country)
{
return CitiesOfTheWorld
.Where(cw => cw.Country == country)
.Select(x => x.StateProvinceArea)
.Distinct()
.ToArray();
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, ushort v)
{
bw.Write(BitConverter.GetBytes(v).Reverse().ToArray());
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, char v)
{
bw.Write(BitConverter.GetBytes((ushort) v).Reverse().ToArray());
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, int v)
{
bw.Write(BitConverter.GetBytes(v).Reverse().ToArray());
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, long v)
{
bw.Write(BitConverter.GetBytes((uint) v).Reverse().ToArray());
}
19
Source : Util.cs
with MIT License
from 499116344
with MIT License
from 499116344
public static void BeWrite(this BinaryWriter bw, ulong v)
{
bw.Write(BitConverter.GetBytes((uint) v).Reverse().ToArray());
}
19
Source : ValuesController.cs
with MIT License
from 42skillz
with MIT License
from 42skillz
private static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
19
Source : TypeExtensions.cs
with MIT License
from 52ABP
with MIT License
from 52ABP
public static T[] GetAttributes<T>(this MemberInfo memberInfo, bool inherit = false) where T : Attribute
{
return memberInfo.GetCustomAttributes(typeof (T), inherit).Cast<T>().ToArray();
}
19
Source : SimulationDevice.cs
with MIT License
from 5argon
with MIT License
from 5argon
public void OnBeforeSerialize()
{
if (orientations == null) return;
orientationKeys = orientations.Keys.ToArray();
orientationValues = orientations.Values.ToArray();
}
19
Source : CommandTree.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
private void _run(string[] commands, int index) {
if (commands.Length == index) {
RunCommand(emptyArgs);
return;
}
string token = commands[index].ToLower();
if (!m_subcommands.ContainsKey(token)) {
RunCommand(commands.Skip(index).ToArray());
return;
}
m_subcommands[token]._run(commands, index + 1);
}
19
Source : OrderByClause.cs
with MIT License
from 71
with MIT License
from 71
public static OrderByClause OrderBy(IEnumerable<OrderingExpression> orderings)
{
if (orderings == null)
throw new ArgumentNullException(nameof(orderings));
if (orderings.Contains(null))
throw new ArgumentNullException(nameof(orderings));
return new OrderByClause(orderings.ToArray());
}
19
Source : SimulationDatabase.cs
with MIT License
from 5argon
with MIT License
from 5argon
internal static void Refresh()
{
if (db == null) db = new Dictionary<string, SimulationDevice>();
db.Clear();
var deviceDirectory = new System.IO.DirectoryInfo(NotchSimulatorUtility.DevicesFolder);
if (!deviceDirectory.Exists) return;
var deviceDefinitions = deviceDirectory.GetFiles("*.device.json");
foreach (var deviceDefinition in deviceDefinitions)
{
SimulationDevice deviceInfo;
using (var sr = deviceDefinition.OpenText())
{
deviceInfo = JsonUtility.FromJson<SimulationDevice>(sr.ReadToEnd());
}
db.Add(deviceInfo.Meta.friendlyName, deviceInfo);
}
KeyList = db.Keys.ToArray();
}
See More Examples