System.Activator.CreateInstance(System.ActivationContext, string[])

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

2373 Examples 7

19 View Source File : CodeActionWithNestedActionsFabric.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static CodeAction CreateCodeActionWithNestedActions(string groupActionreplacedle, ImmutableArray<CodeAction> nestedCodeActions,
																   bool isInlinable = false)
		{
			groupActionreplacedle.ThrowOnNullOrWhiteSpace(nameof(groupActionreplacedle));

			if (nestedCodeActions.IsDefaultOrEmpty)
				return null;

			InitializeSharedStaticData();

			if (_codeActionWithNestedActionsType == null || _roslynOldApiUsed == null)
				return null;

			try
			{
				if (_roslynOldApiUsed.Value)
				{
					return Activator.CreateInstance(_codeActionWithNestedActionsType, groupActionreplacedle, nestedCodeActions, isInlinable) as CodeAction;
				}
				else if (_lowCodeActionPriorityInstance != null)
				{
					return Activator.CreateInstance(_codeActionWithNestedActionsType, groupActionreplacedle, nestedCodeActions,
													isInlinable, _lowCodeActionPriorityInstance) as CodeAction;
				}
				else
					return null;
			}
			catch (Exception e) when (e is MissingMemberException || e is KeyNotFoundException || e is InvalidCastException)
			{
				return null;
			}
		}

19 View Source File : FederationCrmConfigurationManager.cs
License : MIT License
Project Creator : Adoxio

private static FederationCrmConfigurationProvider CreateProvider()
		{
			var section = ConfigurationManager.GetSection(IdenreplacedyModelSection.SectionName) as IdenreplacedyModelSection ?? new IdenreplacedyModelSection();

			if (!string.IsNullOrWhiteSpace(section.ConfigurationProviderType))
			{
				var typeName = section.ConfigurationProviderType;
				var type = TypeExtensions.GetType(typeName);

				if (type == null || !type.IsA<FederationCrmConfigurationProvider>())
				{
					throw new ConfigurationErrorsException("The value '{0}' is not recognized as a valid type or is not of the type '{1}'.".FormatWith(typeName, typeof(FederationCrmConfigurationProvider)));
				}

				return Activator.CreateInstance(type) as FederationCrmConfigurationProvider;
			}

			return new FederationCrmConfigurationProvider();
		}

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

public T CreateData<T>() where T : DataMessage
        {
            var ret = Activator.CreateInstance(typeof(T), ConnectionInformation.AmfEncodingVersion);
            return ret as T;
        }

19 View Source File : DatTests.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[TestMethod]
        public void UnpackCellDatFiles_NoExceptions()
        {
            var replacedembly = typeof(DatDatabase).GetTypeInfo().replacedembly;
            var types = replacedembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(DatFileTypeAttribute), false).Length > 0).ToList();

            if (types.Count == 0)
                throw new Exception("Failed to locate any types with DatFileTypeAttribute.");

            DatDatabase dat = new DatDatabase(cellDatLocation);

            foreach (var kvp in dat.AllFiles)
            {
                if (kvp.Key == 0xFFFF0001) // Not sure what this is, EOF record maybe?
                    continue;

                if (kvp.Value.FileSize == 0) // DatFileType.LandBlock files can be empty
                    continue;

                var fileType = kvp.Value.GetFileType(DatDatabaseType.Cell);

                if ((kvp.Key & 0xFFFF) == 0xFFFE) fileType = DatFileType.LandBlockInfo;
                if ((kvp.Key & 0xFFFF) == 0xFFFF) fileType = DatFileType.LandBlock;

                //replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}, BitFlags:, 0x{kvp.Value.BitFlags:X8}");
                replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}");

                var type = types
                    .SelectMany(m => m.GetCustomAttributes(typeof(DatFileTypeAttribute), false), (m, a) => new { m, a })
                    .Where(t => ((DatFileTypeAttribute)t.a).FileType == fileType)
                    .Select(t => t.m);

                var first = type.FirstOrDefault();

                if (first == null)
                    throw new Exception($"Failed to Unpack fileType: {fileType}");

                var obj = Activator.CreateInstance(first);

                var unpackable = obj as IUnpackable;

                if (unpackable == null)
                    throw new Exception($"Clreplaced for fileType: {fileType} does not implement IUnpackable.");

                var datReader = new DatReader(cellDatLocation, kvp.Value.FileOffset, kvp.Value.FileSize, dat.Header.BlockSize);

                using (var memoryStream = new MemoryStream(datReader.Buffer))
                using (var reader = new BinaryReader(memoryStream))
                {
                    unpackable.Unpack(reader);

                    if (memoryStream.Position != kvp.Value.FileSize)
                        throw new Exception($"Failed to parse all bytes for fileType: {fileType}, ObjectId: 0x{kvp.Value.ObjectId:X8}. Bytes parsed: {memoryStream.Position} of {kvp.Value.FileSize}");
                }
            }
        }

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

private MixedRealityInteractionMapping[] GetDefaultInteractionMappings()
        {
            if (Activator.CreateInstance(controllerType, TrackingState.NotTracked, handedness, null, null) is BaseController detectedController)
            {
                switch (handedness)
                {
                    case Handedness.Left:
                        return detectedController.DefaultLeftHandedInteractions;
                    case Handedness.Right:
                        return detectedController.DefaultRightHandedInteractions;
                    default:
                        return detectedController.DefaultInteractions;
                }
            }

            return null;
        }

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

public static Task Invoke(Kernel kernel, RadiumContext context)
        {
            DefaultResponseBody responseBody = new DefaultResponseBody();

            var req = context.Request;
            var res = context.Response;


            string reqContentType = req.ContentType;
            if (String.IsNullOrEmpty(reqContentType))
                reqContentType = "application/json";
            else
                reqContentType = reqContentType.ToLower();

            PathExecutionParams exeParams = ResourceRepository.Repo[req.Method, req.Path.Value];

            try
            {
                if (exeParams != null)
                {

                    Filters.FilterChainResponse chainResponse =  kernel.FilterManager.ExecuteChain();
                    bool isSuccess = chainResponse.LastResponse !=null ? chainResponse.LastResponse.Success : true;

                    if (!isSuccess)
                    {
                        res.ContentType = reqContentType;
                        responseBody.success = false; 
                        responseBody.result = chainResponse.LastResponse.Message;
                        responseBody.error = chainResponse.LastResponse.Error;
                        res.StatusCode = chainResponse.LastResponse.StatusCode;
                    }
                    else
                    {
                        RestResourceHandler newObj = (RestResourceHandler)Activator.CreateInstance(exeParams.ExecutionInfo.Type);
                        newObj.OContext = context;
                        newObj.DataBag = chainResponse.FilterResponse;
                        var exeMethod = exeParams.ExecutionInfo.Method;
                        List<object> activatorParams = new List<object>();
                        var methodParams = exeMethod.GetParameters();

                        foreach (var mParam in methodParams)
                        {
                            if (exeParams.Parameters.ContainsKey(mParam.Name))
                            {
                                var strValue = exeParams.Parameters[mParam.Name];
                                object convertedValue = Convert.ChangeType(strValue, mParam.ParameterType);
                                activatorParams.Add(convertedValue);
                            }
                            else
                            {
                                throw new ParameterMismatchException();
                            }
                        }

                        object output = exeMethod.Invoke(newObj, activatorParams.ToArray());
                        responseBody.success = true;
                        responseBody.result = output;
                        res.ContentType = reqContentType;
                    }

                }
                else
                {
                    res.ContentType = reqContentType;
                    responseBody.success = false;
                    responseBody.result = "404 Not Found";
                    res.StatusCode = 404;
                }
            }
            catch (Exception ex) 
            {
                res.ContentType = reqContentType;
                responseBody.success = false;
                responseBody.result = ex;
                res.StatusCode = 500;
            }

            var formatter = kernel.ResponseFormatter.GetFormatter(reqContentType);
            return res.WriteAsync(formatter.Format(responseBody));
        }

