System.Activator.CreateInstance(System.Type, params object[])

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

1297 Examples 7

19 View Source File : CustomShaderInspector.cs
License : MIT License
Project Creator : alexismorin

private void ShowCompiledCodeButton( Shader s )
		{
			EditorGUILayout.BeginHorizontal( new GUILayoutOption[ 0 ] );
			EditorGUILayout.PrefixLabel( "Compiled code", EditorStyles.miniButton );
			bool flag = ShaderUtilEx.HreplacedhaderSnippets( s ) || ShaderUtilEx.HreplacedurfaceShaders( s ) || ShaderUtilEx.HasFixedFunctionShaders( s );
			if ( flag )
			{
				GUIContent showCurrent = CustomShaderInspector.Styles.showCurrent;
				Rect rect = GUILayoutUtility.GetRect( showCurrent, EditorStyles.miniButton, new GUILayoutOption[]
				{
					GUILayout.ExpandWidth(false)
				} );
				Rect position = new Rect( rect.xMax - 16f, rect.y, 16f, rect.height );
				if ( EditorGUIEx.ButtonMouseDown( position, GUIContent.none, FocusType.Preplacedive, GUIStyle.none ) )
				{
					Rect last = GUILayoutUtilityEx.TopLevel_GetLast();
					PopupWindow.Show( last, ( PopupWindowContent ) Activator.CreateInstance( System.Type.GetType( "UnityEditor.ShaderInspectorPlatformsPopup, UnityEditor" ), new object[] { s } ) );
					GUIUtility.ExitGUI();
				}
				if ( GUI.Button( rect, showCurrent, EditorStyles.miniButton ) )
				{
					ShaderUtilEx.OpenCompiledShader( s, ShaderInspectorPlatformsPopupEx.GetCurrentMode(), ShaderInspectorPlatformsPopupEx.GetCurrentPlatformMask(), ShaderInspectorPlatformsPopupEx.GetCurrentVariantStripping() == 0 );
					GUIUtility.ExitGUI();
				}
			}
			else
			{
				GUILayout.Button( "none (precompiled shader)", GUI.skin.label, new GUILayoutOption[ 0 ] );
			}
			EditorGUILayout.EndHorizontal();
		}

19 View Source File : DynamoDbContextMetadata.cs
License : MIT License
Project Creator : AllocZero

private DdbConverter CreateConverter(Type converterType)
        {
            var constructor = converterType.GetConstructors()[0];
            var constructorParams = constructor.GetParameters();

            if (constructorParams.Length == 0) 
                return (DdbConverter) Activator.CreateInstance(converterType)!;

            var parameters = new object[constructorParams.Length];
            for (var i = 0; i < constructorParams.Length; i++)
            {
                var parameter = constructorParams[i];

                if (parameter.ParameterType == typeof(DynamoDbContextMetadata))
                {
                    parameters[i] = this;
                }
                else
                {
                    if (!parameter.ParameterType.IsSubclreplacedOf(typeof(DdbConverter))) 
                        throw new DdbException("Can't create converter that contains non converter constructor parameters.");

                    parameters[i] = GetOrAddConverter(parameter.ParameterType.GenericTypeArguments[0], null);
                }
            }

            return (DdbConverter) Activator.CreateInstance(converterType, parameters)!;
        }

19 View Source File : DefaultTriggerAttribute.cs
License : GNU General Public License v3.0
Project Creator : aduskin

public TriggerBase Instantiate()
        {
            object obj2 = null;
            try
            {
                obj2 = Activator.CreateInstance(TriggerType, _parameters);
            }
            catch
            {
                // ignored
            }
            return (TriggerBase) obj2;
        }

19 View Source File : VirtualControl.cs
License : MIT License
Project Creator : alaabenfatma

public void Paste()
        {
            try
            {
                SelectedNodes.Clear();
                var dummyList = Cipher.DeSerializeFromString<List<NodeProperties>>(Clipboard.GetText());
                for (var index = dummyList.Count - 1; index >= 0; index--)
                {
                    var copiednode = dummyList[index];
                    var typename = copiednode.Name;
                    Node newNode = null;
                    foreach (var node in Hub.LoadedExternalNodes)
                    {
                        if (node.ToString() != typename) continue;
                        newNode = node.Clone();
                        AddNode(newNode, copiednode.X, copiednode.Y);
                        newNode.DeSerializeData(copiednode.InputData, copiednode.OutputData);
                        break;
                    }
                    if (newNode != null) continue;
                    var type = Type.GetType(typename);
                    try
                    {
                        var instance = Activator.CreateInstance(type, this, false);
                        AddNode(instance as Node, copiednode.X, copiednode.Y);
                    }
                    catch (Exception)
                    {
                        //Ignored
                    }
                }
            }
            catch
            {
                //ignored
            }
        }

19 View Source File : ContractReferenceState.cs
License : MIT License
Project Creator : AElfProject

private void InitializeProperties()
        {
            foreach (var kv in _methodReferenceProperties)
            {
                var name = kv.Key;
                var propertyInfo = kv.Value;
                var propertyType = kv.Value.PropertyType;
                var instance = Activator.CreateInstance(propertyType, this, name);
                propertyInfo.SetValue(this, instance);
            }
        }

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

public static T GetEnreplacedyIdentifier<T>(this Enreplacedy enreplacedy, string attributeLogicalName, string alias = null) where T : EnreplacedyNode
		{
			var er = GetAttributeAliasedValue<EnreplacedyReference>(enreplacedy, attributeLogicalName, alias);
			var id = er != null ? Activator.CreateInstance(typeof(T), er) as T : null;
			return id;
		}

19 View Source File : Tool.cs
License : Apache License 2.0
Project Creator : Algoryx

protected T GetOrCreateVisualPrimitive<T>( string name, string shader = "Unlit/Color" ) where T : Utils.VisualPrimitive
    {
      T primitive = GetVisualPrimitive<T>( name );
      if ( primitive != null )
        return primitive;

      primitive = (T)Activator.CreateInstance( typeof( T ), new object[] { shader } );
      m_visualPrimitives.Add( name, primitive );

      return primitive;
    }

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

