Here are the examples of the csharp api System.Reflection.MemberInfo.GetCustomAttribute() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2142 Examples
19
View Source File : XnaToFnaUtil.Processor.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public void SetupHooks() {
// To use XnaToFnaGame properly, the actual game override needs to call XnaToFnaGame::.ctor as "base" instead.
Modder.RelinkMap["System.Void Microsoft.Xna.Framework.Game::.ctor()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaGame", "System.Void .ctor()");
Modder.ForceCallMap["System.Void XnaToFna.XnaToFnaGame::.ctor()"] = OpCodes.Call;
foreach (MethodInfo method in typeof(XnaToFnaGame).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
Modder.RelinkMap[method.GetFindableID(type: "Microsoft.Xna.Framework.Game")] =
new RelinkMapEntry("XnaToFna.XnaToFnaGame", method.GetFindableID(withType: false));
Modder.ForceCallMap[method.GetFindableID(withType: true)] = OpCodes.Call;
}
// XNA games expect a WinForms handle. Give it a "proxy" handle instead.
if (HookCompat) {
Modder.RelinkMap["System.IntPtr Microsoft.Xna.Framework.GameWindow::get_Handle()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.IntPtr GetProxyFormHandle(Microsoft.Xna.Framework.GameWindow)");
}
// X360 games can be larger than the screen. Allow the user to "fix" this by forcing a display resolution via env vars.
if (HookHacks) {
Modder.RelinkMap["System.Void Microsoft.Xna.Framework.GraphicsDeviceManager::ApplyChanges()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.Void ApplyChanges(Microsoft.Xna.Framework.GraphicsDeviceManager)");
}
// Let's just completely wreck everything.
foreach (Type type in typeof(Form).replacedembly.GetTypes()) {
string name = type.FullName;
// Subsreplacedute WinForms for ProxyForms
if (HookCompat && name.StartsWith("XnaToFna.ProxyForms."))
Modder.RelinkMap["System.Windows.Forms." + name.Substring(9 + 11)] = name;
// Subsreplacedute common Drawing clreplacedes (f.e. Rectangle) with our own for Drawing-less environments (f.e. Android)
else if (HookCompat && name.StartsWith("XnaToFna.ProxyDrawing."))
Modder.RelinkMap["System.Drawing." + name.Substring(9 + 13)] = name;
// Some XNA games use DInput... let's just subsreplacedute all DInput references with our ProxyDInput.
else if (name.StartsWith("XnaToFna.ProxyDInput."))
Modder.RelinkMap[/* no namespace */ name.Substring(9 + 12)] = name;
// Some X360 games use Microsoft.Xna.Framework.Xdk; let's just stub whatever's required in XTF.
else if (name.StartsWith("XnaToFna.StubXDK.")) {
string nameXDK = "Microsoft.Xna.Framework." + name.Substring(9 + 8);
Modder.RelinkMap[nameXDK] = name;
// Unfortunately, the signatures refer to GamerServices, while XnaToFna itself can't refer to that.
// Let's abuse the MonoModHook attribtue.
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) {
MonoModHook hook = method.GetCustomAttribute<MonoModHook>();
if (hook != null) {
Modder.RelinkMap[hook.FindableID] = new RelinkMapEntry(name, method.GetFindableID(withType: false));
}
}
foreach (ConstructorInfo ctor in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) {
MonoModHook hook = ctor.GetCustomAttribute<MonoModHook>();
if (hook != null) {
Modder.RelinkMap[hook.FindableID] = new RelinkMapEntry(name, ctor.GetFindableID(withType: false));
}
}
}
}
if (HookHacks)
Modder.RelinkMap["System.Boolean Microsoft.Xna.Framework.GamerServices.Guide::get_IsTrialMode()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.IntPtr get_IsTrialMode()");
if (HookBinaryFormatter) {
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::.ctor()"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter Create()");
// The longest relink mapping ever seen...
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::.ctor(System.Runtime.Serialization.ISurrogateSelector,System.Runtime.Serialization.StreamingContext)"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter Create(System.Runtime.Serialization.ISurrogateSelector,System.Runtime.Serialization.StreamingContext)");
Modder.RelinkMap["System.Runtime.Serialization.SerializationBinder System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::get_Binder()"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.SerializationBinder get_Binder(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter)");
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::set_Binder(System.Runtime.Serialization.SerializationBinder)"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Void set_Binder(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,System.Runtime.Serialization.SerializationBinder)");
}
if (HookReflection) {
Modder.RelinkMap["System.Reflection.FieldInfo System.Type::GetField(System.String,System.Reflection.BindingFlags)"] =
new RelinkMapEntry("XnaToFna.ProxyReflection.FieldInfoHelper", "System.Reflection.FieldInfo GetField(System.Type,System.String,System.Reflection.BindingFlags)");
Modder.RelinkMap["System.Reflection.FieldInfo System.Type::GetField(System.String)"] =
new RelinkMapEntry("XnaToFna.ProxyReflection.FieldInfoHelper", "System.Reflection.FieldInfo GetField(System.Type,System.String)");
}
// X360 uses the ".NET Compact Framework", which actually ships with some additional stuff...
Modder.RelinkMap["System.Void System.Threading.Thread::SetProcessorAffinity(System.Int32[])"] =
new RelinkMapEntry("XnaToFna.X360Helper", "System.Void SetProcessorAffinity(System.Threading.Thread,System.Int32[])");
}
19
View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private static SyntaxList<MemberDeclarationSyntax> GenerateNamespace(Type type)
{
var serviceNameAttr = type.GetCustomAttribute<ServiceDiscoveryNameAttribute>();
var namespaceDeclaration = SyntaxFactory.NamespaceDeclaration(GenerateQualifiedNameSyntax("Uragano.DynamicProxy.UraganoProxy"));
return GenerateClreplaced(namespaceDeclaration, type, serviceNameAttr.Name);
}
19
View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private static MemberDeclarationSyntax[] GenerateMethods(Type type, string clreplacedName, string serviceName)
{
var typeAttr = type.GetCustomAttribute<ServiceRouteAttribute>();
var routePrefix = typeAttr == null ? $"{type.Namespace}/{type.Name}" : typeAttr.Route;
var methods = type.GetMethods().ToList();
var s = methods.Select(p => GenerateMethod(routePrefix, p, serviceName)).ToList();
s.Insert(0, GenerateConstructorDeclaration(clreplacedName));
return s.ToArray();
}
19
View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
private static MemberDeclarationSyntax GenerateMethod(string routePrefix, MethodInfo methodInfo, string serviceName)
{
if (methodInfo.ReturnType.Namespace != typeof(Task).Namespace)
throw new NotSupportedException($"Only support proxy asynchronous methods.[{methodInfo.DeclaringType?.Namespace}.{methodInfo.DeclaringType?.Name}.{methodInfo.Name}]");
var methodAttr = methodInfo.GetCustomAttribute<ServiceRouteAttribute>();
var serviceRoute = $"{routePrefix}/{(methodAttr == null ? methodInfo.Name : methodAttr.Route)}";
var returnDeclaration = GenerateType(methodInfo.ReturnType);
var argDeclarations = new List<SyntaxNodeOrToken>();
foreach (var arg in methodInfo.GetParameters())
{
argDeclarations.Add(arg.ParameterType.IsGenericType
? SyntaxFactory.Parameter(SyntaxFactory.Identifier(arg.Name))
.WithType(GenerateType(arg.ParameterType))
: SyntaxFactory.Parameter(SyntaxFactory.Identifier(arg.Name))
.WithType(GenerateQualifiedNameSyntax(arg.ParameterType)));
argDeclarations.Add(SyntaxFactory.Token(SyntaxKind.CommaToken));
}
if (argDeclarations.Any())
{
argDeclarations.RemoveAt(argDeclarations.Count - 1);
}
//Generate return type.
var methodDeclaration = SyntaxFactory.MethodDeclaration(methodInfo.ReturnType == typeof(void) ? SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)) : returnDeclaration, SyntaxFactory.Identifier(methodInfo.Name));
if (methodInfo.ReturnType.Namespace == typeof(Task).Namespace)
{
methodDeclaration = methodDeclaration.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword),
SyntaxFactory.Token(SyntaxKind.AsyncKeyword)));
}
else
{
methodDeclaration = methodDeclaration.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)));
}
methodDeclaration = methodDeclaration.WithParameterList(
SyntaxFactory.ParameterList(SyntaxFactory.SeparatedList<ParameterSyntax>(argDeclarations)));
ExpressionSyntax expressionSyntax;
if (methodInfo.ReturnType == typeof(Task))
{
expressionSyntax = SyntaxFactory.IdentifierName("InvokeAsync");
}
else
{
expressionSyntax = SyntaxFactory.GenericName(SyntaxFactory.Identifier("InvokeAsync"))
.WithTypeArgumentList(((GenericNameSyntax)returnDeclaration).TypeArgumentList);
}
var argNames = methodInfo.GetParameters().Select(p => SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(p.Name))).ToList();
var token = new SyntaxNodeOrToken[]
{
SyntaxFactory.Argument(SyntaxFactory
.ArrayCreationExpression(SyntaxFactory
.ArrayType(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword)))
.WithRankSpecifiers(SyntaxFactory.SingletonList(
SyntaxFactory.ArrayRankSpecifier(
SyntaxFactory.SingletonSeparatedList<ExpressionSyntax>(
SyntaxFactory.OmittedArraySizeExpression())))))
.WithInitializer(SyntaxFactory.InitializerExpression(SyntaxKind.CollectionInitializerExpression,
SyntaxFactory.SeparatedList<ExpressionSyntax>(argNames)))),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression,
SyntaxFactory.Literal(serviceRoute))),
SyntaxFactory.Token(SyntaxKind.CommaToken),
SyntaxFactory.Argument(
SyntaxFactory.LiteralExpression(
SyntaxKind.StringLiteralExpression,
SyntaxFactory.Literal(serviceName)))
};
expressionSyntax = SyntaxFactory.AwaitExpression(SyntaxFactory.InvocationExpression(expressionSyntax)
.WithArgumentList(
SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList<ArgumentSyntax>(token))
));
StatementSyntax statementSyntax;
if (methodInfo.ReturnType != typeof(Task) && methodInfo.ReturnType != typeof(void))
{
statementSyntax = SyntaxFactory.ReturnStatement(expressionSyntax);
}
else
{
statementSyntax = SyntaxFactory.ExpressionStatement(expressionSyntax);
}
return methodDeclaration.WithBody(SyntaxFactory.Block(SyntaxFactory.SingletonList(statementSyntax)));
}
19
View Source File : ServiceFactory.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public void Create(string route, MethodInfo serverMethodInfo, MethodInfo clientMethodInfo, List<Type> serverInterceptors, List<Type> clientInterceptors)
{
if (ServiceInvokers.ContainsKey(route))
throw new DuplicateRouteException(route);
var enableClient = ServiceProvider.GetService<ILoadBalancing>() != null;
ServiceCircuitBreakerOptions breaker = null;
CachingConfig cachingConfig = null;
if (enableClient)
{
#region Circuit breaker
var nonCircuitBreakerAttr = clientMethodInfo.GetCustomAttribute<NonCircuitBreakerAttribute>();
if (nonCircuitBreakerAttr == null)
{
var circuitBreakerAttr = clientMethodInfo.GetCustomAttribute<CircuitBreakerAttribute>();
var globalCircuitBreaker = UraganoSettings.CircuitBreakerOptions;
if (globalCircuitBreaker != null || circuitBreakerAttr != null)
{
breaker = new ServiceCircuitBreakerOptions();
if (globalCircuitBreaker != null)
{
breaker.Timeout = globalCircuitBreaker.Timeout;
breaker.Retry = globalCircuitBreaker.Retry;
breaker.ExceptionsAllowedBeforeBreaking =
globalCircuitBreaker.ExceptionsAllowedBeforeBreaking;
breaker.DurationOfBreak = globalCircuitBreaker.DurationOfBreak;
breaker.MaxParallelization = globalCircuitBreaker.MaxParallelization;
breaker.MaxQueuingActions = globalCircuitBreaker.MaxQueuingActions;
}
if (circuitBreakerAttr != null)
{
if (circuitBreakerAttr.TimeoutMilliseconds > -1)
breaker.Timeout = TimeSpan.FromMilliseconds(circuitBreakerAttr.TimeoutMilliseconds);
if (circuitBreakerAttr.Retry > -1)
breaker.Retry = circuitBreakerAttr.Retry;
if (circuitBreakerAttr.ExceptionsAllowedBeforeBreaking > -1)
breaker.ExceptionsAllowedBeforeBreaking =
circuitBreakerAttr.ExceptionsAllowedBeforeBreaking;
if (circuitBreakerAttr.DurationOfBreakSeconds > -1)
breaker.DurationOfBreak = TimeSpan.FromSeconds(circuitBreakerAttr.DurationOfBreakSeconds);
if (!string.IsNullOrWhiteSpace(circuitBreakerAttr.FallbackExecuteScript))
{
breaker.HasInjection = true;
ScriptInjection.AddScript(route, circuitBreakerAttr.FallbackExecuteScript,
circuitBreakerAttr.ScriptUsingNameSpaces);
}
if (circuitBreakerAttr.MaxParallelization > -1)
breaker.MaxParallelization = circuitBreakerAttr.MaxParallelization;
if (circuitBreakerAttr.MaxQueuingActions > -1)
breaker.MaxQueuingActions = circuitBreakerAttr.MaxQueuingActions;
}
}
}
#endregion
#region Caching
//Must have a method of returning a value.
if (UraganoSettings.CachingOptions != null && clientMethodInfo.ReturnType != typeof(Task) && clientMethodInfo.GetCustomAttribute<NonCachingAttribute>() == null && clientMethodInfo.DeclaringType?.GetCustomAttribute<NonCachingAttribute>() == null)
{
var attr = clientMethodInfo.GetCustomAttribute<CachingAttribute>();
var keyGenerator = ServiceProvider.GetRequiredService<ICachingKeyGenerator>();
var key = keyGenerator.GenerateKeyPlaceholder(UraganoSettings.CachingOptions.KeyPrefix, UraganoSettings.CachingOptions.ExpireSeconds, route, clientMethodInfo, attr);
cachingConfig = new CachingConfig(key, attr != null && !string.IsNullOrWhiteSpace(attr.Key), attr != null && attr.ExpireSeconds != -1 ? attr.ExpireSeconds : UraganoSettings.CachingOptions.ExpireSeconds);
}
#endregion
}
var serviceDescriptor = new ServiceDescriptor(route, serverMethodInfo, clientMethodInfo, serverMethodInfo == null ? null : new MethodInvoker(serverMethodInfo), serverInterceptors, clientInterceptors, breaker, cachingConfig);
ServiceInvokers.TryAdd(route, serviceDescriptor);
}
19
View Source File : RtmpServerBuilder.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public RtmpServer Build()
{
_options = _options ?? new RtmpServerOptions();
_options.Startup = _startup;
var types = replacedembly.GetCallingreplacedembly().GetTypes();
var registerInternalControllers = true;
_websocketOptions._serverOptions = _options;
foreach (var type in types)
{
var neverRegister = type.GetCustomAttribute<NeverRegisterAttribute>();
if (neverRegister != null)
{
continue;
}
if (typeof(NetStream).IsreplacedignableFrom(type) && !type.IsAbstract)
{
_options.RegisterStream(type);
}
else if (typeof(RtmpController).IsreplacedignableFrom(type) && !type.IsAbstract)
{
_options.RegisterController(type);
}
if (typeof(LivingController).IsreplacedignableFrom(type))
{
registerInternalControllers = false;
}
if (_useWebSocket)
{
if (typeof(WebSocketController).IsreplacedignableFrom(type) && !type.IsAbstract)
{
_websocketOptions.RegisterController(type);
}
if (typeof(WebSocketPlayController).IsreplacedignableFrom(type))
{
registerInternalControllers = false;
}
}
}
if (registerInternalControllers)
{
_options.RegisterController<LivingController>();
_options.RegisterStream<LivingStream>();
_options.RegisterStream<RecordStream>();
_options.RegisterController<RecordController>();
if (_useWebSocket)
{
_websocketOptions.RegisterController<WebSocketPlayController>();
}
}
if (_useSsl)
{
_options.Cert = _cert;
}
_options.CleanupRpcRegistration();
_options.BuildContainer();
var ret = new RtmpServer(_options, _websocketOptions);
return ret;
}
19
View Source File : RtmpServerOptions.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void RegisterMessage<T>(MessageFactory factory) where T : Message
{
var tType = typeof(T);
var attr = tType.GetCustomAttribute<RtmpMessageAttribute>();
if (attr == null)
{
throw new InvalidOperationException();
}
foreach (var messageType in attr.MessageTypes)
{
_messageFactories.Add(messageType, factory);
}
}
19
View Source File : RtmpServerOptions.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void RegisterMessage<T>() where T : Message, new()
{
var tType = typeof(T);
var attr = tType.GetCustomAttribute<RtmpMessageAttribute>();
if (attr == null)
{
throw new InvalidOperationException();
}
foreach (var messageType in attr.MessageTypes)
{
_messageFactories.Add(messageType, (MessageHeader a, SerializationContext b, out int c) =>
{
c = 0;
return new T();
});
}
}
19
View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void WriteBytes(object value, SerializationContext context)
{
uint header = 0;
if (value == null)
{
context.Buffer.WriteToBuffer((byte)Amf3Type.Null);
return;
}
else
{
context.Buffer.WriteToBuffer((byte)Amf3Type.Object);
}
var refIndex = context.ObjectReferenceTable.IndexOf(value);
if (refIndex >= 0)
{
header = (uint)refIndex << 1;
WriteU29BytesImpl(header, context);
return;
}
var objType = value.GetType();
string attrTypeName = null;
var clreplacedAttr = objType.GetCustomAttribute<TypedObjectAttribute>();
if (clreplacedAttr != null)
{
attrTypeName = clreplacedAttr.Name;
}
var traits = new Amf3ClreplacedTraits();
var memberValues = new List<object>();
if (value is AmfObject amf3Object)
{
if (amf3Object.IsAnonymous)
{
traits.ClreplacedName = "";
traits.ClreplacedType = Amf3ClreplacedType.Anonymous;
}
else
{
traits.ClreplacedName = attrTypeName ?? objType.Name;
traits.ClreplacedType = Amf3ClreplacedType.Typed;
}
traits.IsDynamic = amf3Object.IsDynamic;
traits.Members = new List<string>(amf3Object.Fields.Keys);
memberValues = new List<object>(amf3Object.Fields.Keys.Select(k => amf3Object.Fields[k]));
}
else if (value is IExternalizable)
{
traits.ClreplacedName = attrTypeName ?? objType.Name;
traits.ClreplacedType = Amf3ClreplacedType.Externalizable;
}
else
{
traits.ClreplacedName = attrTypeName ?? objType.Name;
traits.ClreplacedType = Amf3ClreplacedType.Typed;
var props = objType.GetProperties();
foreach (var prop in props)
{
var attr = (ClreplacedFieldAttribute)Attribute.GetCustomAttribute(prop, typeof(ClreplacedFieldAttribute));
if (attr != null)
{
traits.Members.Add(attr.Name ?? prop.Name);
memberValues.Add(prop.GetValue(value));
}
}
traits.IsDynamic = value is IDynamicObject;
}
context.ObjectReferenceTable.Add(value);
var traitRefIndex = context.ObjectTraitsReferenceTable.IndexOf(traits);
if (traitRefIndex >= 0)
{
header = ((uint)traitRefIndex << 2) | 0x01;
WriteU29BytesImpl(header, context);
}
else
{
if (traits.ClreplacedType == Amf3ClreplacedType.Externalizable)
{
header = 0x07;
WriteU29BytesImpl(header, context);
WriteStringBytesImpl(traits.ClreplacedName, context, context.StringReferenceTable);
var extObj = value as IExternalizable;
extObj.TryEncodeData(context.Buffer);
return;
}
else
{
header = 0x03;
if (traits.IsDynamic)
{
header |= 0x08;
}
var memberCount = (uint)traits.Members.Count;
header |= memberCount << 4;
WriteU29BytesImpl(header, context);
WriteStringBytesImpl(traits.ClreplacedName, context, context.StringReferenceTable);
foreach (var memberName in traits.Members)
{
WriteStringBytesImpl(memberName, context, context.StringReferenceTable);
}
}
context.ObjectTraitsReferenceTable.Add(traits);
}
foreach (var memberValue in memberValues)
{
WriteValueBytes(memberValue, context);
}
if (traits.IsDynamic)
{
var amf3Obj = value as IDynamicObject;
foreach ((var key, var item) in amf3Obj.DynamicFields)
{
WriteStringBytesImpl(key, context, context.StringReferenceTable);
WriteValueBytes(item, context);
}
WriteStringBytesImpl("", context, context.StringReferenceTable);
}
}
19
View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void WriteBytes<T>(Vector<T> value, SerializationContext context)
{
context.Buffer.WriteToBuffer((byte)Amf3Type.VectorObject);
var refIndex = context.ObjectReferenceTable.IndexOf(value);
if (refIndex >= 0)
{
var header = (uint)refIndex << 1;
WriteU29BytesImpl(header, context);
return;
}
else
{
context.ObjectReferenceTable.Add(value);
var header = ((uint)value.Count << 1) | 0x01;
WriteU29BytesImpl(header, context);
context.Buffer.WriteToBuffer(value.IsFixedSize ? (byte)0x01 : (byte)0x00);
var tType = typeof(T);
string typeName = tType.Name;
var attr = tType.GetCustomAttribute<TypedObjectAttribute>();
if (attr != null)
{
typeName = attr.Name;
}
var clreplacedName = typeof(T) == typeof(object) ? "*" : typeName;
WriteStringBytesImpl(clreplacedName, context, context.StringReferenceTable);
foreach (var i in value)
{
WriteValueBytes(i, context);
}
return;
}
}
19
View Source File : CommandMessage.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void DeserializeAmf0(SerializationContext context)
{
var buffer = context.ReadBuffer.Span;
if (!context.Amf0Reader.TryGetNumber(buffer, out var txid, out var consumed))
{
throw new InvalidOperationException();
}
TranscationID = txid;
buffer = buffer.Slice(consumed);
context.Amf0Reader.TryGetObject(buffer, out var commandObj, out consumed);
CommandObject = commandObj;
buffer = buffer.Slice(consumed);
var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
var i = 0;
while (buffer.Length > 0)
{
if (!context.Amf0Reader.TryGetValue(buffer, out _, out var optArg, out consumed))
{
break;
}
buffer = buffer.Slice(consumed);
optionArguments[i].SetValue(this, optArg);
i++;
if (i >= optionArguments.Count)
{
break;
}
}
}
19
View Source File : CommandMessage.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void DeserializeAmf3(SerializationContext context)
{
var buffer = context.ReadBuffer.Span;
if (!context.Amf3Reader.TryGetDouble(buffer, out var txid, out var consumed))
{
throw new InvalidOperationException();
}
TranscationID = txid;
buffer = buffer.Slice(consumed);
context.Amf3Reader.TryGetObject(buffer, out var commandObj, out consumed);
CommandObject = commandObj as AmfObject;
buffer = buffer.Slice(consumed);
var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
var i = 0;
while (buffer.Length > 0)
{
context.Amf0Reader.TryGetValue(buffer, out _, out var optArg, out _);
optionArguments[i].SetValue(this, optArg);
}
}
19
View Source File : CommandMessage.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void SerializeAmf0(SerializationContext context)
{
using (var writeContext = new Amf.Serialization.Amf0.SerializationContext(context.WriteBuffer))
{
if (ProcedureName == null)
{
ProcedureName = GetType().GetCustomAttribute<RtmpCommandAttribute>().Name;
}
Debug.replacedert(!string.IsNullOrEmpty(ProcedureName));
context.Amf0Writer.WriteBytes(ProcedureName, writeContext);
context.Amf0Writer.WriteBytes(TranscationID, writeContext);
context.Amf0Writer.WriteValueBytes(CommandObject, writeContext);
var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
foreach (var optionArgument in optionArguments)
{
context.Amf0Writer.WriteValueBytes(optionArgument.GetValue(this), writeContext);
}
}
}
19
View Source File : CommandMessage.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void SerializeAmf3(SerializationContext context)
{
using (var writeContext = new Amf.Serialization.Amf3.SerializationContext(context.WriteBuffer))
{
if (ProcedureName == null)
{
ProcedureName = GetType().GetCustomAttribute<RtmpCommandAttribute>().Name;
}
Debug.replacedert(!string.IsNullOrEmpty(ProcedureName));
context.Amf3Writer.WriteBytes(ProcedureName, writeContext);
context.Amf3Writer.WriteBytes(TranscationID, writeContext);
context.Amf3Writer.WriteValueBytes(CommandObject, writeContext);
var optionArguments = GetType().GetProperties().Where(p => p.GetCustomAttribute<OptionalArgumentAttribute>() != null).ToList();
foreach (var optionArgument in optionArguments)
{
context.Amf3Writer.WriteValueBytes(optionArgument.GetValue(this), writeContext);
}
}
}
19
View Source File : CommandMessageFactory.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void RegisterMessage<T>() where T: CommandMessage
{
var tType = typeof(T);
var attr = tType.GetCustomAttribute<RtmpCommandAttribute>();
if (attr == null)
{
throw new InvalidOperationException();
}
_messageFactories.Add(attr.Name, tType);
}
19
View Source File : UserControlMessageFactory.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void RegisterMessage<T>() where T: UserControlMessage, new()
{
var tType = typeof(T);
var attr = tType.GetCustomAttribute<UserControlMessageAttribute>();
if (attr == null)
{
throw new InvalidOperationException();
}
_messageFactories.Add(attr.Type, tType);
}
19
View Source File : RtmpMessageStream.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
internal void RegisterMessageHandler<T>(Action<T> handler) where T: Message
{
var attr = typeof(T).GetCustomAttribute<RtmpMessageAttribute>();
if (attr == null || !attr.MessageTypes.Any())
{
throw new InvalidOperationException("unsupported message type");
}
foreach (var messageType in attr.MessageTypes)
{
if (_messageHandlers.ContainsKey(messageType))
{
throw new InvalidOperationException("message type already registered");
}
_messageHandlers[messageType] = m =>
{
handler(m as T);
};
}
}
19
View Source File : RpcService.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
internal void RegeisterController(Type controllerType)
{
var methods = controllerType.GetMethods();
foreach (var method in methods)
{
var attr = method.GetCustomAttribute<RpcMethodAttribute>();
if (attr != null)
{
var rpcMethod = new RpcMethod();
var methodName = attr.Name ?? method.Name;
var parameters = method.GetParameters();
bool canInvoke = false;
var optArgIndex = 0;
foreach (var para in parameters)
{
var fromCommandObject = para.GetCustomAttribute<FromCommandObjectAttribute>();
var fromOptionalArg = para.GetCustomAttribute<FromOptionalArgumentAttribute>();
var commandObject = para.GetCustomAttribute<CommandObjectAttribute>();
if (fromCommandObject == null && fromOptionalArg == null && commandObject == null)
{
break;
}
canInvoke = true;
if (fromCommandObject != null)
{
var name = fromCommandObject.Key ?? para.Name;
rpcMethod.Parameters.Add(new RpcParameter()
{
CommandObjectKey = name,
IsFromCommandObject = true,
ParameterType = para.ParameterType,
IsOptional = para.IsOptional
});
}
else if (fromOptionalArg != null)
{
rpcMethod.Parameters.Add(new RpcParameter()
{
OptionalArgumentIndex = optArgIndex,
IsFromOptionalArgument = true,
ParameterType = para.ParameterType,
IsOptional = para.IsOptional
});
optArgIndex++;
}
else if (commandObject != null && para.ParameterType.IsreplacedignableFrom(typeof(AmfObject)))
{
rpcMethod.Parameters.Add(new RpcParameter()
{
IsCommandObject = true,
IsOptional = para.IsOptional
});
}
}
if (canInvoke || !parameters.Any())
{
rpcMethod.Method = method;
rpcMethod.MethodName = methodName;
if (!Controllers.TryGetValue(controllerType, out var mapping))
{
Controllers.Add(controllerType, new List<RpcMethod>());
}
Controllers[controllerType].Add(rpcMethod);
}
}
}
}
19
View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void RegisterTypedObject<T>() where T: new()
{
var type = typeof(T);
var props = type.GetProperties();
var fields = props.Where(p => p.CanWrite && Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute)) != null).ToList();
var members = fields.ToDictionary(p => ((ClreplacedFieldAttribute)Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute))).Name ?? p.Name, p => new Action<object, object>(p.SetValue));
if (members.Keys.Where(s => string.IsNullOrEmpty(s)).Any())
{
throw new InvalidOperationException("Field name cannot be empty or null");
}
string mapedName = null;
var attr = type.GetCustomAttribute<TypedObjectAttribute>();
if (attr != null)
{
mapedName = attr.Name;
}
var typeName = mapedName == null ? type.Name : mapedName;
var state = new TypeRegisterState()
{
Members = members,
Type = type
};
_registeredTypes.Add(type);
_registeredTypedObejectStates.Add(typeName, state);
}
19
View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void RegisterExternalizable<T>() where T : IExternalizable, new()
{
var type = typeof(T);
string mapedName = null;
var attr = type.GetCustomAttribute<TypedObjectAttribute>();
if (attr != null)
{
mapedName = attr.Name;
}
var typeName = mapedName == null ? type.Name : mapedName;
_registeredExternalizable.Add(typeName, type);
}
19
View Source File : Amf0Reader.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
public void RegisterType<T>() where T : new()
{
var type = typeof(T);
var props = type.GetProperties();
var fields = props.Where(p => p.CanWrite && Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute)) != null).ToList();
var members = fields.ToDictionary(p => ((ClreplacedFieldAttribute)Attribute.GetCustomAttribute(p, typeof(ClreplacedFieldAttribute))).Name ?? p.Name, p => new Action<object, object>(p.SetValue));
if (members.Keys.Where(s => string.IsNullOrEmpty(s)).Any())
{
throw new InvalidOperationException("Field name cannot be empty or null");
}
string mapedName = null;
var attr = type.GetCustomAttribute<TypedObjectAttribute>();
if (attr != null)
{
mapedName = attr.Name;
}
var typeName = mapedName == null ? type.Name : mapedName;
var state = new TypeRegisterState()
{
Members = members,
Type = type
};
_registeredTypes.Add(type);
_registeredTypeStates.Add(typeName, state);
_amf3Reader.RegisterTypedObject(typeName, state);
}
19
View Source File : VxFormDefinition.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
internal static VxFormDefinition CreateFromModel(object model, VxFormLayoutOptions options)
{
// TODO: EXPANDO SWITCH
var allProperties = VxHelpers.GetModelProperties(model.GetType());
var rootFormDefinition = model.GetType().GetCustomAttribute<VxFormDefinition>();
if (rootFormDefinition == null)
rootFormDefinition = VxFormDefinition.Create();
var defaultGroup = VxFormGroup.Create();
foreach (var prop in allProperties)
{
if (VxFormGroup.IsFormGroup(prop))
{
var nestedModel = prop.GetValue(model);
var formGroup = VxFormGroup.CreateFromModel(nestedModel, options);
formGroup.Label = VxFormGroup.GetFormGroup(prop).Label;
rootFormDefinition.Groups.Add(formGroup);
}
else
{
VxFormGroup.Add(prop.Name, defaultGroup, model, options);
}
}
rootFormDefinition.Groups.Add(defaultGroup);
return rootFormDefinition;
}
19
View Source File : VxFormGroup.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
internal static bool IsFormGroup(PropertyInfo propertyInfo)
{
return propertyInfo.GetCustomAttribute<VxFormGroupAttribute>() != null;
}
19
View Source File : VxFormGroup.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
internal static VxFormGroupAttribute GetFormGroup(PropertyInfo propertyInfo)
{
return propertyInfo.GetCustomAttribute<VxFormGroupAttribute>();
}
19
View Source File : VxFormGroup.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
internal static void Add(string fieldIdentifier, VxFormGroup group, object modelInstance, VxFormLayoutOptions options)
{
// TODO: EXPANDO switch
var prop = modelInstance.GetType().GetProperty(fieldIdentifier);
var layoutAttr = prop.GetCustomAttribute<VxFormElementLayoutAttribute>();
var allRowLayoutAttributes = VxHelpers.GetAllAttributes<VxFormRowLayoutAttribute>(prop.DeclaringType);
// If no attribute is found use the name of the property
if (layoutAttr == null)
layoutAttr = new VxFormElementLayoutAttribute()
{
Label = GetLabel(fieldIdentifier, modelInstance)
};
PatchLayoutWithBuiltInAttributes(layoutAttr, prop);
// Check if row already exists
var foundRow = group.Rows.Find(value => value.Id == layoutAttr.RowId.ToString());
if (foundRow == null)
{
foundRow = VxFormRow.Create(layoutAttr, allRowLayoutAttributes.Find(x => x.Id == layoutAttr.RowId), options);
group.Rows.Add(foundRow); ;
}
var formColumn = VxFormElementDefinition.Create(fieldIdentifier, layoutAttr, modelInstance, options);
VxFormRow.AddColumn(foundRow, formColumn, options);
// WHen there is a VxFormRowLayout found use the name if specified, this also sets the row to combined labels
if (options.LabelOrientation == LabelOrientation.LEFT && foundRow.RowLayoutAttribute?.Label == null)
foundRow.Label = string.Join(", ", foundRow.Columns.ConvertAll(x => x.RenderOptions.Label));
}
19
View Source File : VxHelpers.cs
License : MIT License
Project Creator : Aaltuj
License : MIT License
Project Creator : Aaltuj
internal static IEnumerable<PropertyInfo> GetModelProperties(Type modelType)
{
return modelType.GetProperties()
.Where(w => w.GetCustomAttribute<VxIgnoreAttribute>() == null);
}
19
View Source File : UserModule.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
[Command("help")]
[Description("List of all commands")]
//RU: Выводит список команд
public async Task Helpsync()
{
var sb = new StringBuilder();
foreach (var type in replacedembly.GetExecutingreplacedembly().GetTypes())
{
if (!(type.IsClreplaced && type.IsSubclreplacedOf(typeof(ModuleBase<SocketCommandContext>))))
{
continue;
}
foreach (var method in type.GetMethods().Where(x => x.IsPublic && x.GetCustomAttribute<CommandAttribute>() != null && x.GetCustomAttribute<CommandAttribute>() != null))
{
DescriptionAttribute desc = method.GetCustomAttribute<DescriptionAttribute>();
CommandAttribute cmd = method.GetCustomAttribute<CommandAttribute>();
if (!string.IsNullOrEmpty(desc.Description))
{
// !OC help:
sb.Append(Program.PX + ' ');
sb.Append(cmd.Text);
sb.Append(": ");
sb.Append(desc.Description);
sb.AppendLine();
}
}
}
await ReplyAsync(sb.ToString());
}
19
View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott
License : Microsoft Public License
Project Creator : AArnott
private bool ExecuteInnerTask(object innerTask)
{
Type innerTaskType = innerTask.GetType();
Type innerTaskBaseType = innerTaskType;
while (innerTaskBaseType.FullName != typeof(ContextIsolatedTask).FullName)
{
innerTaskBaseType = innerTaskBaseType.GetTypeInfo().BaseType;
}
var outerProperties = this.GetType().GetRuntimeProperties().ToDictionary(i => i.Name);
var innerProperties = innerTaskType.GetRuntimeProperties().ToDictionary(i => i.Name);
var propertiesDiscovery = from outerProperty in outerProperties.Values
where outerProperty.SetMethod != null && outerProperty.GetMethod != null
let innerProperty = innerProperties[outerProperty.Name]
select new { outerProperty, innerProperty };
var propertiesMap = propertiesDiscovery.ToArray();
var outputPropertiesMap = propertiesMap.Where(pair => pair.outerProperty.GetCustomAttribute<OutputAttribute>() != null).ToArray();
foreach (var propertyPair in propertiesMap)
{
object outerPropertyValue = propertyPair.outerProperty.GetValue(this);
propertyPair.innerProperty.SetValue(innerTask, outerPropertyValue);
}
// Forward any cancellation requests
MethodInfo innerCancelMethod = innerTaskType.GetMethod(nameof(Cancel));
using (this.CancellationToken.Register(() => innerCancelMethod.Invoke(innerTask, new object[0])))
{
this.CancellationToken.ThrowIfCancellationRequested();
// Execute the inner task.
var executeInnerMethod = innerTaskType.GetMethod(nameof(ExecuteIsolated), BindingFlags.Instance | BindingFlags.NonPublic);
bool result = (bool)executeInnerMethod.Invoke(innerTask, new object[0]);
// Retrieve any output properties.
foreach (var propertyPair in outputPropertiesMap)
{
propertyPair.outerProperty.SetValue(this, propertyPair.innerProperty.GetValue(innerTask));
}
return result;
}
}
19
View Source File : InspectorUIUtility.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
public static bool RenderHelpURL(Type targetType)
{
bool result = false;
if (targetType != null)
{
HelpURLAttribute helpURL = targetType.GetCustomAttribute<HelpURLAttribute>();
if (helpURL != null)
{
result = RenderDoreplacedentationSection(helpURL.URL);
}
}
return result;
}
19
View Source File : DependencyRegistrator.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private void RegisterRpcServer(List<Type> types)
{
types ??= replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
var methodInfos = types.SelectMany(d => d.GetMethods()).Where(d => d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(RpcServerAttribute))).ToList();
//去重复
var dicMethod = new Dictionary<int, MethodInfo>();
methodInfos.ForEach(m =>
{
dicMethod.TryAdd(m.MetadataToken, m);
});
RpcServerMethodList = dicMethod.Select(d => d.Value).ToList();
var first = RpcServerMethodList.Select(d => d.GetCustomAttribute<RpcServerAttribute>().GetFormatKey()).GroupBy(d => d)
.ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value)
.FirstOrDefault();
if (first.Value > 1)
throw new ArgumentException($"RpcServr Key 重复:{first.Key}");
}
19
View Source File : DependencyRegistrator.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
private void RegisterSubscriber(List<Type> types)
{
types ??= replacedemblies.SelectMany(d => d.GetTypes().Where(t => t.IsClreplaced)).ToList();
var methodInfos = types.SelectMany(d => d.GetMethods()).Where(d => d.CustomAttributes.Any(t => t.AttributeType.Name == nameof(SubscriberAttribute))).ToList();
//去重复
var dicMethod = new Dictionary<int, MethodInfo>();
methodInfos.ForEach(m =>
{
dicMethod.TryAdd(m.MetadataToken, m);
});
SubscriberMethodList = dicMethod.Select(d => d.Value).ToList();
var first = SubscriberMethodList.Select(d => d.GetCustomAttribute<SubscriberAttribute>().GetFormatKey()).GroupBy(d => d)
.ToDictionary(d => d.Key, d => d.Count()).OrderByDescending(d => d.Value)
.FirstOrDefault();
if (first.Value > 1)
throw new ArgumentException($"Subscriber Key 重复:{first.Key}");
}
19
View Source File : AssociatedAssemblyNameAttribute.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public static replacedociatedreplacedemblyNameAttribute? GetCachedFor(Type type) => s_attributeCache.GetOrAdd(type, type => type.GetCustomAttribute<replacedociatedreplacedemblyNameAttribute>());
19
View Source File : ZeroDiscover.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
private void FindApi(Type type, bool onlyDoc)
{
if (type.IsAbstract)
return;
StationDoreplacedent station;
var sa = type.GetCustomAttribute<StationAttribute>();
if (sa != null)
{
if (!StationInfo.TryGetValue(sa.Name, out station))
{
StationInfo.Add(sa.Name, station = new StationDoreplacedent
{
Name = sa.Name
});
}
}
else
{
station = _defStation;
}
//station.Copy(XmlMember.Find(type));
string routeHead = null;
var attrib = type.GetCustomAttribute<RouteAttribute>();
if (attrib != null)
{
routeHead = attrib.Name;
}
else
{
var attrib2 = type.GetCustomAttribute<RoutePrefixAttribute>();
if (attrib2 != null)
{
routeHead = attrib2.Name;
}
}
if (string.IsNullOrWhiteSpace(routeHead))
routeHead = null;
else
routeHead = routeHead.Trim(' ', '\t', '\r', '\n', '/') + "/";
var methods = type.GetMethods(BindingFlags.Instance
| BindingFlags.Public
| BindingFlags.NonPublic);
var xdoc = XmlMember.Find(type);
foreach (var method in methods)
{
var route = method.GetCustomAttribute<RouteAttribute>();
if (route == null)
{
//ZeroTrace.WriteError("ApiDiscover", "exclude", station.Name, type.Name, method.Name);
continue;
}
if (method.Name.Length > 4 && (method.Name.IndexOf("get_") == 0 || method.Name.IndexOf("set_") == 0))
continue;
if (method.GetParameters().Length > 1)
{
//ZeroTrace.WriteError("ApiDiscover", "argument size must 0 or 1", station.Name, type.Name, method.Name);
continue;
}
var name = route?.Name == null
? $"{routeHead}{method.Name}"
: $"{routeHead}{route.Name.Trim(' ', '\t', '\r', '\n', '/')}";
var accessOption = method.GetCustomAttribute<ApiAccessOptionFilterAttribute>();
var ca = method.GetAttribute<CategoryAttribute>();
var api = new ApiActionInfo
{
Name = method.Name,
ApiName= route?.Name ?? method.Name,
RouteName = name,
Category = ca?.Category ?? xdoc?.Caption,
AccessOption = accessOption?.Option ?? ApiAccessOption.Public | ApiAccessOption.ArgumentCanNil,
ResultInfo = ReadEnreplacedy(method.ReturnType, "result")
};
var doc = XmlMember.Find(type, method.Name, "M");
api.Copy(doc);
var arg = method.GetParameters().FirstOrDefault();
api.HaseArgument = arg != null;
//动态生成并编译
if (api.HaseArgument)
{
api.ArgumentInfo = ReadEnreplacedy(arg.ParameterType, "argument") ?? new TypeDoreplacedent();
api.ArgumentInfo.Name = arg.Name;
if (doc != null)
api.ArgumentInfo.Caption = doc.Arguments.Values.FirstOrDefault();
if (!onlyDoc)
{
api.ArgumenType = arg.ParameterType;
api.ArgumentAction = CreateFunc<IApiArgument, IApiResult>(type.GetTypeInfo(),
method.Name,
arg.ParameterType.GetTypeInfo(),
method.ReturnType.GetTypeInfo());
}
}
else if (!onlyDoc)
{
api.Action = CreateFunc<IApiResult>(type.GetTypeInfo(), method.Name, method.ReturnType.GetTypeInfo());
}
station.Aips.Add(api.RouteName, api);
}
}
19
View Source File : MissionMapBuilder.cs
License : MIT License
Project Creator : ahydrax
License : MIT License
Project Creator : ahydrax
public static MissionMap BuildMap(replacedembly[] missionreplacedemblies)
{
var targetTypes = missionreplacedemblies
.SelectMany(x => x.GetTypes())
.Where(x => x.GetCustomAttribute<MissionLauncherAttribute>() != null)
.ToArray();
var missions = LookupForMission(targetTypes)
.OrderBy(x => x.Name)
.ToDictionary(x => x.Id, x => x);
return new MissionMap(missions);
}
19
View Source File : EventArgs.cs
License : Mozilla Public License 2.0
Project Creator : ahyahy
License : Mozilla Public License 2.0
Project Creator : ahyahy
public virtual bool PostEvent()
{
if (Sender.GetType() == typeof(osf.ComboBox))
{
string s = "";
osf.ComboBox ComboBox1 = (osf.ComboBox)Sender;
if (ComboBox1.DrawMode != 0)
{
dynamic item = ComboBox1.Items[ComboBox1.SelectedIndex];
if (Sender.GetType() == typeof(osf.ComboBox))
{
string ObjType = item.GetType().ToString();
if (ObjType == "System.Data.DataRowView")
{
System.Data.DataRowView drv = (System.Data.DataRowView)item;
try
{
dynamic var1 = drv.Row[ComboBox1.DisplayMember];
System.Type Type1 = var1.GetType();
s = Type1.GetCustomAttribute<ContextClreplacedAttribute>().GetName();
}
catch
{
if (drv.Row[ComboBox1.DisplayMember].GetType() == typeof(System.Boolean))
{
ScriptEngine.Machine.Values.BooleanValue Bool1;
if ((System.Boolean)drv.Row[ComboBox1.DisplayMember])
{
Bool1 = ScriptEngine.Machine.Values.BooleanValue.True;
}
else
{
Bool1 = ScriptEngine.Machine.Values.BooleanValue.False;
}
s = Bool1.ToString();
}
else
{
s = drv.Row[ComboBox1.DisplayMember].ToString();
}
}
}
}
else if (Sender.GetType() == typeof(osf.Lisreplacedem))
{
}
if (s == "")
{
try
{
System.Type Type1 = item.GetType();
s = Type1.GetCustomAttribute<ContextClreplacedAttribute>().GetName();
}
catch
{
s = item.ToString();
}
}
ComboBox1.Text = s;
}
}
return true;
}
19
View Source File : EnumControl.cs
License : MIT License
Project Creator : ahydrax
License : MIT License
Project Creator : ahydrax
private static string GetDescription(Type enumType, string valueName)
=> enumType.GetField(valueName)
?.GetCustomAttribute<DescriptionAttribute>()
?.Description;
19
View Source File : MissionMapBuilder.cs
License : MIT License
Project Creator : ahydrax
License : MIT License
Project Creator : ahydrax
private static IEnumerable<Mission> LookupForMission(Type[] targetTypes)
{
foreach (var targetType in targetTypes)
{
var missionLauncherAttribute = targetType.GetCustomAttribute<MissionLauncherAttribute>();
var suitableMethods = targetType
.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)
.Where(x => x.GetCustomAttribute<MissionAttribute>() != null)
.ToArray();
foreach (var suitableMethod in suitableMethods)
{
var missionAttribute = suitableMethod.GetCustomAttribute<MissionAttribute>();
yield return new Mission(missionLauncherAttribute, missionAttribute, suitableMethod);
}
}
}
19
View Source File : CommandsNextUtilities.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
internal static object CreateInstance(this Type t, IServiceProvider services)
{
var ti = t.GetTypeInfo();
var constructors = ti.DeclaredConstructors
.Where(xci => xci.IsPublic)
.ToArray();
if (constructors.Length != 1)
throw new ArgumentException("Specified type does not contain a public constructor or contains more than one public constructor.");
var constructor = constructors[0];
var constructorArgs = constructor.GetParameters();
var args = new object[constructorArgs.Length];
if (constructorArgs.Length != 0 && services == null)
throw new InvalidOperationException("Dependency collection needs to be specified for parameterized constructors.");
// inject via constructor
if (constructorArgs.Length != 0)
for (var i = 0; i < args.Length; i++)
args[i] = services.GetRequiredService(constructorArgs[i].ParameterType);
var moduleInstance = Activator.CreateInstance(t, args);
// inject into properties
var props = t.GetRuntimeProperties().Where(xp => xp.CanWrite && xp.SetMethod != null && !xp.SetMethod.IsStatic && xp.SetMethod.IsPublic);
foreach (var prop in props)
{
if (prop.GetCustomAttribute<DontInjectAttribute>() != null)
continue;
var service = services.GetService(prop.PropertyType);
if (service == null)
continue;
prop.SetValue(moduleInstance, service);
}
// inject into fields
var fields = t.GetRuntimeFields().Where(xf => !xf.IsInitOnly && !xf.IsStatic && xf.IsPublic);
foreach (var field in fields)
{
if (field.GetCustomAttribute<DontInjectAttribute>() != null)
continue;
var service = services.GetService(field.FieldType);
if (service == null)
continue;
field.SetValue(moduleInstance, service);
}
return moduleInstance;
}
19
View Source File : CommandsNextExtension.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
private void RegisterCommands(Type t, CommandGroupBuilder currentParent, IEnumerable<CheckBaseAttribute> inheritedChecks, out List<CommandBuilder> foundCommands)
{
var ti = t.GetTypeInfo();
var lifespan = ti.GetCustomAttribute<ModuleLifespanAttribute>();
var moduleLifespan = lifespan != null ? lifespan.Lifespan : ModuleLifespan.Singleton;
var module = new CommandModuleBuilder()
.WithType(t)
.WithLifespan(moduleLifespan)
.Build(this.Services);
// restrict parent lifespan to more or equally restrictive
if (currentParent?.Module is TransientCommandModule && moduleLifespan != ModuleLifespan.Transient)
throw new InvalidOperationException("In a transient module, child modules can only be transient.");
// check if we are anything
var groupBuilder = new CommandGroupBuilder(module);
var isModule = false;
var moduleAttributes = ti.GetCustomAttributes();
var moduleHidden = false;
var moduleChecks = new List<CheckBaseAttribute>();
foreach (var xa in moduleAttributes)
{
switch (xa)
{
case GroupAttribute g:
isModule = true;
var moduleName = g.Name;
if (moduleName == null)
{
moduleName = ti.Name;
if (moduleName.EndsWith("Group") && moduleName != "Group")
moduleName = moduleName.Substring(0, moduleName.Length - 5);
else if (moduleName.EndsWith("Module") && moduleName != "Module")
moduleName = moduleName.Substring(0, moduleName.Length - 6);
else if (moduleName.EndsWith("Commands") && moduleName != "Commands")
moduleName = moduleName.Substring(0, moduleName.Length - 8);
}
if (!this.Config.CaseSensitive)
moduleName = moduleName.ToLowerInvariant();
groupBuilder.WithName(moduleName);
if (inheritedChecks != null)
foreach (var chk in inheritedChecks)
groupBuilder.WithExecutionCheck(chk);
foreach (var mi in ti.DeclaredMethods.Where(x => x.IsCommandCandidate(out _) && x.GetCustomAttribute<GroupCommandAttribute>() != null))
groupBuilder.WithOverload(new CommandOverloadBuilder(mi));
break;
case AliasesAttribute a:
foreach (var xalias in a.Aliases)
groupBuilder.WithAlias(this.Config.CaseSensitive ? xalias : xalias.ToLowerInvariant());
break;
case HiddenAttribute h:
groupBuilder.WithHiddenStatus(true);
moduleHidden = true;
break;
case DescriptionAttribute d:
groupBuilder.WithDescription(d.Description);
break;
case CheckBaseAttribute c:
moduleChecks.Add(c);
groupBuilder.WithExecutionCheck(c);
break;
default:
groupBuilder.WithCustomAttribute(xa);
break;
}
}
if (!isModule)
{
groupBuilder = null;
if (inheritedChecks != null)
moduleChecks.AddRange(inheritedChecks);
}
// candidate methods
var methods = ti.DeclaredMethods;
var commands = new List<CommandBuilder>();
var commandBuilders = new Dictionary<string, CommandBuilder>();
foreach (var m in methods)
{
if (!m.IsCommandCandidate(out _))
continue;
var attrs = m.GetCustomAttributes();
if (attrs.FirstOrDefault(xa => xa is CommandAttribute) is not CommandAttribute cattr)
continue;
var commandName = cattr.Name;
if (commandName == null)
{
commandName = m.Name;
if (commandName.EndsWith("Async") && commandName != "Async")
commandName = commandName.Substring(0, commandName.Length - 5);
}
if (!this.Config.CaseSensitive)
commandName = commandName.ToLowerInvariant();
if (!commandBuilders.TryGetValue(commandName, out var commandBuilder))
{
commandBuilders.Add(commandName, commandBuilder = new CommandBuilder(module).WithName(commandName));
if (!isModule)
if (currentParent != null)
currentParent.WithChild(commandBuilder);
else
commands.Add(commandBuilder);
else
groupBuilder.WithChild(commandBuilder);
}
commandBuilder.WithOverload(new CommandOverloadBuilder(m));
if (!isModule && moduleChecks.Any())
foreach (var chk in moduleChecks)
commandBuilder.WithExecutionCheck(chk);
foreach (var xa in attrs)
{
switch (xa)
{
case AliasesAttribute a:
foreach (var xalias in a.Aliases)
commandBuilder.WithAlias(this.Config.CaseSensitive ? xalias : xalias.ToLowerInvariant());
break;
case CheckBaseAttribute p:
commandBuilder.WithExecutionCheck(p);
break;
case DescriptionAttribute d:
commandBuilder.WithDescription(d.Description);
break;
case HiddenAttribute h:
commandBuilder.WithHiddenStatus(true);
break;
default:
commandBuilder.WithCustomAttribute(xa);
break;
}
}
if (!isModule && moduleHidden)
commandBuilder.WithHiddenStatus(true);
}
// candidate types
var types = ti.DeclaredNestedTypes
.Where(xt => xt.IsModuleCandidateType() && xt.DeclaredConstructors.Any(xc => xc.IsPublic));
foreach (var type in types)
{
this.RegisterCommands(type.AsType(),
groupBuilder,
!isModule ? moduleChecks : null,
out var tempCommands);
if (isModule)
foreach (var chk in moduleChecks)
groupBuilder.WithExecutionCheck(chk);
if (isModule && tempCommands != null)
foreach (var xtcmd in tempCommands)
groupBuilder.WithChild(xtcmd);
else if (tempCommands != null)
commands.AddRange(tempCommands);
}
if (isModule && currentParent == null)
commands.Add(groupBuilder);
else if (isModule)
currentParent.WithChild(groupBuilder);
foundCommands = commands;
}
19
View Source File : AutowiredControllerActivator.cs
License : MIT License
Project Creator : aishang2015
License : MIT License
Project Creator : aishang2015
private object CreateInstance(IServiceProvider serviceProvider, Type type, int deep = 1)
{
// 超过指定深度,返回null
if (deep > MaxDeep)
{
return null;
}
var instance = serviceProvider.GetService(type);
// 当实例可以从容器中获取时,继续在实例中寻找可以自动注入的对象
if (instance != null)
{
// 在类型中查找
var autowiredFields = instance.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
// 循环创建实例
foreach (var field in autowiredFields)
{
var fieldInstance = CreateInstance(serviceProvider, field.FieldType, deep + 1);
// 如果实例可以获得,并且其包含自动装配特性,则将其放入字段中
if (fieldInstance != null &&
field.GetCustomAttribute<AutowiredAttribute>() != null)
{
field.SetValue(instance, fieldInstance);
}
}
}
return instance;
}
19
View Source File : OffsetManager.cs
License : GNU Affero General Public License v3.0
Project Creator : akira0245
License : GNU Affero General Public License v3.0
Project Creator : akira0245
public static void Setup(SigScanner scanner)
{
var props = typeof(Offsets).GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.Select(i => (prop: i, Attribute: i.GetCustomAttribute<SigAttribute>())).Where(i => i.Attribute != null);
List<Exception> exceptions = new List<Exception>(100);
foreach ((PropertyInfo propertyInfo, SigAttribute sigAttribute) in props)
{
try
{
var sig = sigAttribute.SigString;
sig = string.Join(' ', sig.Split(new[] { ' ' }, StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries)
.Select(i => i == "?" ? "??" : i));
IntPtr address;
switch (sigAttribute)
{
case StaticAddressAttribute:
address = scanner.GetStaticAddressFromSig(sig);
break;
case FunctionAttribute:
address = scanner.ScanText(sig);
break;
case OffsetAttribute:
{
address = scanner.ScanText(sig);
address += sigAttribute.Offset;
var structure = Marshal.PtrToStructure(address, propertyInfo.PropertyType);
propertyInfo.SetValue(null, structure);
PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {propertyInfo.PropertyType.FullName} {structure}");
continue;
}
default:
throw new ArgumentOutOfRangeException();
}
address += sigAttribute.Offset;
propertyInfo.SetValue(null, address);
PluginLog.Information($"[{nameof(OffsetManager)}][{propertyInfo.Name}] {address.ToInt64():X}");
}
catch (Exception e)
{
PluginLog.Error(e, $"[{nameof(OffsetManager)}][{propertyInfo?.Name}] failed to find sig : {sigAttribute?.SigString}");
exceptions.Add(e);
}
}
if (exceptions.Any())
{
throw new AggregateException(exceptions);
}
}
19
View Source File : NodeProvider.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
static void BuildCacheForNode(Type nodeType, NodeDescriptions targetDescription, BaseGraph graph = null)
{
var attrs = nodeType.GetCustomAttributes(typeof(NodeMenuItemAttribute), false) as NodeMenuItemAttribute[];
if (attrs != null && attrs.Length > 0)
{
foreach (var attr in attrs)
targetDescription.nodePerMenureplacedle[attr.menureplacedle] = nodeType;
}
foreach (var field in nodeType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (field.GetCustomAttribute<HideInInspector>() == null && field.GetCustomAttributes().Any(c => c is InputAttribute || c is OutputAttribute))
targetDescription.slotTypes.Add(field.FieldType);
}
ProvideNodePortCreationDescription(nodeType, targetDescription, graph);
}
19
View Source File : NodeProvider.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
static bool IsNodeSpecificToGraph(Type nodeType)
{
var isCompatibleWithGraphMethods = nodeType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy).Where(m => m.GetCustomAttribute<IsCompatibleWithGraph>() != null);
var nodeMenuAttributes = nodeType.GetCustomAttributes<NodeMenuItemAttribute>();
List<Type> compatibleGraphTypes = nodeMenuAttributes.Where(n => n.onlyCompatibleWithGraph != null).Select(a => a.onlyCompatibleWithGraph).ToList();
List<MethodInfo> compatibleMethods = new List<MethodInfo>();
foreach (var method in isCompatibleWithGraphMethods)
{
// Check if the method is static and have the correct prototype
var p = method.GetParameters();
if (method.ReturnType != typeof(bool) || p.Count() != 1 || p[0].ParameterType != typeof(BaseGraph))
Debug.LogError($"The function '{method.Name}' marked with the IsCompatibleWithGraph attribute either doesn't return a boolean or doesn't take one parameter of BaseGraph type.");
else
compatibleMethods.Add(method);
}
if (compatibleMethods.Count > 0 || compatibleGraphTypes.Count > 0)
{
// We still need to add the element in specificNode even without specific graph
if (compatibleGraphTypes.Count == 0)
compatibleGraphTypes.Add(null);
foreach (var graphType in compatibleGraphTypes)
{
specificNodes.Add(new NodeSpecificToGraph{
nodeType = nodeType,
isCompatibleWithGraph = compatibleMethods,
compatibleWithGraphType = graphType
});
}
return true;
}
return false;
}
19
View Source File : BaseNodeView.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
private void AddEmptyField(FieldInfo field, bool fromInspector)
{
if (field.GetCustomAttribute(typeof(InputAttribute)) == null || fromInspector)
return;
if (field.GetCustomAttribute<VerticalAttribute>() != null)
return;
var box = new VisualElement {name = field.Name};
box.AddToClreplacedList("port-input-element");
box.AddToClreplacedList("empty");
inputContainerElement.Add(box);
}
19
View Source File : BaseNodeView.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
protected void AddSettingField(FieldInfo field)
{
if (field == null)
return;
var label = field.GetCustomAttribute<SettingAttribute>().name;
var element = new PropertyField(FindSerializedProperty(field.Name));
element.Bind(owner.serializedGraph);
if (element != null)
{
settingsContainer.Add(element);
element.name = field.Name;
}
}
19
View Source File : BaseNode.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
void InitializeInOutDatas()
{
var fields = GetNodeFields();
var methods = GetType().GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var field in fields)
{
var inputAttribute = field.GetCustomAttribute< InputAttribute >();
var outputAttribute = field.GetCustomAttribute< OutputAttribute >();
var tooltipAttribute = field.GetCustomAttribute< TooltipAttribute >();
var showInInspector = field.GetCustomAttribute< ShowInInspector >();
var vertical = field.GetCustomAttribute< VerticalAttribute >();
bool isMultiple = false;
bool input = false;
string name = field.Name;
string tooltip = null;
if (showInInspector != null)
_needsInspector = true;
if (inputAttribute == null && outputAttribute == null)
continue ;
//check if field is a collection type
isMultiple = (inputAttribute != null) ? inputAttribute.allowMultiple : (outputAttribute.allowMultiple);
input = inputAttribute != null;
tooltip = tooltipAttribute?.tooltip;
if (!String.IsNullOrEmpty(inputAttribute?.name))
name = inputAttribute.name;
if (!String.IsNullOrEmpty(outputAttribute?.name))
name = outputAttribute.name;
// By default we set the behavior to null, if the field have a custom behavior, it will be set in the loop just below
nodeFields[field.Name] = new NodeFieldInformation(field, name, input, isMultiple, tooltip, vertical != null, null);
}
foreach (var method in methods)
{
var customPortBehaviorAttribute = method.GetCustomAttribute< CustomPortBehaviorAttribute >();
CustomPortBehaviorDelegate behavior = null;
if (customPortBehaviorAttribute == null)
continue ;
// Check if custom port behavior function is valid
try {
var referenceType = typeof(CustomPortBehaviorDelegate);
behavior = (CustomPortBehaviorDelegate)Delegate.CreateDelegate(referenceType, this, method, true);
} catch {
Debug.LogError("The function " + method + " cannot be converted to the required delegate format: " + typeof(CustomPortBehaviorDelegate));
}
if (nodeFields.ContainsKey(customPortBehaviorAttribute.fieldName))
nodeFields[customPortBehaviorAttribute.fieldName].behavior = behavior;
else
Debug.LogError("Invalid field name for custom port behavior: " + method + ", " + customPortBehaviorAttribute.fieldName);
}
}
19
View Source File : MixtureNode.cs
License : MIT License
Project Creator : alelievr
License : MIT License
Project Creator : alelievr
[CustomPortTypeBehavior(typeof(Texture))]
[CustomPortTypeBehavior(typeof(RenderTexture))]
[CustomPortTypeBehavior(typeof(CustomRenderTexture))]
IEnumerable< PortData > GetTypeFromTextureDim(string fieldName, string displayName, object fieldValue)
{
bool input = false;
var field = GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if (field.GetCustomAttribute<InputAttribute>() != null)
input = true;
yield return new PortData
{
displayName = displayName,
displayType = TextureUtils.GetTypeFromDimension(settings.GetResolvedTextureDimension(graph)),
identifier = fieldName,
acceptMultipleEdges = input ? false : true,
};
}
19
View Source File : Extension.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
public static Table TableName(this Type type)
{
if (CachedTableNames.ContainsKey(type))
return CachedTableNames[type];
return CachedTableNames.GetOrAdd(type, (type.GetCustomAttribute<Table>() ?? new Table(type.Name)));
}
19
View Source File : DbSchema.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
private object Save(object o, bool isIndependentData, bool updateOnly = false, List<string> ignoredProperties = null, string lastProperty = null)
{
try
{
if (ignoredProperties == null)
ignoredProperties = new List<string>();
if (lastProperty == null)
lastProperty = string.Empty; // not valid name
GlobalConfiguration.Log?.Info("Save", o);
_repository.CreateTransaction();
var props = DeepCloner.GetFastDeepClonerProperties(o.GetType());
var primaryKey = o.GetPrimaryKey();
if (primaryKey == null)
throw new EnreplacedyException("Object must have a PrimaryKey");
var primaryKeyId = !Extension.ObjectIsNew(o.GetPrimaryKeyValue()) ? o.GetPrimaryKeyValue() : null;
var availableColumns = _repository.GetColumnSchema(o.GetType());
var objectRules = o.GetType().GetCustomAttribute<Rule>();
var tableName = o.GetType().TableName().GetName(_repository.DataBaseTypes);
var primaryKeySubsreplacedut = !primaryKey.GetCustomAttribute<PrimaryKey>().AutoGenerate ? primaryKeyId : null;
object dbTrigger = null;
if (objectRules != null && !CachedIDbRuleTrigger.ContainsKey(o.GetType()))
{
dbTrigger = objectRules.RuleType.CreateInstance();
CachedIDbRuleTrigger.Add(o.GetType(), dbTrigger);
}
else if (objectRules != null || CachedIDbRuleTrigger.ContainsKey(o.GetType()))
dbTrigger = CachedIDbRuleTrigger[o.GetType()];
if (primaryKeyId != null && !updateOnly) // lets attach the object
{
var data = GetById(primaryKeyId, o.GetType());
if (data == null)
{
primaryKeyId = null;
o.SetPrimaryKeyValue();
}
else
{
if (!_repository.IsAttached(o))
_repository.Attach(data);
var changes = _repository.GetObjectChanges(o);
foreach (var item in props.Where(x => x.CanRead && !changes.Any(a => a.PropertyName == x.Name) && (x.IsInternalType || x.ContainAttribute<JsonDoreplacedent>())))
item.SetValue(o, item.GetValue(data));
}
}
if (!updateOnly)
dbTrigger?.GetType().GetMethod("BeforeSave").Invoke(dbTrigger, new List<object>() { _repository, o }.ToArray()); // Check the Rule before save
object tempPrimaryKey = null;
var sql = "UPDATE " + (o.GetType().TableName().GetName(_repository.DataBaseTypes)) + " SET ";
var cols = props.FindAll(x => x.CanRead && (availableColumns.ContainsKey(x.GetPropertyName()) || availableColumns.ContainsKey(x.GetPropertyName().ToLower())) && (x.IsInternalType || x.ContainAttribute<JsonDoreplacedent>() || x.ContainAttribute<XmlDoreplacedent>()) && !x.ContainAttribute<ExcludeFromAbstract>() && x.GetCustomAttribute<PrimaryKey>() == null);
// Clean out all unwanted properties
if (ignoredProperties.Any())
cols = cols.FindAll(x => !ignoredProperties.Any(a => a == x.Name || a == (o.GetType().Name + "." + x.Name) || a == (lastProperty + "." + x.Name)));
if (primaryKeyId == null)
{
if (primaryKey.PropertyType.IsNumeric() && primaryKey.GetCustomAttribute<PrimaryKey>().AutoGenerate)
{
sql = "INSERT INTO " + tableName + "(" + string.Join(",", cols.Select(x => "[" + x.GetPropertyName() + "]")) + ") Values(";
sql += string.Join(",", cols.Select(x => "@" + x.GetPropertyName())) + ");";
sql += _repository.DataBaseTypes == DataBaseTypes.Sqllight ? " select last_insert_rowid();" : (_repository.DataBaseTypes != DataBaseTypes.PostgreSql ? " SELECT IDENT_CURRENT('" + tableName + "');" : " SELECT currval('" + string.Format("{0}_{1}_seq", tableName, primaryKey.GetPropertyName()) + "');");
}
else
{
var colList = new List<IFastDeepClonerProperty>();
tempPrimaryKey = primaryKeySubsreplacedut == null ? Guid.NewGuid() : primaryKeySubsreplacedut;
if (primaryKeySubsreplacedut == null && primaryKey.PropertyType.IsNumeric())
tempPrimaryKey = _repository.ExecuteScalar(_repository.GetSqlCommand(String.Format("SELECT MAX([{0}]) FROM {1}", primaryKey.GetPropertyName(), tableName))).ConvertValue<long>() + 1;
else if (primaryKey.PropertyType == typeof(string))
tempPrimaryKey = tempPrimaryKey.ToString();
colList.Insert(0, primaryKey);
colList.AddRange(cols);
sql = "INSERT INTO " + tableName + "(" + string.Join(",", colList.Select(x => "[" + x.GetPropertyName() + "]")) + ") Values(";
sql += string.Join(",", colList.Select(x => "@" + x.GetPropertyName())) + "); select '" + tempPrimaryKey + "'";
}
}
else
{
sql += string.Join(",", cols.Select(x => "[" + x.GetPropertyName() + "]" + " = @" + x.GetPropertyName()));
sql += Querys.Where(_repository.DataBaseTypes).Column(o.GetType().GetActualType().GetPrimaryKey().GetPropertyName()).Equal(primaryKeyId).Execute();
}
var cmd = _repository.GetSqlCommand(sql);
if ((!primaryKey.PropertyType.IsNumeric() || !primaryKey.GetCustomAttribute<PrimaryKey>().AutoGenerate) && primaryKeyId == null)
_repository.AddInnerParameter(cmd, primaryKey.GetPropertyName(), tempPrimaryKey);
foreach (var col in cols)
{
var v = col.GetValue(o);
var defaultOnEmpty = col.GetCustomAttribute<DefaultOnEmpty>();
if (col.ContainAttribute<ForeignKey>() && (v?.ObjectIsNew() ?? true))
{
var ob = props.FirstOrDefault(x => (x.PropertyType == col.GetCustomAttribute<ForeignKey>().Type) && (string.IsNullOrEmpty(col.GetCustomAttribute<ForeignKey>().PropertyName) || col.GetCustomAttribute<ForeignKey>().PropertyName == x.Name));
var obValue = ob?.GetValue(o);
var independentData = ob?.GetCustomAttribute<IndependentData>() != null;
if (obValue != null)
{
v = obValue.GetType().GetPrimaryKey().GetValue(obValue)?.ObjectIsNew() ?? true ?
Save(obValue, independentData, false, ignoredProperties, ob.Name) :
obValue.GetType().GetPrimaryKey().GetValue(obValue);
col.SetValue(o, v);
}
}
if (col.ContainAttribute<ToBase64String>())
{
if (!v?.ConvertValue<string>().IsBase64String() ?? false)
{
v = MethodHelper.EncodeStringToBase64(v.ConvertValue<string>());
}
}
if (col.ContainAttribute<JsonDoreplacedent>())
{
v = v?.ToJson();
}
if (col.ContainAttribute<XmlDoreplacedent>())
{
v = v?.ToXml();
}
if (col.ContainAttribute<Stringify>() || col.ContainAttribute<DataEncode>())
v = v?.ConvertValue<string>();
if (col.ContainAttribute<DataEncode>())
{
if (col.PropertyType != typeof(string))
throw new EnreplacedyException(string.Format("Property {0} Contain DataEncode. PropertyType must be of type String .", col.FullName));
v = new DataCipher(col.GetCustomAttribute<DataEncode>().Key, col.GetCustomAttribute<DataEncode>().KeySize).Encrypt(v.ToString());
}
if (col.ContainAttribute<NotNullable>() && v == null && defaultOnEmpty == null)
throw new EnreplacedyException(string.Format("Property {0} dose not allow null.", col.FullName));
if (v == null && defaultOnEmpty != null)
v = defaultOnEmpty.Value.ConvertValue(col.PropertyType);
_repository.AddInnerParameter(cmd, col.GetPropertyName(), v);
}
if (primaryKeyId == null)
primaryKeyId = _repository.ExecuteScalar(cmd).ConvertValue(primaryKey.PropertyType);
else _repository.ExecuteNonQuery(cmd);
var oState = dbTrigger != null ? DeepCloner.Clone(o) : null;
if (updateOnly)
return primaryKeyId;
dbTrigger?.GetType().GetMethod("AfterSave").Invoke(dbTrigger, new List<object>() { _repository, o, primaryKeyId }.ToArray()); // Check the Rule before save
foreach (var prop in props.Where(x => !x.IsInternalType && !x.ContainAttribute<JsonDoreplacedent>() && !x.ContainAttribute<XmlDoreplacedent>() && !x.ContainAttribute<ExcludeFromAbstract>()))
{
var independentData = prop.GetCustomAttribute<IndependentData>() != null;
var type = prop.PropertyType.GetActualType();
var oValue = prop.GetValue(o);
if (oValue == null)
continue;
var vList = oValue is IList ? (IList)oValue : new List<object>() { oValue };
foreach (var item in vList)
{
var foreignKey = DeepCloner.GetFastDeepClonerProperties(item.GetType()).FirstOrDefault(x => x.GetCustomAttribute<ForeignKey>()?.Type == o.GetType() && string.IsNullOrEmpty(x.GetCustomAttribute<ForeignKey>().PropertyName));
foreignKey?.SetValue(item, primaryKeyId);
var res = Save(item, independentData, false, ignoredProperties, prop.Name);
foreignKey = props.FirstOrDefault(x => x.GetCustomAttribute<ForeignKey>()?.Type == type && (x.GetCustomAttribute<ForeignKey>().PropertyName == prop.Name || string.IsNullOrEmpty(x.GetCustomAttribute<ForeignKey>().PropertyName)));
if (foreignKey == null || !foreignKey.GetValue(o).ObjectIsNew()) continue;
if (o.GetType() == foreignKey.GetCustomAttribute<ForeignKey>().Type) continue;
foreignKey.SetValue(o, res);
}
}
if (oState != null && _repository.GetObjectChanges(o, oState).Count > 0) // a change has been made outside the function Save then resave
{
o.SetPrimaryKeyValue(primaryKeyId);
Save(o, false, true, ignoredProperties);
}
o.SetPrimaryKeyValue(primaryKeyId);
_repository.Attach(o, true);
return primaryKeyId;
}
catch (Exception e)
{
GlobalConfiguration.Log?.Error(e);
_repository.Rollback();
throw;
}
}
19
View Source File : DbSchema.cs
License : MIT License
Project Creator : AlenToma
License : MIT License
Project Creator : AlenToma
public CodeToDataBaseMergeCollection GetDatabase_Diff(Type tableType, CodeToDataBaseMergeCollection str = null, List<Type> createdTables = null)
{
str = str ?? new CodeToDataBaseMergeCollection(_repository);
if (tableType.GetCustomAttribute<ExcludeFromAbstract>() != null || _alreadyControlled.Any(x => x == tableType))
return str;
_repository.CreateSchema(tableType);
tableType = tableType.GetActualType();
_alreadyControlled.Add(tableType);
createdTables = createdTables ?? new List<Type>();
if (createdTables.Any(x => x == tableType) || tableType.GetPrimaryKey() == null)
return str;
if (CodeToDataBaseMergeCollection.ExecutedData.ContainsKey(tableType.FullName + _repository.DataBaseTypes.ToString()))
return str;
createdTables.Add(tableType);
var table = _repository.GetColumnSchema(tableType);
var tableName = tableType.TableName();
var props = DeepCloner.GetFastDeepClonerProperties(tableType).Where(x => x.CanRead && !x.ContainAttribute<ExcludeFromAbstract>());
var codeToDataBaseMerge = new CodeToDataBaseMerge() { Object_Type = tableType };
var isPrimaryKey = "";
if (!IsValidName(tableName.Name))
throw new EnreplacedyException(tableName.Name + " is not a valid Name for the current provider " + _repository.DataBaseTypes);
if (!table.Values.Any())
{
codeToDataBaseMerge.Sql = new StringBuilder($"CREATE TABLE {tableName.GetName(_repository.DataBaseTypes)} (");
foreach (var prop in props.Where(x => (x.GetDbTypeByType(_repository.DataBaseTypes) != null || !x.IsInternalType ||
x.ContainAttribute<JsonDoreplacedent>() || x.ContainAttribute<XmlDoreplacedent>()) &&
!x.ContainAttribute<ExcludeFromAbstract>()).GroupBy(x => x.Name).Select(x => x.First())
.OrderBy(x => x.ContainAttribute<PrimaryKey>() ? null : x.Name))
{
if (!prop.IsInternalType && !prop.ContainAttribute<JsonDoreplacedent>() && !prop.ContainAttribute<XmlDoreplacedent>())
{
if (!str.Any(x => x.Object_Type == prop.PropertyType.GetActualType()) && createdTables.All(x => x != prop.PropertyType.GetActualType()))
GetDatabase_Diff(prop.PropertyType, str, createdTables);
continue;
}
isPrimaryKey = prop.ContainAttribute<PrimaryKey>() ? prop.GetPropertyName() : isPrimaryKey;
var foreignKey = prop.GetCustomAttribute<ForeignKey>();
var dbType = prop.GetDbTypeByType(_repository.DataBaseTypes);
var propName = string.Format("[{0}]", prop.GetPropertyName());
codeToDataBaseMerge.Sql.Append(propName + " ");
if (!IsValidName(prop.GetPropertyName()))
throw new Exception(prop.GetPropertyName() + " is not a valid Name for the current provider " + _repository.DataBaseTypes);
if (!prop.ContainAttribute<PrimaryKey>() || _repository.DataBaseTypes == DataBaseTypes.Mssql)
codeToDataBaseMerge.Sql.Append(dbType + " ");
if (foreignKey != null && createdTables.All(x => x != foreignKey.Type))
GetDatabase_Diff(foreignKey.Type, str, createdTables);
if (prop.ContainAttribute<PrimaryKey>())
{
if (prop.PropertyType.IsNumeric() && prop.GetCustomAttribute<PrimaryKey>().AutoGenerate)
codeToDataBaseMerge.Sql.Append(_repository.DataBaseTypes == DataBaseTypes.Mssql ? "IDENreplacedY(1,1) NOT NULL," : (_repository.DataBaseTypes == DataBaseTypes.Sqllight ? " Integer PRIMARY KEY AUTOINCREMENT," : " BIGSERIAL PRIMARY KEY,"));
else codeToDataBaseMerge.Sql.Append(_repository.DataBaseTypes == DataBaseTypes.Mssql ? "NOT NULL," : " " + dbType + " PRIMARY KEY,");
continue;
}
if (foreignKey != null)
{
var key = propName + "-" + tableName.GetName(_repository.DataBaseTypes);
if (!str.Keys.ContainsKey(key))
str.Keys.Add(key, new Tuple<string, ForeignKey>(tableName.GetName(_repository.DataBaseTypes), foreignKey));
}
codeToDataBaseMerge.Sql.Append((Nullable.GetUnderlyingType(prop.PropertyType) != null || prop.PropertyType == typeof(string)) && !prop.ContainAttribute<NotNullable>() ? " NULL," : " NOT NULL,");
}
if (str.Keys.Any() && _repository.DataBaseTypes == DataBaseTypes.Sqllight)
{
while (str.Keys.Any(x => x.Value.Item1 == tableName.Name))
{
var key = str.Keys.FirstOrDefault(x => x.Value.Item1 == tableName.Name);
var type = key.Value.Item2.Type.GetActualType();
var keyPrimary = type.GetPrimaryKey().GetPropertyName();
var tb = type.TableName();
codeToDataBaseMerge.Sql.Append("FOREIGN KEY(" + key.Key.Split('-')[0] + ") REFERENCES " + tb.GetName(_repository.DataBaseTypes) + "(" + keyPrimary + "),");
str.Keys.Remove(key.Key);
}
}
if (!string.IsNullOrEmpty(isPrimaryKey) && _repository.DataBaseTypes == DataBaseTypes.Mssql)
{
codeToDataBaseMerge.Sql.Append(" CONSTRAINT [PK_" + tableName.Name + "] PRIMARY KEY CLUSTERED");
codeToDataBaseMerge.Sql.Append(" ([" + isPrimaryKey + "] ASC");
codeToDataBaseMerge.Sql.Append(")");
codeToDataBaseMerge.Sql.Append("WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]");
codeToDataBaseMerge.Sql.Append(") ON [PRIMARY]");
}
else
{
if (_repository.DataBaseTypes == DataBaseTypes.Sqllight)
codeToDataBaseMerge.Sql = new StringBuilder(codeToDataBaseMerge.Sql.ToString().TrimEnd(','));
codeToDataBaseMerge.Sql.Append(")");
}
str.Add(codeToDataBaseMerge);
}
else
{
foreach (var prop in props.Where(x => (x.GetDbTypeByType(_repository.DataBaseTypes) != null || !x.IsInternalType) && !x.ContainAttribute<ExcludeFromAbstract>()).GroupBy(x => x.Name).Select(x => x.First())
.OrderBy(x => x.ContainAttribute<PrimaryKey>() ? null : x.Name))
{
if (prop.ContainAttribute<ForeignKey>())
GetDatabase_Diff(prop.GetCustomAttribute<ForeignKey>().Type, str, createdTables);
var propType = prop.PropertyType;
if (prop.ContainAttribute<Stringify>() ||
prop.ContainAttribute<DataEncode>() ||
prop.ContainAttribute<ToBase64String>() ||
prop.ContainAttribute<JsonDoreplacedent>() ||
prop.ContainAttribute<XmlDoreplacedent>())
propType = typeof(string);
var modify = prop.IsInternalType || prop.ContainAttribute<JsonDoreplacedent>() || prop.ContainAttribute<XmlDoreplacedent>() ? (_repository.DataBaseTypes == DataBaseTypes.PostgreSql ? table.Get(prop.GetPropertyName().ToLower()) : table.Get(prop.GetPropertyName())) : null;
if (modify != null)
{
if (_repository.DataBaseTypes != DataBaseTypes.Sqllight && !(prop.GetDbTypeListByType(_repository.DataBaseTypes).Any(x => x.ToLower().Contains(modify.DataType.ToLower()))) && _repository.DataBaseTypes != DataBaseTypes.PostgreSql)
{
var constraine = Properties.Resources.DropContraine
.Replace("@tb", $"'{tableName.Name}'").Replace("@col", $"'{prop.GetPropertyName()}'")
.Replace("@schema", $"'{tableName.Schema ?? ""}'")
.Replace("@TableName", "@" + counter++)
.Replace("@ColumnName", "@" + counter++)
.Replace("@fullName", "@" + counter++)
.Replace("@DROP_COMMAND", "@" + counter++)
.Replace("@FOREIGN_KEY_NAME", "@" + counter++);
codeToDataBaseMerge.Sql.Append(constraine);
codeToDataBaseMerge.Sql.Append($"\nALTER TABLE {tableName.GetName(_repository.DataBaseTypes)} ALTER COLUMN [{prop.GetPropertyName()}] {prop.GetDbTypeByType(_repository.DataBaseTypes)} {((Nullable.GetUnderlyingType(propType) != null || propType == typeof(string)) && !prop.ContainAttribute<NotNullable>() ? " NULL" : " NOT NULL")}");
}
else
{
if (!(prop.GetDbTypeListByType(_repository.DataBaseTypes).Any(x => x.ToLower().Contains(modify.DataType.ToLower()))) && _repository.DataBaseTypes == DataBaseTypes.PostgreSql)
codeToDataBaseMerge.Sql.Append($"\nALTER TABLE {tableName.GetName(_repository.DataBaseTypes)} ALTER COLUMN [{prop.GetPropertyName()}] TYPE {prop.GetDbTypeByType(_repository.DataBaseTypes)}, ALTER COLUMN [{prop.GetPropertyName()}] SET DEFAULT {Querys.GetValueByTypeSTRING(MethodHelper.ConvertValue(null, propType), _repository.DataBaseTypes)};");
}
}
else if (!prop.IsInternalType && !prop.ContainAttribute<JsonDoreplacedent>() && !prop.ContainAttribute<XmlDoreplacedent>())
GetDatabase_Diff(prop.PropertyType, str, createdTables);
else
{
codeToDataBaseMerge.Sql.Append(string.Format("\nALTER TABLE {0} ADD " + (_repository.DataBaseTypes == DataBaseTypes.PostgreSql ? "COLUMN" : "") + " [{1}] {2} {3} DEFAULT {4};", tableName.GetName(_repository.DataBaseTypes), prop.GetPropertyName(), prop.GetDbTypeByType(_repository.DataBaseTypes),
(Nullable.GetUnderlyingType(propType) != null || propType == typeof(string)) && !prop.ContainAttribute<NotNullable>() ? " NULL" : " NOT NULL", Querys.GetValueByTypeSTRING(MethodHelper.ConvertValue(null, propType), _repository.DataBaseTypes)));
}
}
}
var colRemove = new CodeToDataBaseMerge() { Object_Type = tableType };
// Now lets clean the table and remove unused columns
foreach (var col in table.Values.Where(x =>
!props.Any(a => string.Equals(x.ColumnName, a.GetPropertyName(), StringComparison.CurrentCultureIgnoreCase) &&
(a.GetDbTypeByType(_repository.DataBaseTypes) != null || (!a.IsInternalType || a.ContainAttribute<JsonDoreplacedent>() || a.ContainAttribute<XmlDoreplacedent>())) &&
!a.ContainAttribute<ExcludeFromAbstract>())))
{
if (_repository.DataBaseTypes != DataBaseTypes.Sqllight)
{
if (_repository.DataBaseTypes == DataBaseTypes.Mssql)
{
var constraine = Properties.Resources.DropContraine
.Replace("@tb", $"'{tableName.Name}'")
.Replace("@col", $"'{col.ColumnName}'")
.Replace("@schema", $"'{tableName.Schema ?? ""}'")
.Replace("@TableName", "@" + counter++)
.Replace("@ColumnName", "@" + counter++)
.Replace("@fullName", "@" + counter++)
.Replace("@DROP_COMMAND", "@" + counter++)
.Replace("@FOREIGN_KEY_NAME", "@" + counter++);
colRemove.Sql.Append(constraine);
}
colRemove.Sql.Append(string.Format("\nALTER TABLE {0} DROP COLUMN IF EXISTS [{1}];", tableName.GetName(_repository.DataBaseTypes), col.ColumnName));
}
else
{
colRemove.Sql.Append(string.Format("DROP TABLE IF exists [{0}_temp];\nCREATE TABLE [{0}_temp] AS SELECT {1} FROM [{0}];", tableName.Name, string.Join(",", table.Values.ToList().FindAll(x =>
props.Any(a => string.Equals(x.ColumnName, a.GetPropertyName(), StringComparison.CurrentCultureIgnoreCase) &&
(a.GetDbTypeByType(_repository.DataBaseTypes) != null || !a.IsInternalType) &&
!a.ContainAttribute<ExcludeFromAbstract>())).Select(x => x.ColumnName))));
colRemove.Sql.Append(string.Format("DROP TABLE [{0}];\n", tableName.Name));
colRemove.Sql.Append(string.Format("ALTER TABLE [{0}_temp] RENAME TO [{0}]; ", tableName.Name));
}
colRemove.DataLoss = true;
}
str.Add(colRemove);
foreach (var prop in props.Where(x => !x.IsInternalType && !x.ContainAttribute<JsonDoreplacedent>() && !x.ContainAttribute<XmlDoreplacedent>() && !x.ContainAttribute<XmlDoreplacedent>() && !x.ContainAttribute<ExcludeFromAbstract>()).GroupBy(x => x.Name).Select(x => x.First()))
{
var type = prop.PropertyType.GetActualType();
if (type.GetPrimaryKey() != null)
GetDatabase_Diff(type, str, createdTables);
}
str.Add(codeToDataBaseMerge);
return str;
}
See More Examples