19 View Source File : CompositeObjectCache.cs
License : MIT License
Project Creator : Adoxio

public virtual void Initialize(string name, NameValueCollection config)
		{
			_name = name;

			if (config != null && Cache == null)
			{
				var innerTypeName = config["innerType"];

				if (!string.IsNullOrWhiteSpace(innerTypeName))
				{
					// instantiate by type

					var innerType = TypeExtensions.GetType(innerTypeName);

					if (innerType == typeof(MemoryCache))
					{
						Cache = new MemoryCache(name, config);
					}
					else if (innerType.IsA<MemoryCache>())
					{
						Cache = Activator.CreateInstance(innerType, name, config) as ObjectCache;
					}
					else
					{
						Cache = Activator.CreateInstance(innerType) as ObjectCache;
					}
				}

				var innerObjectCacheName = config["innerObjectCacheName"];

				if (!string.IsNullOrWhiteSpace(innerObjectCacheName))
				{
					// instantiate by config

					Cache = CrmConfigurationManager.CreateObjectCache(innerObjectCacheName);
				}
			}

			if (Cache == null)
			{
				// fall back to MemoryCache

				Cache = new MemoryCache(name, config);
			}
		}

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

public static IApplicationBuilder UseModules(this IApplicationBuilder app, IModuleCollection modules)
    {

        foreach (var module in modules)
        {
            if (module?.Layerreplacedemblies == null)
                continue;

            var replacedembly = module.Layerreplacedemblies.Web ?? module.Layerreplacedemblies.Api;
            if (replacedembly == null)
                continue;

            var middlewareConfigurator = replacedembly.GetTypes().FirstOrDefault(m => typeof(IModuleMiddlewareConfigurator).IsreplacedignableFrom(m));
            if (middlewareConfigurator != null)
            {
                ((IModuleMiddlewareConfigurator)Activator.CreateInstance(middlewareConfigurator))?.Configure(app);
            }
        }

        return app;
    }

19 View Source File : MessagePayloadSerializerFactory.cs
License : MIT License
Project Creator : Adyen

internal IMessagePayloadSerializer<IMessagePayload> CreateSerializer(string messageCategory, string messageType)
        {
            var messagePayoadFullName = CreateMessagePayloadFullName(messageCategory, messageType);
            var messagePayloadSerializer = TypeHelper.CreateGenericTypeFromStringFullNamespace(typeof(MessagePayloadSerializer<>), messagePayoadFullName);

            return (IMessagePayloadSerializer<IMessagePayload>)Activator.CreateInstance(messagePayloadSerializer);
        }

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

private static ITemplateOutput Complie(string cscode, string typename) {
			var replacedemly = _compiler.Value.CompileCode(cscode);
			var type = replacedemly.DefinedTypes.Where(a => a.FullName.EndsWith(typename)).FirstOrDefault();
			return Activator.CreateInstance(type) as ITemplateOutput;
		}

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

private static void EventChanged(Type newType, SerializedProperty evenreplacedem)
        {
            SerializedProperty clreplacedName = evenreplacedem.FindPropertyRelative("ClreplacedName");
            SerializedProperty replacedemblyQualifiedName = evenreplacedem.FindPropertyRelative("replacedemblyQualifiedName");

            clreplacedName.stringValue = newType.Name;
            replacedemblyQualifiedName.stringValue = newType.replacedemblyQualifiedName;

            SerializedProperty settings = evenreplacedem.FindPropertyRelative("Settings");

            ReceiverBase defaultReceiver = (ReceiverBase)Activator.CreateInstance(newType, new UnityEvent());
            InspectorFieldsUtility.ClearSettingsList(settings, InspectorFieldsUtility.GetInspectorFields(defaultReceiver));
        }

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

protected override GenericJoystickController GetOrAddController(string joystickName)
        {
            using (GetOrAddControllerPerfMarker.Auto())
            {
                // If a device is already registered with the ID provided, just return it.
                if (ActiveControllers.ContainsKey(joystickName))
                {
                    var controller = ActiveControllers[joystickName];
                    Debug.replacedert(controller != null);
                    return controller;
                }

                Handedness controllingHand;

                if (joystickName.Contains("Left"))
                {
                    controllingHand = Handedness.Left;
                }
                else if (joystickName.Contains("Right"))
                {
                    controllingHand = Handedness.Right;
                }
                else
                {
                    controllingHand = Handedness.None;
                }

                var currentControllerType = GetCurrentControllerType(joystickName);
                Type controllerType;

                switch (currentControllerType)
                {
                    case SupportedControllerType.GenericOpenVR:
                        controllerType = typeof(GenericOpenVRController);
                        break;
                    case SupportedControllerType.ViveWand:
                        controllerType = typeof(ViveWandController);
                        break;
                    case SupportedControllerType.ViveKnuckles:
                        controllerType = typeof(ViveKnucklesController);
                        break;
                    case SupportedControllerType.OculusTouch:
                        controllerType = typeof(OculusTouchController);
                        break;
                    case SupportedControllerType.OculusRemote:
                        controllerType = typeof(OculusRemoteController);
                        break;
                    case SupportedControllerType.WindowsMixedReality:
                        controllerType = typeof(WindowsMixedRealityOpenVRMotionController);
                        break;
                    default:
                        return null;
                }

                IMixedRealityInputSystem inputSystem = Service as IMixedRealityInputSystem;

                var pointers = RequestPointers(currentControllerType, controllingHand);
                var inputSource = inputSystem?.RequestNewGenericInputSource($"{currentControllerType} Controller {controllingHand}", pointers, InputSourceType.Controller);
                var detectedController = Activator.CreateInstance(controllerType, TrackingState.NotTracked, controllingHand, inputSource, null) as GenericOpenVRController;

                if (detectedController == null || !detectedController.Enabled)
                {
                    // Controller failed to be set up correctly.
                    Debug.LogError($"Failed to create {controllerType.Name} controller");

                    // Return null so we don't raise the source detected.
                    return null;
                }

                for (int i = 0; i < detectedController.InputSource?.Pointers?.Length; i++)
                {
                    detectedController.InputSource.Pointers[i].Controller = detectedController;
                }

                ActiveControllers.Add(joystickName, detectedController);

                return detectedController;
            }
        }