private object NormalBuild()
        {
            if (null != Instance)
            {
                if (IsSingleInstance)
                {
                    return SingleInstance ?? (SingleInstance = Instance);
                }
                else
                {
                    if (Instance is ICloneable)
                    {
                        var clone = (Instance as ICloneable).Clone();
                        m_InstanceList.Add(clone);
                        return clone;
                    }
                    else
                    {
                        throw new System.Exception(string.Format("Type '{0}' is not replacedignable from 'ICloneable' interface.",Instance.GetType()));
                    }
                }

            }
            else
            {
                if (IsSingleInstance)
                {
                    return SingleInstance ?? (SingleInstance = Activator.CreateInstance(BindType, BindTypeParameter));
                }
                else
                {
                    var instance = Activator.CreateInstance(BindType, BindTypeParameter);
                    if (null != instance)
                    {
                        m_InstanceList.Add(instance);
                        return instance;
                    }
                }
            }
            return null;
        }

19 View Source File : Plugin.cs
License : MIT License
Project Creator : AlternateLife

private T CreateNativeManager<T>(Func<IntPtr, IntPtr> pointerReceiver) where T : clreplaced
        {
            return (T) Activator.CreateInstance(typeof(T), pointerReceiver(NativeMultiplayer), this);
        }

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

private T ActivateInstance<T>(Type concreteType, SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1), params object[] args) where T : IMixedRealityService
        {
            if (concreteType == null) { return default(T); }

#if UNITY_EDITOR
            if (!UnityEditor.EditorUserBuildSettings.activeBuildTarget.IsPlatformSupported(supportedPlatforms))
#else
            if (!Application.platform.IsPlatformSupported(supportedPlatforms))
#endif
            {
                return default(T);
            }

            if (!typeof(T).IsreplacedignableFrom(concreteType))
            {
                Debug.LogError($"Error: {concreteType.Name} service must implement {typeof(T)}.");
                return default(T);
            }

            try
            {
                T serviceInstance = (T)Activator.CreateInstance(concreteType, args);
                return serviceInstance;
            }
            catch (Exception e)
            {
                Debug.LogError($"Error: Failed to instantiate {concreteType.Name}: {e.GetType()} - {e.Message}");
                return default(T);
            }
        }

19 View Source File : CommandsNextUtilities.cs
License : MIT License
Project Creator : Aiko-IT-Systems

internal static object CreateInstance(this Type t, IServiceProvider services)
        {
            var ti = t.GetTypeInfo();
            var constructors = ti.DeclaredConstructors
                .Where(xci => xci.IsPublic)
                .ToArray();

            if (constructors.Length != 1)
                throw new ArgumentException("Specified type does not contain a public constructor or contains more than one public constructor.");

            var constructor = constructors[0];
            var constructorArgs = constructor.GetParameters();
            var args = new object[constructorArgs.Length];

            if (constructorArgs.Length != 0 && services == null)
                throw new InvalidOperationException("Dependency collection needs to be specified for parameterized constructors.");

            // inject via constructor
            if (constructorArgs.Length != 0)
                for (var i = 0; i < args.Length; i++)
                    args[i] = services.GetRequiredService(constructorArgs[i].ParameterType);

            var moduleInstance = Activator.CreateInstance(t, args);

            // inject into properties
            var props = t.GetRuntimeProperties().Where(xp => xp.CanWrite && xp.SetMethod != null && !xp.SetMethod.IsStatic && xp.SetMethod.IsPublic);
            foreach (var prop in props)
            {
                if (prop.GetCustomAttribute<DontInjectAttribute>() != null)
                    continue;

                var service = services.GetService(prop.PropertyType);
                if (service == null)
                    continue;

                prop.SetValue(moduleInstance, service);
            }

            // inject into fields
            var fields = t.GetRuntimeFields().Where(xf => !xf.IsInitOnly && !xf.IsStatic && xf.IsPublic);
            foreach (var field in fields)
            {
                if (field.GetCustomAttribute<DontInjectAttribute>() != null)
                    continue;

                var service = services.GetService(field.FieldType);
                if (service == null)
                    continue;

                field.SetValue(moduleInstance, service);
            }

            return moduleInstance;
        }

19 View Source File : ImportService.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private async Task ImportSubEnreplacediesAsync(T enreplacedy, Dictionary<string, IEnumerable> subEnreplacedies, IAdminStore<T> store, ImportFileResult result)
            {                
                if (!subEnreplacedies.Any())
                {
                    return;
                }

                var expand = string.Join(",", subEnreplacedies.Keys);
                enreplacedy = await store.GetAsync(enreplacedy.Id, new GetRequest { Expand = expand }).ConfigureAwait(false);

                foreach (var key in subEnreplacedies.Keys)
                {
                    if (subEnreplacedies[key] == null)
                    {
                        continue;
                    }

                    var property = typeof(T).GetProperty(key);
                    var subEnreplacedyList = property.GetValue(enreplacedy) as IEnumerable;
                    var enreplacedyType = property.PropertyType.GetGenericArguments()[0];
                    var importerType = typeof(Importer<>).MakeGenericType(enreplacedyType);
                    var importer = Activator.CreateInstance(importerType, _provider) as Importer;
                    await importer.RemoveEnreplacediesAsync(subEnreplacedyList, result).ConfigureAwait(false);
                }

                foreach (var enreplacedyList in subEnreplacedies)
                {
                    var enumerator = enreplacedyList.Value.GetEnumerator();
                    if (!enumerator.MoveNext())
                    {
                        continue;
                    }

                    var enreplacedyType = enumerator.Current.GetType();
                    var importerType = typeof(Importer<>).MakeGenericType(enreplacedyType);
                    var importer = Activator.CreateInstance(importerType, _provider) as Importer;

                    await importer.AddOrUpdateSubEnreplacediesAsync(enreplacedyList.Value, result).ConfigureAwait(false);
                }
            }

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

public EnreplacedyNode ToNode(Enreplacedy enreplacedy)
		{
			var node = Activator.CreateInstance(EnreplacedyNodeType, enreplacedy, null) as EnreplacedyNode;
			return node;
		}

19 View Source File : ServiceExecutor.cs
License : MIT License
Project Creator : alexandredenes

public object Execute(RequestMessage requestMessage)
        {
            (Type type, MethodInfo info)? action = _localServices.GetExecutionInfo(requestMessage.Action);

            if (!action.HasValue)
                throw new InvalidOperationException($"Action {requestMessage.Action} not found");

            object[] parms = null;

            if (action.Value.info.GetParameters().Length != 0)
                parms = CreateParams(action.Value.info.GetParameters(), requestMessage);

            bool contextConstructor = action.Value.type.GetConstructor(new Type[]{ _context.GetType()}) != null;
            object obj;
            if(contextConstructor)
                obj = Activator.CreateInstance(action.Value.type, new object[] { _context });
            else
                obj = Activator.CreateInstance(action.Value.type, new object[] { });

            return action.Value.info.Invoke(obj, parms);

        }

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

public static object New(Type type, params object[] args)
            {
                return Activator.CreateInstance(type,args);
            }

19 View Source File : Constraint.cs
License : Apache License 2.0
Project Creator : Algoryx

protected override bool Initialize()
    {
      if ( AttachmentPair.ReferenceObject == null ) {
        Debug.LogError( "Unable to initialize constraint - reference object " +
                        "must be valid and contain a rigid body component.",
                        this );
        return false;
      }

      if ( Type == ConstraintType.Unknown ) {
        Debug.LogError( "Unable to initialize constraint - constraint type is Unknown.",
                        this );
        return false;
      }

      // Synchronize frames to make sure connected frame is up to date.
      AttachmentPair.Synchronize();

      // TODO: Disabling rigid body game object (activeSelf == false) and will not be
      //       able to create native body (since State == Constructed and not Awake).
      //       Do: GetComponentInParent<RigidBody>( true <- include inactive ) and wait
      //           for the body to become active?
      //       E.g., rb.AwaitInitialize += ThisConstraintInitialize.
      RigidBody rb1 = AttachmentPair.ReferenceObject.GetInitializedComponentInParent<RigidBody>();
      if ( rb1 == null ) {
        Debug.LogError( "Unable to initialize constraint - reference object must " +
                        "contain a rigid body component.",
                        AttachmentPair.ReferenceObject );
        return false;
      }

      // Native constraint frames.
      agx.Frame f1 = new agx.Frame();
      agx.Frame f2 = new agx.Frame();

      // Note that the native constraint want 'f1' given in rigid body frame, and that
      // 'ReferenceFrame' may be relative to any object in the children of the body.
      f1.setLocalTranslate( AttachmentPair.ReferenceFrame.CalculateLocalPosition( rb1.gameObject ).ToHandedVec3() );
      f1.setLocalRotate( AttachmentPair.ReferenceFrame.CalculateLocalRotation( rb1.gameObject ).ToHandedQuat() );

      RigidBody rb2 = AttachmentPair.ConnectedObject != null ?
                        AttachmentPair.ConnectedObject.GetInitializedComponentInParent<RigidBody>() :
                        null;
      if ( rb1 == rb2 ) {
        Debug.LogError( "Unable to initialize constraint - reference and connected " +
                        "rigid body is the same instance.",
                        this );
        return false;
      }

      if ( rb2 != null ) {
        // Note that the native constraint want 'f2' given in rigid body frame, and that
        // 'ReferenceFrame' may be relative to any object in the children of the body.
        f2.setLocalTranslate( AttachmentPair.ConnectedFrame.CalculateLocalPosition( rb2.gameObject ).ToHandedVec3() );
        f2.setLocalRotate( AttachmentPair.ConnectedFrame.CalculateLocalRotation( rb2.gameObject ).ToHandedQuat() );
      }
      else {
        f2.setLocalTranslate( AttachmentPair.ConnectedFrame.Position.ToHandedVec3() );
        f2.setLocalRotate( AttachmentPair.ConnectedFrame.Rotation.ToHandedQuat() );
      }

      try {
        Native = (agx.Constraint)Activator.CreateInstance( NativeType,
                                                           new object[]
                                                           {
                                                             rb1.Native,
                                                             f1,
                                                             ( rb2 != null ? rb2.Native : null ),
                                                             f2
                                                           } );

        // replacedigning native elementary constraints to our elementary constraint instances.
        foreach ( ElementaryConstraint ec in ElementaryConstraints )
          if ( !ec.OnConstraintInitialize( this ) )
            throw new Exception( "Unable to initialize elementary constraint: " +
                                 ec.NativeName +
                                 " (not present in native constraint). ConstraintType: " + Type );

        bool added = GetSimulation().add( Native );
        Native.setEnable( IsEnabled );

        // Not possible to handle collisions if connected frame parent is null/world.
        if ( CollisionsState != ECollisionsState.KeepExternalState && AttachmentPair.ConnectedObject != null ) {
          string groupName = gameObject.name + "_" + gameObject.GetInstanceID().ToString();
          GameObject go1   = null;
          GameObject go2   = null;
          if ( CollisionsState == ECollisionsState.DisableReferenceVsConnected ) {
            go1 = AttachmentPair.ReferenceObject;
            go2 = AttachmentPair.ConnectedObject;
          }
          else {
            go1 = rb1.gameObject;
            go2 = rb2 != null ?
                    rb2.gameObject :
                    AttachmentPair.ConnectedObject;
          }

          go1.GetOrCreateComponent<CollisionGroups>().GetInitialized<CollisionGroups>().AddGroup( groupName, false );
          // Propagate to children if rb2 is null, which means
          // that go2 could be some static structure.
          go2.GetOrCreateComponent<CollisionGroups>().GetInitialized<CollisionGroups>().AddGroup( groupName, rb2 == null );
          CollisionGroupsManager.Instance.GetInitialized<CollisionGroupsManager>().SetEnablePair( groupName, groupName, false );
        }

        Native.setName( name );

        bool valid = added && Native.getValid();
        Simulation.Instance.StepCallbacks.PreSynchronizeTransforms += OnPreStepForwardUpdate;

        // It's not possible to check which properties an animator
        // is controlling, for now we update all properties in the
        // controllers if we have an animator.
        m_isAnimated = GetComponent<Animator>() != null;

        return valid;
      }
      catch ( System.Exception e ) {
        Debug.LogException( e, gameObject );
        return false;
      }


    }

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