19 View Source File : ResponsePacketProcessor.cs
License : MIT License
Project Creator : 499116344

public IPacketCommand Process()
        {
            var receivePackageCommandAttributes = _receivePacketType.GetCustomAttributes<ReceivePacketCommand>();
            if (receivePackageCommandAttributes.Any())
            {
                var packetCommand = receivePackageCommandAttributes.First().Command;
                var types = replacedembly.GetExecutingreplacedembly().GetTypes();
                foreach (var type in types)
                {
                    var attributes = type.GetCustomAttributes<ResponsePacketCommand>();
                    if (!attributes.Any())
                    {
                        continue;
                    }

                    var responseCommand = attributes.First().Command;
                    if (responseCommand == packetCommand)
                    {
                        return Activator.CreateInstance(type, _args) as IPacketCommand;
                    }
                }
            }

            return new DefaultResponseCommand(new QQEventArgs<ReceivePacket>(_args.Service, _args.User,
                _args.ReceivePacket));
        }

19 View Source File : DatTests.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[TestMethod]
        public void UnpackLocalEnglishDatFiles_NoExceptions()
        {
            var replacedembly = typeof(DatDatabase).GetTypeInfo().replacedembly;
            var types = replacedembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(DatFileTypeAttribute), false).Length > 0).ToList();

            if (types.Count == 0)
                throw new Exception("Failed to locate any types with DatFileTypeAttribute.");

            DatDatabase dat = new DatDatabase(localEnglishDatLocation);

            foreach (var kvp in dat.AllFiles)
            {
                if (kvp.Key == 0xFFFF0001) // Not sure what this is, EOF record maybe?
                    continue;

                var fileType = kvp.Value.GetFileType(DatDatabaseType.Language);

                //replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}, BitFlags:, 0x{kvp.Value.BitFlags:X8}");
                replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}");

                // These file types aren't converted yet
                if (fileType == DatFileType.UiLayout) continue;

                var type = types
                    .SelectMany(m => m.GetCustomAttributes(typeof(DatFileTypeAttribute), false), (m, a) => new { m, a })
                    .Where(t => ((DatFileTypeAttribute)t.a).FileType == fileType)
                    .Select(t => t.m);

                var first = type.FirstOrDefault();

                if (first == null)
                    throw new Exception($"Failed to Unpack fileType: {fileType}");

                var obj = Activator.CreateInstance(first);

                var unpackable = obj as IUnpackable;

                if (unpackable == null)
                    throw new Exception($"Clreplaced for fileType: {fileType} does not implement IUnpackable.");

                var datReader = new DatReader(localEnglishDatLocation, kvp.Value.FileOffset, kvp.Value.FileSize, dat.Header.BlockSize);

                using (var memoryStream = new MemoryStream(datReader.Buffer))
                using (var reader = new BinaryReader(memoryStream))
                {
                    unpackable.Unpack(reader);

                    if (memoryStream.Position != kvp.Value.FileSize)
                        throw new Exception($"Failed to parse all bytes for fileType: {fileType}, ObjectId: 0x{kvp.Value.ObjectId:X8}. Bytes parsed: {memoryStream.Position} of {kvp.Value.FileSize}");
                }
            }
        }

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

private void LoadRepositories()
    {
        if (_repositoryreplacedemblies.IsNullOrEmpty())
            return;

        foreach (var replacedembly in _repositoryreplacedemblies)
        {
            /*
             * 仓储约定:
             * 1、仓储统一放在Repositories目录中
             * 2、仓储默认使用SqlServer数据库,如果数据库之间有差异无法通过ORM规避时,采用以下方式解决:
             *    a)将对应的方法定义为虚函数
             *    b)假如当前方法在MySql中实现有差异,则在Repositories新建一个MySql目录
             *    c)在MySql目录中新建一个仓储(我称之为兼容仓储)并继承默认仓储
             *    d)在新建的兼容仓储中使用MySql语法重写对应的方法
             */

            var repositoryTypes = replacedembly.GetTypes()
                .Where(m => !m.IsInterface && typeof(IRepository).IsImplementType(m))
                //排除兼容仓储
                .Where(m => m.FullName!.Split('.')[^2].EqualsIgnoreCase("Repositories"))
                .ToList();

            //兼容仓储列表
            var compatibilityRepositoryTypes = replacedembly.GetTypes()
                .Where(m => !m.IsInterface && typeof(IRepository).IsImplementType(m))
                //根据数据库类型来过滤
                .Where(m => m.FullName!.Split('.')[^2].EqualsIgnoreCase(Options.Provider.ToString()))
                .ToList();

            foreach (var type in repositoryTypes)
            {
                //按照框架约定,仓储的第三个接口类型就是所需的仓储接口
                var interfaceType = type.GetInterfaces()[2];

                //按照约定,仓储接口的第一个接口的泛型参数即为对应实体类型
                var enreplacedyType = interfaceType.GetInterfaces()[0].GetGenericArguments()[0];
                //保存实体描述符
                DbContext.EnreplacedyDescriptors.Add(new EnreplacedyDescriptor(DbContext, enreplacedyType));

                //优先使用兼容仓储
                var implementationType = compatibilityRepositoryTypes.FirstOrDefault(m => m.Name == type.Name) ?? type;

                Services.AddScoped(interfaceType, sp =>
                {
                    var instance = Activator.CreateInstance(implementationType);
                    var initMethod = implementationType.GetMethod("Init", BindingFlags.Instance | BindingFlags.NonPublic);
                    initMethod!.Invoke(instance, new Object[] { DbContext });

                    //保存仓储实例
                    var manager = sp.GetService<IRepositoryManager>();
                    manager?.Add((IRepository)instance);

                    return instance;
                });

                //保存仓储描述符
                DbContext.RepositoryDescriptors.Add(new RepositoryDescriptor(enreplacedyType, interfaceType, implementationType));
            }
        }
    }

19 View Source File : ContentMap.cs
License : MIT License
Project Creator : Adoxio

private static EnreplacedyNode ToEnreplacedyIdentifier(EnreplacedyNode node)
		{
			var identifier = node != null
				? Activator.CreateInstance(node.GetType(), node.ToEnreplacedyReference()) as EnreplacedyNode
				: null;

			return identifier;
		}

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

public Message Provide(MessageHeader header, SerializationContext context, out int consumed)
        {
            string name = null;
            bool amf3 = false;
            if (header.MessageType == MessageType.Amf0Command)
            {
                if (!context.Amf0Reader.TryGetString(context.ReadBuffer.Span, out name, out consumed))
                {
                    throw new ProtocolViolationException();
                }
            }
            else if (header.MessageType == MessageType.Amf3Command)
            {
                amf3 = true;
                if (!context.Amf3Reader.TryGetString(context.ReadBuffer.Span, out name, out consumed))
                {
                    throw new ProtocolViolationException();
                }
            }
            else
            {
                throw new InvalidOperationException();
            }
            if (!_messageFactories.TryGetValue(name, out var t))
            {
                throw new NotSupportedException();
            }
            var ret = (CommandMessage)Activator.CreateInstance(t, amf3 ? AmfEncodingVersion.Amf3 : AmfEncodingVersion.Amf0);
            ret.ProcedureName = name;
            return ret;
        }

19 View Source File : ObjectCacheManager.cs
License : MIT License
Project Creator : Adoxio

private static ObjectCacheProvider CreateProvider()
		{
			var section = CrmConfigurationManager.GetCrmSection();

			if (!string.IsNullOrWhiteSpace(section.ObjectCacheProviderType))
			{
				var typeName = section.ObjectCacheProviderType;
				var type = TypeExtensions.GetType(typeName);

				if (type == null || !type.IsA<ObjectCacheProvider>())
				{
					throw new ConfigurationErrorsException("The value '{0}' is not recognized as a valid type or is not of the type '{1}'.".FormatWith(typeName, typeof(ObjectCacheProvider)));
				}

				return Activator.CreateInstance(type) as ObjectCacheProvider;
			}

			return new ObjectCacheProvider();
		}

19 View Source File : TableClassGeneratorTest.cs
License : MIT License
Project Creator : 0x1000000