private static TDependency CreateDependency<TDefault>(
			Type type,
			Func<TDefault> createDefault,
			params object[] args)
			where TDefault : TDependency
		{
			if (type == typeof(TDefault)) return createDefault();
			if (type.IsA(typeof(TDefault))) return (TDependency)Activator.CreateInstance(type, args);
			return (TDependency)Activator.CreateInstance(type);
		}

19 View Source File : DynamicGenericResolver.cs
License : Apache License 2.0
Project Creator : allenai

private static object CreateInstance(Type genericType, Type[] genericTypeArguments, params object[] arguments)
        {
            return Activator.CreateInstance(genericType.MakeGenericType(genericTypeArguments), arguments);
        }

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

public virtual IDbSet Set(Type enreplacedyType) {
			if (_dicSet.ContainsKey(enreplacedyType)) return _dicSet[enreplacedyType];
			var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(enreplacedyType), this) as IDbSet;
			if (enreplacedyType != typeof(object)) _dicSet.Add(enreplacedyType, sd);
			return sd;
		}

19 View Source File : TypeExtension.cs
License : MIT License
Project Creator : AlphaYu

public static T CreateInstance<T>([NotNull] this Type @this, params object[] args) => (T)Activator.CreateInstance(@this, args);

19 View Source File : ThemeApp.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static void CreateThemeLists()
        {

            if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "replacedets", "skins")))
            {
                string[] skins = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "replacedets", "skins"), "*_landscape.png");

                foreach (string path in skins)
                {
                    try
                    {
                        Texture2D skin = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "skins", Path.GetFileName(path).Replace("_landscape", "")));
                        Texture2D skinl = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "skins", Path.GetFileName(path)));
                        if (skin != null && skinl != null)
                        {
                            skinDict.Add(Path.Combine("replacedets", "skins", Path.GetFileName(path).Replace("_landscape", "")), new Texture2D[] { skin, skinl });
                            Monitor.Log($"loaded skin {path.Replace("_landscape", "")}");
                        }
                        else
                            Monitor.Log($"Couldn't load skin {path.Replace("_landscape", "")}: texture was null", LogLevel.Error);
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log($"Couldn't load skin {path.Replace("_landscape", "")}: {ex}", LogLevel.Error);
                    }
                }
            }

            if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "replacedets", "backgrounds")))
            {
                string[] papers = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "replacedets", "backgrounds"), "*_landscape.png");
                foreach (string path in papers)
                {
                    try
                    {
                        Texture2D back = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "backgrounds", Path.GetFileName(path).Replace("_landscape", "")));
                        Texture2D backl = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "backgrounds", Path.GetFileName(path)));
                        if (back != null && backl != null)
                        {
                            backgroundDict.Add(Path.Combine("replacedets", "backgrounds", Path.GetFileName(path).Replace("_landscape", "")), new Texture2D[] { back, backl });
                            Monitor.Log($"loaded background {path.Replace("_landscape", "")}");
                        }
                        else
                            Monitor.Log($"Couldn't load background {path.Replace("_landscape", "")}: texture was null", LogLevel.Error);
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log($"Couldn't load background {path.Replace("_landscape", "")}: {ex}", LogLevel.Error);
                    }
                }
            }


            if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "replacedets", "ringtones")))
            {
                string[] rings = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "replacedets", "ringtones"), "*.wav");
                foreach (string path in rings)
                {
                    try
                    {
                        object ring;
                        try
                        {
                            var type = Type.GetType("System.Media.SoundPlayer, System");
                            ring = Activator.CreateInstance(type, new object[] { path });
                        }
                        catch 
                        {
                            ring = SoundEffect.FromStream(new FileStream(path, FileMode.Open));
                        }
                        if (ring != null)
                        {
                            ringDict.Add(Path.GetFileName(path).Replace(".wav", ""), ring);
                            Monitor.Log($"loaded ring {path}");
                        }
                        else
                            Monitor.Log($"Couldn't load ring {path}", LogLevel.Error);
                    }
                    catch (Exception ex)
                    {
                        Monitor.Log($"Couldn't load ring {path}:\r\n{ex}", LogLevel.Error);
                    }
                }
                rings = Config.BuiltInRingTones.Split(',');
                foreach (string ring in rings)
                {
                    ringDict.Add(ring, null);
                }
            }
            ringList = ringDict.Keys.ToList();
            skinList = skinDict.Keys.ToList();
            backgroundList = backgroundDict.Keys.ToList();
        }

19 View Source File : ValueTypeBox.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public static IValueTypeBox Box(object vt, Type vtType)
        {
            Debug.replacedert(vtType.IsValueType);
            var boxType = typeof(ValueTypeBox<>).MakeGenericType(vtType);
            return (IValueTypeBox) Activator.CreateInstance(boxType, vt);
        }

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 : StartupExtension.cs
License : Apache License 2.0
Project Creator : agoda-com

private static void RegisterKeyedFactory(this IServiceCollection services, IDictionary<Type, List<KeyTypePair>> keysForTypes)
        {
            foreach (var key in keysForTypes)
            {
                var keyedFactoryInterfaceType = typeof(IKeyedComponentFactory<>).MakeGenericType(key.Key);
                var keyedFactoryImplementationType = typeof(KeyedComponentFactory<>).MakeGenericType(key.Key);

                var regObject = typeof(NetCoreKeyedRegistrations<>).MakeGenericType(key.Key);
                var regObjectInstance = Activator.CreateInstance(regObject,
                    key.Value.ToDictionary(x => x.Key,
                        y => y.Type));
                services.AddSingleton(regObject, provider => regObjectInstance);
                services.AddSingleton(keyedFactoryInterfaceType, keyedFactoryImplementationType);
                services.AddSingleton(typeof(IKeyedComponentResolver<>).MakeGenericType(key.Key), typeof(NetCoreKeyedComponentResolver<>).MakeGenericType(key.Key));
                foreach (var implementation in key.Value)
                {
                    services.Add(new ServiceDescriptor(implementation.Type, implementation.Type,
                                    implementation.ServiceLifetime));
                }
            }
        }

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