[Test]
        public async Task BasicTest()
        {

            using var dbManager = new DbManager(new DbManagerTest(),
                new SqlConnection("Initial Catalog=_1_2_3tbl;"),
                new GenTablesOptions(ConnectionType.MsSql, "fake", "Tab", "", "MyTables", verbosity: Verbosity.Quiet));

            var tables = await dbManager.SelectTables();

            replacedert.AreEqual(2, tables.Count);

            var tableMap = tables.ToDictionary(t => t.DbName);

            IReadOnlyDictionary<TableRef, ClreplacedDeclarationSyntax> existingCode =
                new Dictionary<TableRef, ClreplacedDeclarationSyntax>();

            var generator =
                new TableClreplacedGenerator(tableMap, "MyCompany.MyProject.Tables", existingCode);


            var trees = tables.Select(t => CSharpSyntaxTree.Create(generator.Generate(t, out _))).ToList();

            var compilation = CSharpCompilation.Create("Tables",
                trees,
                options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            compilation = compilation.AddReferences(
                MetadataReference.CreateFromFile(replacedembly.Load("netstandard, Version=2.0.0.0").Location),
                MetadataReference.CreateFromFile(typeof(object).replacedembly.GetreplacedemblyLocation()),
                MetadataReference.CreateFromFile(replacedembly
                    .Load("System.Runtime, Version=4.2.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
                    .Location),
                MetadataReference.CreateFromFile(typeof(SqQueryBuilder).replacedembly.GetreplacedemblyLocation()));

            MemoryStream ms = new MemoryStream();

            var emitResult = compilation.Emit(ms);
            if (!emitResult.Success)
            {
                replacedert.Fail(emitResult.Diagnostics.FirstOrDefault()?.GetMessage());
            }

            var replacedembly = replacedembly.Load(ms.ToArray());

            var allTypes = replacedembly.GetTypes();

            var table1 = (TableBase) Activator.CreateInstance(allTypes.Find(t => t.Name == tables[0].Name));
            replacedert.NotNull(table1);
            var table2 = (TableBase) Activator.CreateInstance(allTypes.Find(t => t.Name == tables[1].Name));
            replacedert.NotNull(table2);


            string table1ExpectedSql =
                "CREATE TABLE [dbo].[TableZ]([Id] int NOT NULL  IDENreplacedY (1, 1) DEFAULT (0),[ValueA] [nvarchar](255) NOT NULL DEFAULT (''),[Value_A] decimal(2,6),CONSTRAINT [PK_dbo_TableZ] PRIMARY KEY ([Id]));";
            replacedert.AreEqual(table1ExpectedSql, TSqlExporter.Default.ToSql(table1.Script.Create()));

            string table2ExpectedSql =
                "CREATE TABLE [dbo].[TableA]([Id] int NOT NULL  IDENreplacedY (1, 1) DEFAULT (0),[Value] datetime NOT NULL DEFAULT (GETUTCDATE()),CONSTRAINT [PK_dbo_TableA] PRIMARY KEY ([Id]),CONSTRAINT [FK_dbo__TableA_to_dbo__TableZ] FOREIGN KEY ([Id]) REFERENCES [dbo].[TableZ]([Id]),INDEX [IX_dbo_TableA_Value_DESC] UNIQUE([Value] DESC));";
            replacedert.AreEqual(table2ExpectedSql, TSqlExporter.Default.ToSql(table2.Script.Create()));
        }

19 View Source File : DefaultPageController.cs
License : Apache License 2.0
Project Creator : advanced-cms

private static IPageViewModel<SitePageData> CreateModel(SitePageData page)
        {
            var type = typeof(PageViewModel<>).MakeGenericType(page.GetOriginalType());
            return Activator.CreateInstance(type, page) as IPageViewModel<SitePageData>;
        }

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 : AppenderFactory.cs
License : MIT License
Project Creator : Abc-Arbitrage

public static IAppender CreateAppender(AppenderDefinition definition)
        {
            var appenderType = GetAppenderType(definition) ?? throw new InvalidOperationException($"Appender type not found: {definition.AppenderTypeName}");

            var appender = (IAppender)Activator.CreateInstance(appenderType)!;
            appender.Name = definition.Name;

            var appenderParameterType = GetAppenderParameterType(appenderType);
            if (appenderParameterType != null)
            {
                var appenderParameters = GetAppenderParameters(definition, appenderParameterType);

                var configureMethod = appenderType.GetMethod(nameof(IAppender<object>.Configure), new[] { appenderParameterType });
                configureMethod?.Invoke(appender, new[] { appenderParameters });
            }

            return appender;
        }

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

private void AddConfigCore(ModuleConfigureContext context)
    {
        var configProvider = new DefaultConfigProvider();

        //添加通用配置
        var commonConfig = new CommonConfig();
        context.Configuration.GetSection("Mkh:Common").Bind(commonConfig);
        if (commonConfig.TempDir.IsNull())
        {
            commonConfig.TempDir = Path.Combine(AppContext.BaseDirectory, "Temp");
        }

        configProvider.Configs.Add(typeof(CommonConfig).TypeHandle, commonConfig);

        foreach (var module in context.Modules)
        {
            var configType = module.Layerreplacedemblies.Core.GetTypes().FirstOrDefault(m => typeof(IConfig).IsImplementType(m));
            if (configType != null)
            {
                var instance = Activator.CreateInstance(configType);
                context.Configuration.GetSection($"Mkh:Modules:{module.Code}:Config").Bind(instance);

                configProvider.Configs.Add(configType.TypeHandle, (IConfig)instance);
            }
        }

        context.Services.AddSingleton<IConfigProvider>(configProvider);
    }

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

protected virtual GenericJoystickController GetOrAddController(string joystickName)
        {
            using (GetOrAddControllerPerfMarker.Auto())
            {
                IMixedRealityInputSystem inputSystem = Service as IMixedRealityInputSystem;

                if (ActiveControllers.ContainsKey(joystickName))
                {
                    var controller = ActiveControllers[joystickName];
                    Debug.replacedert(controller != null);
                    return controller;
                }

                Type controllerType;

                switch (GetCurrentControllerType(joystickName))
                {
                    default:
                        return null;
                    case SupportedControllerType.GenericUnity:
                        controllerType = typeof(GenericJoystickController);
                        break;
                    case SupportedControllerType.Xbox:
                        controllerType = typeof(XboxController);
                        break;
                }

                var inputSource = inputSystem?.RequestNewGenericInputSource($"{controllerType.Name} Controller", sourceType: InputSourceType.Controller);
                var detectedController = Activator.CreateInstance(controllerType, TrackingState.NotTracked, Handedness.None, inputSource, null) as GenericJoystickController;

                if (detectedController == null || !detectedController.Enabled)
                {
                    // Controller failed to be setup correctly.
                    Debug.LogError($"Failed to create {controllerType.Name} controller");

                    // Return null so we don't raise the source detected.
                    return null;
                }

                ActiveControllers.Add(joystickName, detectedController);

                return detectedController;
            }
        }

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

public override IDbSet Set(Type enreplacedyType) {
			if (_dicSet.ContainsKey(enreplacedyType)) return _dicSet[enreplacedyType];

			var tb = _orm.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
			if (tb == null) return null;

			object repos = _repos;
			if (enreplacedyType != _repos.EnreplacedyType) {
				repos = Activator.CreateInstance(typeof(DefaultRepository<,>).MakeGenericType(enreplacedyType, typeof(int)), _repos.Orm);
				(repos as IBaseRepository).UnitOfWork = _repos.UnitOfWork;
				GetRepositoryDbField(enreplacedyType).SetValue(repos, this);

				typeof(RepositoryDbContext).GetMethod("SetRepositoryDataFilter").MakeGenericMethod(_repos.EnreplacedyType)
					.Invoke(null, new object[] { repos, _repos });
			}

			var sd = Activator.CreateInstance(typeof(RepositoryDbSet<>).MakeGenericType(enreplacedyType), repos) as IDbSet;
			if (enreplacedyType != typeof(object)) _dicSet.Add(enreplacedyType, sd);
			return sd;
		}

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

public static bool RenderEvent(SerializedProperty evenreplacedem, bool canRemove = true)
        {
            using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox))
            {
                SerializedProperty uEvent = evenreplacedem.FindPropertyRelative("Event");
                SerializedProperty eventName = evenreplacedem.FindPropertyRelative("Name");
                SerializedProperty clreplacedName = evenreplacedem.FindPropertyRelative("ClreplacedName");
                SerializedProperty replacedemblyQualifiedName = evenreplacedem.FindPropertyRelative("replacedemblyQualifiedName");
                Type receiverType;

                InspectorUIUtility.DrawHeader("Event Receiver Type");
                using (new EditorGUILayout.HorizontalScope())
                {
                    Rect position = EditorGUILayout.GetControlRect();
                    using (new EditorGUI.PropertyScope(position, SelectEventLabel, clreplacedName))
                    {
                        var receiverTypes = TypeCacheUtility.GetSubClreplacedes<ReceiverBase>();
                        var recevierClreplacedNames = receiverTypes.Select(t => t?.Name).ToArray();
                        int id = Array.IndexOf(recevierClreplacedNames, clreplacedName.stringValue);
                        int newId = EditorGUI.Popup(position, id, recevierClreplacedNames);
                        if (newId == -1) { newId = 0; }

                        receiverType = receiverTypes[newId];

                        // Temporary workaround to fix bug shipped in GA where replacedemblyQualifiedName was never set
                        if (string.IsNullOrEmpty(replacedemblyQualifiedName.stringValue))
                        {
                            replacedemblyQualifiedName.stringValue = receiverType.replacedemblyQualifiedName;
                        }

                        if (id != newId)
                        {
                            EventChanged(receiverType, evenreplacedem);
                        }
                    }

                    if (canRemove)
                    {
                        if (InspectorUIUtility.FlexButton(new GUIContent("Remove Event")))
                        {
                            return true;
                        }
                    }
                }

                EditorGUILayout.Space();
                InspectorUIUtility.DrawHeader("Event Properties");

                ReceiverBase receiver = (ReceiverBase)Activator.CreateInstance(receiverType, new UnityEvent());

                if (!receiver.HideUnityEvents)
                {
                    EditorGUILayout.PropertyField(uEvent, new GUIContent(receiver.Name));
                }

                SerializedProperty eventSettings = evenreplacedem.FindPropertyRelative("Settings");

                // If fields for given receiver clreplaced type have been changed, update the related inspector field data
                var fieldList = InspectorFieldsUtility.GetInspectorFields(receiver);
                if (!InspectorFieldsUtility.AreFieldsSame(eventSettings, fieldList))
                {
                    InspectorFieldsUtility.UpdateSettingsList(eventSettings, fieldList);
                }

                for (int index = 0; index < eventSettings.arraySize; index++)
                {
                    SerializedProperty propertyField = eventSettings.GetArrayElementAtIndex(index);
                    bool isEvent = InspectorFieldsUtility.IsPropertyType(propertyField, InspectorField.FieldTypes.Event);

                    if (!receiver.HideUnityEvents || !isEvent)
                    {
                        InspectorFieldsUtility.DisplayPropertyField(eventSettings.GetArrayElementAtIndex(index));
                    }
                }
            }

            return false;
        }

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