public Exception Unwrap(IDictionary<String, Type> typeMapping)
        {
            Exception innerException = null;
            if (InnerException != null)
            {
                innerException = InnerException.Unwrap(typeMapping);
                UnwrappedInnerException = innerException;
            }

            Exception exception = null;

            // if they have bothered to map type, use that first.
            if (!String.IsNullOrEmpty(TypeKey))
            {
                Type type;
                if (typeMapping != null && typeMapping.TryGetValue(TypeKey, out type) ||
                    baseTranslatedExceptions.TryGetValue(TypeKey, out type))
                {
                    try
                    {
                        this.Type = type;
                        exception = Activator.CreateInstance(this.Type, Message, innerException) as Exception;
                    }
                    catch (Exception)
                    {
                        // do nothing
                    }
                }
            }

            if (exception == null)
            {
                //no standard mapping, fallback to 
                exception = UnWrap(innerException);
            }

            if (exception is VssException)
            {
                ((VssException)exception).EventId = this.EventId;
                ((VssException)exception).ErrorCode = this.ErrorCode;
            }

            if (exception == null && !String.IsNullOrEmpty(Message))
            {
                // NOTE: We can get exceptions that we can't create, IE. SqlException, AzureExceptions.
                // This is not a failure, we will just wrap the exception in a VssServiceException
                // since the type is not available.
                exception = new VssServiceException(Message, innerException);
            }

            if (exception == null && !string.IsNullOrEmpty(TypeName))
            {
                Debug.replacedert(false, string.Format("Server exception cannot be resolved. Type name: {0}", TypeName));
            }

            if (exception != null
                && !string.IsNullOrEmpty(HelpLink))
            {
                exception.HelpLink = HelpLink;
            }

            if (exception != null
                && !string.IsNullOrEmpty(this.StackTrace))
            {
                FieldInfo stackTraceField = typeof(Exception).GetTypeInfo().GetDeclaredField("_stackTraceString");
                if (stackTraceField != null && !stackTraceField.Attributes.HasFlag(FieldAttributes.Public) && !stackTraceField.Attributes.HasFlag(FieldAttributes.Static))
                {
                    stackTraceField.SetValue(exception, this.StackTrace);
                }
            }

            if (exception != null && exception.GetType() == this.Type)
            {
                TryUnWrapCustomProperties(exception);
            }

            return exception;
        }

19 View Source File : ImportService.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private async Task<ImportFileResult> ImportFileAsync(IFormFile file)
        {
            var reader = new StreamReader(file.OpenReadStream());
            var content = await reader.ReadToEndAsync().ConfigureAwait(false);
            var metadata = JsonConvert.DeserializeObject<EnreplacedyMetadata>(content);
            var enreplacedyType = Type.GetType(metadata.Metadata.TypeName);
            var importerType = typeof(Importer<>).MakeGenericType(enreplacedyType);
            var importer = Activator.CreateInstance(importerType, _provider) as Importer;
            var result = await importer.ImportAsync(content).ConfigureAwait(false);
            result.FileName = file.FileName;
            return result;
        }

19 View Source File : EditContextExtensions.cs
License : Apache License 2.0
Project Creator : Aguafrommars

private static IValidationContext CreateValidationContext(object model)
        {
            var validationContextType = typeof(ValidationContext<>).MakeGenericType(model.GetType());
            return Activator.CreateInstance(validationContextType, model) as IValidationContext;
        }

19 View Source File : ObjectFactory.cs
License : GNU General Public License v3.0
Project Creator : Adam-Wilkinson

public object CreateInstance(Type type)
        {
            if (type == typeof(IObjectFactory))
            {
                return this;
            }
            
            if (type == typeof(Instance))
            {
                return _instance;
            }

            if (TryGetImplementation(type, out Type implementationType))
            {
                return CreateInstance(implementationType);
            }

            if (type.GetConstructor(Type.EmptyTypes) is not null)
            {
                return Activator.CreateInstance(type);
            }

            ConstructorInfo info = type.GetConstructors()[0];
            ParameterInfo[] parameters = info.GetParameters();
            object[] parameterObjects = new object[parameters.Length];
            int i = 0;
            foreach (ParameterInfo parameter in info.GetParameters())
            {
                parameterObjects[i] = CreateInstance(parameter.ParameterType);
                i++;
            }

            return Activator.CreateInstance(type, parameterObjects);
        }

19 View Source File : ServiceExtensions.cs
License : MIT License
Project Creator : aksoftware98

public static IServiceCollection AddLanguageContainer<TKeysProvider>(this IServiceCollection services, replacedembly replacedembly, string folderName = "Resources")
        where TKeysProvider : KeysProvider
        {
            services.AddSingleton<IKeysProvider, TKeysProvider>(s => (TKeysProvider)Activator.CreateInstance(typeof(TKeysProvider), replacedembly, folderName));
            return services.AddSingleton<ILanguageContainerService, LanguageContainerInreplacedembly>(s =>
            {
                var keysProvider = s.GetService<IKeysProvider>();
                return new LanguageContainerInreplacedembly(keysProvider);
            });
        }

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

public void AddAEditorWindowBase<EditorWindowBase>(string path, EditorIcon icon = null) where EditorWindowBase : AEditorWindowBase
        {
            AEditorWindowBase aEditorWindowBase = (AEditorWindowBase)Activator.CreateInstance(typeof(EditorWindowBase), new object[] { this });
            if (icon == null)
            {
                OdinMenuTree.Add(path, aEditorWindowBase);
            }
            else
            {
                OdinMenuTree.Add(path, aEditorWindowBase, icon);
            }
            aEditorWindowBaseList.Add(aEditorWindowBase);
        }

19 View Source File : DialogService.cs
License : MIT License
Project Creator : AlexanderPro

public TViewModel CreateDialog<TViewModel, TDialog>(params object[] args)
            where TDialog : Window, new()
            where TViewModel : DialogViewModelBase
        {
            var dlg = new TDialog();
            var vm = (TViewModel)Activator.CreateInstance(typeof(TViewModel), new object[] { dlg }.Concat(args).ToArray());
            dlg.DataContext = vm;
            if (dlg.Content == null)
                dlg.Content = vm;

            return vm;
        }

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

private object CreateEnreplacedy(object enreplacedy)
		{
			// attempt to dynamically convert from DynamicEnreplacedyWrapper to the specified type
			var type = TypeExtensions.GetType(Owner.StaticEnreplacedyWrapperTypeName);

			// invoke the constructor that takes a single DynamicEnreplacedyWrapper
			return Activator.CreateInstance(type, enreplacedy);
		}

19 View Source File : SaveLoad.cs
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet

public static void Load(out T serializableClreplaced, string fileName, string dataPath)
        {
            if (dataPath == null)
            {dataPath = Application.dataPath;}
            string destination = dataPath + "/"+ fileName;
            FileStream file;

            if (File.Exists(destination))
            {
                file = File.OpenRead(destination);
                BinaryFormatter bf = new BinaryFormatter();
                serializableClreplaced = (T)bf.Deserialize(file);
                file.Close();
            }
            else
            {
                serializableClreplaced = (T)Activator.CreateInstance(typeof(T), new object[] { });
            }
            Debug.Log("Load from to : " + destination);


        }

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

public object CreateSourceInstance(object[] parameters)
        {
            if (parameters == null || parameters.Length == 0)
                return Activator.CreateInstance(this.SourceType, true);

            if (this.SourceConstructorsMergeParametersLength.TryGetValue(parameters.Length, out var ctors) == false)
                throw new ArgumentException($"{this.SourceType.DisplayCsharp()} 没有定义长度 {parameters.Length} 的构造函数");

            return Activator.CreateInstance(this.SourceType, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parameters);
        }

19 View Source File : PropertyFetcher.cs
License : MIT License
Project Creator : alexvaluyskiy

public static PropertyFetch FetcherForProperty(PropertyInfo propertyInfo)
            {
                if (propertyInfo == null || !typeof(T).IsreplacedignableFrom(propertyInfo.PropertyType))
                {
                    // returns null on any fetch.
                    return new PropertyFetch();
                }

                var typedPropertyFetcher = typeof(TypedPropertyFetch<,>);
                var instantiatedTypedPropertyFetcher = typedPropertyFetcher.MakeGenericType(
                    typeof(T), propertyInfo.DeclaringType, propertyInfo.PropertyType);
                return (PropertyFetch)Activator.CreateInstance(instantiatedTypedPropertyFetcher, propertyInfo);
            }

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

public static T GetIntersectEnreplacedyIdentifier<T>(this Enreplacedy enreplacedy, string enreplacedyLogicalName, string attributeLogicalName, string alias = null) where T : EnreplacedyNode
		{
			var guid = GetAttributeAliasedValue<Guid?>(enreplacedy, attributeLogicalName, alias);
			var er = guid != null ? new EnreplacedyReference(enreplacedyLogicalName, guid.Value) : null;
			var id = er != null ? Activator.CreateInstance(typeof(T), er) as T : null;
			return id;
		}

19 View Source File : VisitorCollection.cs
License : MIT License
Project Creator : aliencube

public static VisitorCollection CreateInstance()
        {
            var collection = new VisitorCollection();
            collection.Visitors = typeof(IVisitor).replacedembly
                                           .GetTypes()
                                           .Where(p => p.Name.EndsWith("Visitor") && p.IsClreplaced && !p.IsAbstract)
                                           .Select(p => (IVisitor)Activator.CreateInstance(p, collection)).ToList(); // NOTE: there is no direct enforcement on the constructor arguments of the visitors
            return collection;
        }

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

private object SelfBindTypeBuild()
        {
            if (IsSingleInstance)
            {
                return SingleInstance ?? (SingleInstance = Activator.CreateInstance(SelfBindType, BindTypeParameter));
            }
            else
            {
                var instance = Activator.CreateInstance(SelfBindType, BindTypeParameter);
                if (null != instance)
                {
                    m_InstanceList.Add(instance);
                    return instance;
                }
            }
            return null;
        }

19 View Source File : ToolManager.cs
License : Apache License 2.0
Project Creator : Algoryx

public static void OnTargetEditorEnable( Object[] targets, Editor editor )
    {
      if ( targets.Length == 0 )
        return;

      // The target type has our custom editor, register the
      // replacedembly of the editor for possible custom target tools.
      if ( editor != null )
        RegisterCustomToolsreplacedembly( editor.GetType().replacedembly.GetName().Name );

      Utils.KeyHandler.HandleDetectKeyOnEnable( targets );

      var toolType = FindCustomToolType( targets[ 0 ].GetType() );
      if ( toolType == null )
        return;

      CustomTargetTool tool = null;
      try {
        tool = (CustomTargetTool)Activator.CreateInstance( toolType, new object[] { targets } );
      }
      catch ( Exception e ) {
        Debug.LogException( e );
        return;
      }

      m_activeTools.Add( tool );

      tool.OnAdd();
    }

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

private static TDependency CreateDependency<TDefault1, TDefault2>(
			Type type,
			Func<TDefault1> createDefault1,
			object[] args1,
			Func<TDefault2> createDefault2,
			object[] args2)
			where TDefault1 : TDefault2
			where TDefault2 : TDependency
		{
			if (type == typeof(TDefault1)) return createDefault1();
			if (type.IsA(typeof(TDefault1))) return (TDependency)Activator.CreateInstance(type, args1);
			if (type == typeof(TDefault2)) return createDefault2();
			if (type.IsA(typeof(TDefault2))) return (TDependency)Activator.CreateInstance(type, args2);
			return (TDependency)Activator.CreateInstance(type);
		}