protected virtual GenericXRSDKController GetOrAddController(InputDevice inputDevice)
        {
            using (GetOrAddControllerPerfMarker.Auto())
            {
                // If a device is already registered with the ID provided, just return it.
                if (ActiveControllers.ContainsKey(inputDevice))
                {
                    var controller = ActiveControllers[inputDevice];
                    Debug.replacedert(controller != null);
                    return controller;
                }

                Handedness controllingHand;

                if (inputDevice.characteristics.HasFlag(InputDeviceCharacteristics.Left))
                {
                    controllingHand = Handedness.Left;
                }
                else if (inputDevice.characteristics.HasFlag(InputDeviceCharacteristics.Right))
                {
                    controllingHand = Handedness.Right;
                }
                else
                {
                    controllingHand = Handedness.None;
                }

                var currentControllerType = GetCurrentControllerType(inputDevice);
                Type controllerType = GetControllerType(currentControllerType);
                InputSourceType inputSourceType = GetInputSourceType(currentControllerType);

                IMixedRealityInputSystem inputSystem = Service as IMixedRealityInputSystem;
                IMixedRealityPointer[] pointers = RequestPointers(currentControllerType, controllingHand);
                IMixedRealityInputSource inputSource = inputSystem?.RequestNewGenericInputSource($"{currentControllerType} Controller {controllingHand}", pointers, inputSourceType);
                GenericXRSDKController detectedController = Activator.CreateInstance(controllerType, TrackingState.NotTracked, controllingHand, inputSource, null) as GenericXRSDKController;

                if (detectedController == null || !detectedController.Enabled)
                {
                    // Controller failed to be set up correctly.
                    Debug.LogError($"Failed to create {controllerType.Name} controller");

                    // Return null so we don't raise the source detected.
                    return null;
                }

                for (int i = 0; i < detectedController.InputSource?.Pointers?.Length; i++)
                {
                    detectedController.InputSource.Pointers[i].Controller = detectedController;
                }

                ActiveControllers.Add(inputDevice, detectedController);

                return detectedController;
            }
        }

19 View Source File : DispatchPacketToCommand.cs
License : MIT License
Project Creator : 499116344

public IPacketCommand dispatch_receive_packet(QQCommand command)
        {
            var types = replacedembly.GetExecutingreplacedembly().GetTypes();
            foreach (var type in types)
            {
                var attributes = type.GetCustomAttributes();
                if (!attributes.Any(attr => attr is ReceivePacketCommand))
                {
                    continue;
                }

                var attribute = attributes.First(attr => attr is ReceivePacketCommand) as ReceivePacketCommand;
                if (attribute.Command == command)
                {
                    var receivePacket =
                        Activator.CreateInstance(type, _data, _service, _transponder, _user) as IPacketCommand;
                    return receivePacket;
                }
            }

            return new DefaultReceiveCommand(_data, _service, _transponder, _user);
        }

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

public static ReceiverBase CreateReceiver(InteractableEvent iEvent)
        {
            if (string.IsNullOrEmpty(iEvent.ClreplacedName))
            {
                // If the clreplaced name of this event is empty, the replacedet is invalid and loading types will throw errors. Return null.
                return null;
            }

            // Temporary workaround
            // This is to fix a bug in GA where the replacedemblyQualifiedName was never actually saved. Functionality would work in editor...but never on device player
            if (iEvent.ReceiverType == null)
            {
                var correctType = TypeCacheUtility.GetSubClreplacedes<ReceiverBase>().Where(s => s?.Name == iEvent.ClreplacedName).First();
                iEvent.ReceiverType = correctType;
            }

            ReceiverBase newEvent = (ReceiverBase)Activator.CreateInstance(iEvent.ReceiverType, iEvent.Event);
            InspectorGenericFields<ReceiverBase>.LoadSettings(newEvent, iEvent.Settings);

            return newEvent;
        }

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

private ICodeFirstProvider CreateCodeFirstProvider(string dbAdapterreplacedemblyName, replacedembly dbAdapterreplacedembly, IServiceCollection services)
    {
        var schemaProviderType = dbAdapterreplacedembly.GetType($"{dbAdapterreplacedemblyName}.{Options.Provider}CodeFirstProvider");
        return (ICodeFirstProvider)Activator.CreateInstance(schemaProviderType!, CodeFirstOptions, DbContext, services);
    }

19 View Source File : DatTests.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

[TestMethod]
        public void UnpackPortalDatFiles_NoExceptions()
        {
            var replacedembly = typeof(DatDatabase).GetTypeInfo().replacedembly;
            var types = replacedembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(DatFileTypeAttribute), false).Length > 0).ToList();

            if (types.Count == 0)
                throw new Exception("Failed to locate any types with DatFileTypeAttribute.");

            DatDatabase dat = new DatDatabase(portalDatLocation);

            foreach (var kvp in dat.AllFiles)
            {
                if (kvp.Key == 0xFFFF0001) // Not sure what this is, EOF record maybe?
                    continue;

                var fileType = kvp.Value.GetFileType(DatDatabaseType.Portal);

                //replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}, BitFlags:, 0x{kvp.Value.BitFlags:X8}");
                replacedert.IsNotNull(fileType, $"Key: 0x{kvp.Key:X8}, ObjectID: 0x{kvp.Value.ObjectId:X8}, FileSize: {kvp.Value.FileSize}");

                // These file types aren't converted yet
                if (fileType == DatFileType.KeyMap) continue;
                if (fileType == DatFileType.RenderMaterial) continue;
                if (fileType == DatFileType.MaterialModifier) continue;
                if (fileType == DatFileType.MaterialInstance) continue;
                if (fileType == DatFileType.ActionMap) continue;
                if (fileType == DatFileType.MasterProperty) continue;
                if (fileType == DatFileType.DbProperties) continue;

                var type = types
                    .SelectMany(m => m.GetCustomAttributes(typeof(DatFileTypeAttribute), false), (m, a) => new {m, a})
                    .Where(t => ((DatFileTypeAttribute) t.a).FileType == fileType)
                    .Select(t => t.m);

                var first = type.FirstOrDefault();

                if (first == null)
                    throw new Exception($"Failed to Unpack fileType: {fileType}");

                var obj = Activator.CreateInstance(first);

                var unpackable = obj as IUnpackable;

                if (unpackable == null)
                    throw new Exception($"Clreplaced for fileType: {fileType} does not implement IUnpackable.");

                var datReader = new DatReader(portalDatLocation, kvp.Value.FileOffset, kvp.Value.FileSize, dat.Header.BlockSize);

                using (var memoryStream = new MemoryStream(datReader.Buffer))
                using (var reader = new BinaryReader(memoryStream))
                {
                    unpackable.Unpack(reader);

                    if (memoryStream.Position != kvp.Value.FileSize)
                        throw new Exception($"Failed to parse all bytes for fileType: {fileType}, ObjectId: 0x{kvp.Value.ObjectId:X8}. Bytes parsed: {memoryStream.Position} of {kvp.Value.FileSize}");
                }
            }
        }

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

public void LoadExportedreplacedembly(string exportedreplacedemblyName)
        {
            var targetTypes = Utility.Reflection.GetImplTypes(exportedreplacedemblyName,typeof(ExportedreplacedemblyBase));
            if (0<targetTypes.Length)
            {
                var instance = Activator.CreateInstance(targetTypes[0]);
                var child = instance as ExportedreplacedemblyBase;
                child.replacedemblyName = exportedreplacedemblyName;
                child.OnExport(Framework.IoC);
                AddChildNode(instance as ExportedreplacedemblyBase);
            }
        }

19 View Source File : VssConnection.cs
License : MIT License
Project Creator : actions