19 View Source File : DynamoDbContextMetadata.cs
License : MIT License
Project Creator : AllocZero

private DdbConverter GetOrAddNestedObjectConverter(Type propertyType)
        {
            var converterType = typeof(ObjectDdbConverter<>).MakeGenericType(propertyType);

            return _factoryConvertersCache.GetOrAdd(propertyType, (x, metadata) => (DdbConverter) Activator.CreateInstance(converterType, metadata)!, this)!;
        }

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 : FieldStorage.cs
License : MIT License
Project Creator : Alprog

public object AddOwnValue(FieldKey key, Type type = null)
        {
            if (type == null)
            {
                type = FieldMeta.Get(key).FieldType;
            }
            object value = null;
            if (type.IsArray)
            {
                value = Activator.CreateInstance(type, 0);
            }
            else
            {
                if (type == typeof(String) || type == typeof(string))
                {
                    value = String.Empty;
                }
                else
                {
                    value = Activator.CreateInstance(type);
                }
            }
            SetValue(key, value);
            return value;
        }

19 View Source File : PhoneGameLoop.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void GameLoop_GameLaunched(object sender, StardewModdingAPI.Events.GameLaunchedEventArgs e)
        {
            foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
            {
                Monitor.Log($"Reading content pack: {contentPack.Manifest.Name} {contentPack.Manifest.Version} from {contentPack.DirectoryPath}");
                try
                {
                    MobilePhonePackJSON json = contentPack.ReadJsonFile<MobilePhonePackJSON>("content.json") ?? null;
                    
                    if(json != null)
                    {
                        if (json.apps != null && json.apps.Any())
                        {
                            foreach (AppJSON app in json.apps)
                            {
                                Texture2D tex = contentPack.Loadreplacedet<Texture2D>(app.iconPath);
                                if (tex == null)
                                {
                                    continue;
                                }
                                ModEntry.apps.Add(app.id, new MobileApp(app.name, app.keyPress, app.closePhone, tex));
                                Monitor.Log($"Added app {app.name} from {contentPack.DirectoryPath}");
                            }
                        }
                        else if (json.iconPath != null)
                        {
                            Texture2D icon = contentPack.Loadreplacedet<Texture2D>(json.iconPath);
                            if (icon == null)
                            {
                                continue;
                            }
                            ModEntry.apps.Add(json.id, new MobileApp(json.name, json.keyPress, json.closePhone, icon));
                            Monitor.Log($"Added app {json.name} from {contentPack.DirectoryPath}");
                        }
                        if (json.invites != null && json.invites.Any())
                        {
                            foreach (EventInvite invite in json.invites)
                            {
                                MobilePhoneCall.eventInvites.Add(invite);
                                Monitor.Log($"Added event invite {invite.name} from {contentPack.DirectoryPath}");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Monitor.Log($"error reading content.json file in content pack {contentPack.Manifest.Name}.\r\n{ex}", LogLevel.Error);
                }
                if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "events")))
                {
                    Monitor.Log($"Adding events");
                    string[] events = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "events"), "*.json");
                    Monitor.Log($"CP has {events.Length} events");
                    foreach (string eventFile in events)
                    {
                        try
                        {
                            string eventPath = Path.Combine("replacedets", "events", Path.GetFileName(eventFile));
                            Monitor.Log($"Adding events {Path.GetFileName(eventFile)} from {contentPack.DirectoryPath}");
                            Reminiscence r = contentPack.ReadJsonFile<Reminiscence>(eventPath);
                            MobilePhoneCall.contentPackReminiscences.Add(Path.GetFileName(eventFile).Replace(".json", ""), r);
                            Monitor.Log($"Added event {Path.GetFileName(eventFile)} from {contentPack.DirectoryPath}");
                        }
                        catch { }
                    }
                }
                if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "skins")))
                {
                    Monitor.Log($"Adding skins");
                    string[] skins = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "skins"), "*_landscape.png");
                    Monitor.Log($"CP has {skins.Length} skins");
                    foreach (string skinFile in skins)
                    {
                        try
                        {
                            string skinPath = Path.Combine("replacedets", "skins", Path.GetFileName(skinFile));
                            Monitor.Log($"Adding skin {Path.GetFileName(skinFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
                            Texture2D skin = contentPack.Loadreplacedet<Texture2D>(skinPath.Replace("_landscape.png", ".png"));
                            Texture2D skinl = contentPack.Loadreplacedet<Texture2D>(skinPath);
                            ThemeApp.skinList.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(skinFile).Replace("_landscape.png", ""));
                            ThemeApp.skinDict.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(skinFile).Replace("_landscape.png", ""), new Texture2D[] { skin, skinl});
                            Monitor.Log($"Added skin {Path.GetFileName(skinFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
                        }
                        catch { }
                    }
                }
                if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "backgrounds")))
                {
                    Monitor.Log($"Adding backgrounds");
                    string[] backgrounds = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "backgrounds"), "*_landscape.png");
                    Monitor.Log($"CP has {backgrounds.Length} backgrounds");
                    foreach (string backFile in backgrounds)
                    {
                        try
                        {
                            string backPath = Path.Combine("replacedets", "backgrounds", Path.GetFileName(backFile));
                            Monitor.Log($"Adding background {Path.GetFileName(backFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
                            Texture2D back = contentPack.Loadreplacedet<Texture2D>(backPath.Replace("_landscape.png", ".png"));
                            Texture2D backl = contentPack.Loadreplacedet<Texture2D>(backPath);
                            ThemeApp.backgroundDict.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(backFile).Replace("_landscape.png", ""), new Texture2D[] { back, backl });
                            ThemeApp.backgroundList.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(backFile).Replace("_landscape.png", ""));
                            Monitor.Log($"Added background {Path.GetFileName(backFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
                        }
                        catch { }
                    }
                }
                if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "ringtones")))
                {
                    Monitor.Log($"Adding ringtones");
                    string[] rings = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "ringtones"), "*.wav");
                    Monitor.Log($"CP has {rings.Length} ringtones");
                    foreach (string path in rings)
                    {
                        try
                        {
                            object ring;
                            try
                            {
                                var type = Type.GetType("System.Media.SoundPlayer, System");
                                ring = Activator.CreateInstance(type, new object[] { path });
                            }
                            catch
                            {
                                ring = SoundEffect.FromStream(new FileStream(path, FileMode.Open));
                            }
                            if (ring != null)
                            {
                                ThemeApp.ringDict.Add(string.Concat(contentPack.Manifest.UniqueID,":", Path.GetFileName(path).Replace(".wav", "")), ring);
                                ThemeApp.ringList.Add(string.Concat(contentPack.Manifest.UniqueID,":", Path.GetFileName(path).Replace(".wav", "")));
                                Monitor.Log($"loaded ring {path}");
                            }
                            else
                                Monitor.Log($"Couldn't load ring {path}");
                        }
                        catch (Exception ex)
                        {
                            Monitor.Log($"Couldn't load ring {path}:\r\n{ex}", LogLevel.Error);
                        }
                    }
                }
            }

            ModEntry.listHeight = Config.IconMarginY + (int)Math.Ceiling(ModEntry.apps.Count / (float)ModEntry.gridWidth) * (Config.IconHeight + Config.IconMarginY);
            PhoneVisuals.CreatePhoneTextures();
            PhoneUtils.RefreshPhoneLayout();

            if (Helper.ModRegistry.IsLoaded("purrplingcat.npcadventure"))
            {
                INpcAdventureModApi api = Helper.ModRegistry.GetApi<INpcAdventureModApi>("purrplingcat.npcadventure");
                if (api != null)
                {
                    Monitor.Log("Loaded NpcAdventureModApi successfully");
                    ModEntry.npcAdventureModApi = api;
                }
            }
        }

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