private async Task<Object> GetClientInstanceAsync(
            Type managedType,
            Guid serviceIdentifier,
            CancellationToken cancellationToken,
            VssHttpRequestSettings settings,
            DelegatingHandler[] handlers)
        {
            CheckForDisposed();
            ILocationService locationService = await GetServiceAsync<ILocationService>(cancellationToken).ConfigureAwait(false);
            ILocationDataProvider locationData = await locationService.GetLocationDataAsync(serviceIdentifier, cancellationToken).ConfigureAwait(false);

            if (locationData == null)
            {
                throw new VssServiceException(WebApiResources.ServerDataProviderNotFound(serviceIdentifier));
            }

            String serviceLocationString = await locationData.LocationForCurrentConnectionAsync(
                ServiceInterfaces.LocationService2,
                LocationServiceConstants.SelfReferenceIdentifier,
                cancellationToken).ConfigureAwait(false);

            // This won't ever be null because of compat code in ServerDataProvider
            Uri clientBaseUri = new Uri(serviceLocationString);

            VssHttpClientBase toReturn = null;

            if (settings != null)
            {
                toReturn = (VssHttpClientBase)Activator.CreateInstance(managedType, clientBaseUri, Credentials, settings, handlers);
            }
            else
            {
                toReturn = (VssHttpClientBase)Activator.CreateInstance(managedType, clientBaseUri, m_pipeline, false /* disposeHandler */);
            }

            ApiResourceLocationCollection resourceLocations = await locationData.GetResourceLocationsAsync(cancellationToken).ConfigureAwait(false);
            toReturn.SetResourceLocations(resourceLocations);

            return toReturn;
        }

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

public DataType Read(CelesteNetBinaryReader reader) {
            PositionAwareStream? pas = reader.BaseStream as PositionAwareStream;
            pas?.ResetPosition();

            string id = reader.ReadNetMappedString();
            DataFlags flags = (DataFlags) reader.ReadUInt16();
            bool small = (flags & DataFlags.Small) == DataFlags.Small;
            bool big = (flags & DataFlags.Big) == DataFlags.Big;

            string source = reader.ReadNetMappedString();
            MetaTypeWrap[] metas = ReadMeta(reader);

            uint length = small ? reader.ReadByte() : big ? reader.ReadUInt32() : reader.ReadUInt16();
            long start = pas?.Position ?? 0;

            if (!IDToDataType.TryGetValue(id, out Type? type))
                return new DataUnparsed() {
                    InnerID = id,
                    InnerSource = source,
                    InnerFlags = flags,
                    InnerMeta = new(metas),
                    InnerData = reader.ReadBytes((int) length)
                };

            DataType? data = (DataType?) Activator.CreateInstance(type);
            if (data == null)
                throw new Exception($"Cannot create instance of data type {type.FullName}");

            try {
                data.UnwrapMeta(this, metas);
                data.Read(reader);
            } catch (Exception e) {
                throw new Exception($"Exception while reading {id} {flags} {source} {length}", e);
            }

            if (pas != null) {
                long lengthReal = pas.Position - start;
                if (lengthReal != length)
                    throw new Exception($"Length mismatch for {id} {flags} {source} {length} - got {lengthReal}");
            }

            return data;
        }

19 View Source File : RxNavigationPage.cs
License : MIT License
Project Creator : adospace

protected override void OnAddChild(VisualNode widget, BindableObject childNativeControl)
        {
            if (childNativeControl is Page page)
            {
                _nativeControl = (T)Activator.CreateInstance(typeof(T), page);
                base.OnMount();
                OnUpdate();
            }
            //else
            //{
            //    throw new InvalidOperationException($"Root must be a Page: received {childNativeControl.GetType()}");
            //}

            base.OnAddChild(widget, childNativeControl);
        }

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

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

            if (!TryDescribeData(buffer, out var type, out _))
            {
                return true;
            }

            if (type != Amf0Type.TypedObject)
            {
                return false;
            }

            var consumed = Amf0CommonValues.MARKER_LENGTH;

            if (!TryGetStringImpl(buffer.Slice(Amf0CommonValues.MARKER_LENGTH), Amf0CommonValues.STRING_HEADER_LENGTH, out var clreplacedName, out var stringLength))
            {
                return false;
            }

            consumed += stringLength;

            var objectBuffer = buffer.Slice(consumed);

            if (!TryGetObjectImpl(objectBuffer, out var dict, out var objectConsumed))
            {
                return false;
            }

            consumed += objectConsumed;

            if (!_registeredTypeStates.TryGetValue(clreplacedName, out var state))
            {
                return false;
            }
            var objectType = state.Type;
            var obj = Activator.CreateInstance(objectType);

            if (state.Members.Keys.Except(dict.Keys).Any())
            {
                return false;
            }
            else if (dict.Keys.Except(state.Members.Keys).Any())
            {
                return false;
            }

            foreach ((var name, var setter) in state.Members)
            {
                setter(obj, dict[name]);
            }

            value = obj;
            consumedLength = consumed;

            return true;
        }

19 View Source File : AdxstudioCrmConfigurationManager.cs
License : MIT License
Project Creator : Adoxio

private static AdxstudioCrmConfigurationProvider CreateProvider()
		{
			var section = ConfigurationManager.GetSection(CrmSection.SectionName) as CrmSection ?? new CrmSection();

			if (!string.IsNullOrWhiteSpace(section.ConfigurationProviderType))
			{
				var typeName = section.ConfigurationProviderType;
				var type = TypeExtensions.GetType(typeName);

				if (type == null || !type.IsA<AdxstudioCrmConfigurationProvider>())
				{
					throw new ConfigurationErrorsException("The value {0} is not recognized as a valid type or is not of the type {1}.".FormatWith(typeName, typeof(AdxstudioCrmConfigurationProvider)));
				}

				return Activator.CreateInstance(type) as AdxstudioCrmConfigurationProvider;
			}

			return new AdxstudioCrmConfigurationProvider();
		}

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

private void LoadServicesConfigurator(ModuleDescriptor descriptor)
    {
        if (descriptor.Layerreplacedemblies.Core != null)
        {
            var servicesConfiguratorType = descriptor.Layerreplacedemblies.Core.GetTypes()
                .FirstOrDefault(m => typeof(IModuleServicesConfigurator).IsreplacedignableFrom(m));

            if (servicesConfiguratorType != null)
            {
                descriptor.ServicesConfigurator =
                    (IModuleServicesConfigurator)Activator.CreateInstance(servicesConfiguratorType);
            }
        }
    }

19 View Source File : CmsEntityRelationshipHandler.cs
License : MIT License
Project Creator : Adoxio