private bool RegisterDataProviderInternal<T>(
            bool retryWithRegistrar,
            Type concreteType,
            SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
            params object[] args) where T : IMixedRealityDataProvider
        {
#if !UNITY_EDITOR
            if (!Application.platform.IsPlatformSupported(supportedPlatforms))
#else
            if (!EditorUserBuildSettings.activeBuildTarget.IsPlatformSupported(supportedPlatforms))
#endif
            {
                return false;
            }

            if (concreteType == null)
            {
                Debug.LogError($"Unable to register {typeof(T).Name} service with a null concrete type.");
                return false;
            }

            if (!typeof(IMixedRealityDataProvider).IsreplacedignableFrom(concreteType))
            {
                Debug.LogError($"Unable to register the {concreteType.Name} data provider. It does not implement {typeof(IMixedRealityDataProvider)}.");
                return false;
            }

            T dataProviderInstance;

            try
            {
                dataProviderInstance = (T)Activator.CreateInstance(concreteType, args);
            }
            catch (Exception e)
            {
                if (retryWithRegistrar && (e is MissingMethodException))
                {
                    Debug.LogWarning($"Failed to find an appropriate constructor for the {concreteType.Name} data provider. Adding the Registrar instance and re-attempting registration.");
#pragma warning disable 0618
                    List<object> updatedArgs = new List<object>();
                    updatedArgs.Add(Registrar);
                    if (args != null)
                    {
                        updatedArgs.AddRange(args);
                    }
                    return RegisterDataProviderInternal<T>(
                        false, // Do NOT retry, we have already added the configured IMIxedRealityServiceRegistrar
                        concreteType,
                        supportedPlatforms,
                        updatedArgs.ToArray());
#pragma warning restore 0618
                }

                Debug.LogError($"Failed to register the {concreteType.Name} data provider: {e.GetType()} - {e.Message}");

                // Failures to create the concrete type generally surface as nested exceptions - just logging
                // the top level exception itself may not be helpful. If there is a nested exception (for example,
                // null reference in the constructor of the object itself), it's helpful to also surface those here.
                if (e.InnerException != null)
                {
                    Debug.LogError("Underlying exception information: " + e.InnerException);
                }
                return false;
            }

            return RegisterDataProvider(dataProviderInstance);
        }

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

private IDbAdapter CreateDbAdapter(string dbAdapterreplacedemblyName, replacedembly dbAdapterreplacedembly)
    {
        var dbAdapterType = dbAdapterreplacedembly.GetType($"{dbAdapterreplacedemblyName}.{Options.Provider}DbAdapter");

        Check.NotNull(dbAdapterType, $"数据库适配器{dbAdapterreplacedemblyName}未安装");

        var dbAdapter = (IDbAdapter)Activator.CreateInstance(dbAdapterType!);
        dbAdapterType.GetProperty("Options")!.SetValue(dbAdapter, Options);
        return dbAdapter;
    }

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 : DynamicProxyMeta.cs
License : MIT License
Project Creator : 2881099

public static object CreateInstanceDefault(Type type)
        {
            if (type == null) return null;
            if (type == typeof(string)) return default(string);
            if (type.IsArray) return Array.CreateInstance(type, 0);
            var ctorParms = InternalGetTypeConstructor0OrFirst(type, true)?.GetParameters();
            if (ctorParms == null || ctorParms.Any() == false) return Activator.CreateInstance(type, null);
            return Activator.CreateInstance(type, ctorParms.Select(a => a.ParameterType.IsInterface || a.ParameterType.IsAbstract || a.ParameterType == typeof(string) ? null : Activator.CreateInstance(a.ParameterType, null)).ToArray());
        }

19 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 : StringLocalizerFactory.cs
License : Apache License 2.0
Project Creator : Aguafrommars

public IStringLocalizer Create(Type resourceSource)
        {
            if (resourceSource != null)
            {
                var type = typeof(StringLocalizer<>).MakeGenericType(new Type[] { resourceSource });
                return Activator.CreateInstance(type, _provider) as IStringLocalizer;
            }

            return new StringLocalizer(_provider, null, null);
        }

See More Examples