private static Enreplacedy CreateEnreplacedyOfType(OrganizationServiceContext serviceContext, string enreplacedyLogicalName)
		{
			EnreplacedySetInfo enreplacedySetInfo;

			if (OrganizationServiceContextInfo.TryGet(serviceContext.GetType(), enreplacedyLogicalName, out enreplacedySetInfo))
			{
				try
				{
					return (Enreplacedy)Activator.CreateInstance(enreplacedySetInfo.Enreplacedy.EnreplacedyType);
				}
				catch
				{
					return new Enreplacedy(enreplacedyLogicalName);
				}
			}

			return new Enreplacedy(enreplacedyLogicalName);
		}

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

public T CreateCommandMessage<T>() where T: CommandMessage
        {
            var ret = Activator.CreateInstance(typeof(T), ConnectionInformation.AmfEncodingVersion);
            return ret as T;
        }

19 View Source File : LockManager.cs
License : MIT License
Project Creator : Adoxio

private static ILockProvider CreateProvider()
		{
			var section = CrmConfigurationManager.GetCrmSection();

			if (section != null && !string.IsNullOrWhiteSpace(section.LockProviderType))
			{
				var typeName = section.LockProviderType;
				var type = TypeExtensions.GetType(typeName);

				if (type == null || !type.IsA<ILockProvider>())
				{
					throw new ConfigurationErrorsException("The value '{0}' is not recognized as a valid type or is not of the type '{1}'.".FormatWith(typeName, typeof(ILockProvider)));
				}

				return Activator.CreateInstance(type) as ILockProvider;
			}

			return new MutexLockProvider();
		}

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

public Action Request<T>(int timeout, DataHandler<T> cb, Action? cbTimeout = null) where T : DataType<T>, IDataRequestable
            => Request(timeout, Activator.CreateInstance(typeof(T).GetRequestType()) as DataType ?? throw new Exception($"Invalid requested type: {typeof(T).FullName}"), cb, cbTimeout);

19 View Source File : PostProcessingInspector.cs
License : MIT License
Project Creator : AdultLink

void OnEnable()
        {
            if (target == null)
                return;

            // Aggregate custom post-fx editors
            var replacedembly = replacedembly.Getreplacedembly(typeof(PostProcessingInspector));

            var editorTypes = replacedembly.GetTypes()
                .Where(x => x.IsDefined(typeof(PostProcessingModelEditorAttribute), false));

            var customEditors = new Dictionary<Type, PostProcessingModelEditor>();
            foreach (var editor in editorTypes)
            {
                var attr = (PostProcessingModelEditorAttribute)editor.GetCustomAttributes(typeof(PostProcessingModelEditorAttribute), false)[0];
                var effectType = attr.type;
                var alwaysEnabled = attr.alwaysEnabled;

                var editorInst = (PostProcessingModelEditor)Activator.CreateInstance(editor);
                editorInst.alwaysEnabled = alwaysEnabled;
                editorInst.profile = target as PostProcessingProfile;
                editorInst.inspector = this;
                customEditors.Add(effectType, editorInst);
            }

            // ... and corresponding models
            var baseType = target.GetType();
            var property = serializedObject.Gereplacederator();

            while (property.Next(true))
            {
                if (!property.hasChildren)
                    continue;

                var type = baseType;
                var srcObject = ReflectionUtils.GetFieldValueFromPath(serializedObject.targetObject, ref type, property.propertyPath);

                if (srcObject == null)
                    continue;

                PostProcessingModelEditor editor;
                if (customEditors.TryGetValue(type, out editor))
                {
                    var effect = (PostProcessingModel)srcObject;

                    if (editor.alwaysEnabled)
                        effect.enabled = editor.alwaysEnabled;

                    m_CustomEditors.Add(editor, effect);
                    editor.target = effect;
                    editor.serializedProperty = property.Copy();
                    editor.OnPreEnable();
                }
            }

            // Prepare monitors
            m_Monitors = new List<PostProcessingMonitor>();

            var monitors = new List<PostProcessingMonitor>
            {
                new HistogramMonitor(),
                new WaveformMonitor(),
                new ParadeMonitor(),
                new VectorscopeMonitor()
            };

            var monitorNames = new List<GUIContent>();

            foreach (var monitor in monitors)
            {
                if (monitor.IsSupported())
                {
                    monitor.Init(m_ConcreteTarget.monitors, this);
                    m_Monitors.Add(monitor);
                    monitorNames.Add(monitor.GetMonitorreplacedle());
                }
            }

            m_MonitorNames = monitorNames.ToArray();

            if (m_Monitors.Count > 0)
                m_ConcreteTarget.monitors.onFrameEndEditorOnly = OnFrameEnd;
        }

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 : MvcBuilderExtensions.cs
License : MIT License
Project Creator : 17MKH

public static IModuleCollection AddModules(this IMvcBuilder builder, IModuleCollection modules)
    {
        foreach (var module in modules)
        {
            var replacedembly = module.Layerreplacedemblies.Web ?? module.Layerreplacedemblies.Api;
            if (replacedembly == null)
                continue;

            if (module?.Layerreplacedemblies == null)
                continue;

            builder.AddApplicationPart(module.Layerreplacedemblies.Web ?? module.Layerreplacedemblies.Api);

            builder.AddMvcOptions(options =>
            {
                var mvcOptionsConfigurator = replacedembly.GetTypes().FirstOrDefault(m => typeof(IModuleMvcOptionsConfigurator).IsreplacedignableFrom(m));
                if (mvcOptionsConfigurator != null)
                {
                    ((IModuleMvcOptionsConfigurator)Activator.CreateInstance(mvcOptionsConfigurator))?.Configure(options);
                }
            });
        }

        return modules;
    }

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

public Action Request<T>(DataHandler<T> cb) where T : DataType<T>, IDataRequestable
            => Request(0, Activator.CreateInstance(typeof(T).GetRequestType()) as DataType ?? throw new Exception($"Invalid requested type: {typeof(T).FullName}"), cb, null);

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

public MetaType Unwrap(DataContext ctx) {
            MetaType meta = Activator.CreateInstance(ctx.IDToMetaType[ID]) as MetaType ?? throw new Exception($"Couldn't unwrap MetaType {ID}");
            meta.Read(ctx, this);
            return meta;
        }

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

private ISchemaProvider CreateSchemaProvider(string dbAdapterreplacedemblyName, replacedembly dbAdapterreplacedembly)
    {
        var schemaProviderType = dbAdapterreplacedembly.GetType($"{dbAdapterreplacedemblyName}.{Options.Provider}SchemaProvider");

        return (ISchemaProvider)Activator.CreateInstance(schemaProviderType!, Options.ConnectionString);
    }

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 : States.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

public BaseStateModel CreateStateModel()
        {
            BaseStateModel stateLogic = (BaseStateModel)Activator.CreateInstance(StateModelType, StateList[DefaultIndex]);

            List<State> stateListCopy = new List<State>();
            foreach (State s in StateList)
            {
                stateListCopy.Add(s.Copy());
            }

            stateLogic.ImportStates(stateListCopy);

            return stateLogic;
        }

See More Examples