Type() public static method

Returns a string that can be used for representing a System.Type in log entries.
public static Type ( Type type ) : string
type System.Type
return string
Example #1
0
        /// <summary>
        /// Loads the Resource from the specified <see cref="Stream"/>. You shouldn't need this method in almost all cases.
        /// Only use it when you know exactly what you're doing. Consider requesting the Resource from the <see cref="ContentProvider"/> instead.
        /// </summary>
        /// <typeparam name="T">
        /// Desired Type of the returned reference. Does not affect the loaded Resource in any way - it is simply returned as T.
        /// Results in returning null if the loaded Resource's Type isn't assignable to T.
        /// </typeparam>
        /// <param name="str">The stream to load the Resource from.</param>
        /// <param name="resPath">The path that is assumed as the loaded Resource's origin.</param>
        /// <param name="loadCallback">An optional callback that is invoked right after loading the Resource, but before initializing it.</param>
        /// <param name="initResource">
        /// Specifies whether or not the Resource is initialized by calling <see cref="Resource.OnLoaded"/>. Never attempt to use
        /// uninitialized Resources or register them in the ContentProvider.
        /// </param>
        /// <returns>The Resource that has been loaded.</returns>
        public static T Load <T>(Formatter formatter, string resPath = null, Action <T> loadCallback = null, bool initResource = true) where T : Resource
        {
            T newContent = null;

            try
            {
                Resource res = formatter.ReadObject <Resource>();
                if (res == null)
                {
                    throw new ApplicationException("Loading Resource failed");
                }

                res.initState = InitState.Initializing;
                res.path      = resPath;
                if (loadCallback != null)
                {
                    loadCallback(res as T);                                       // Callback before initializing.
                }
                if (initResource)
                {
                    Init(res);
                }
                newContent = res as T;
            }
            catch (Exception e)
            {
                Log.Core.WriteError("Can't load {0} from '{1}', because an error occurred: {3}{2}",
                                    Log.Type(typeof(T)),
                                    resPath ?? formatter.ToString(),
                                    Log.Exception(e),
                                    Environment.NewLine);
            }

            return(newContent);
        }
Example #2
0
        /// <summary>
        /// Adds the specified <see cref="Component"/> to this GameObject, if no Component of that Type is already part of this GameObject.
        /// Simply uses the already added Component otherwise.
        /// </summary>
        /// <typeparam name="T">The Components Type.</typeparam>
        /// <param name="newComp">The Component instance to add to this GameObject.</param>
        /// <returns>A reference to a Component of the specified Type</returns>
        /// <exception cref="System.ArgumentException">Thrown if the specified Component is already attached to a GameObject</exception>
        public T AddComponent <T>(T newComp) where T : Component
        {
            if (newComp.gameobj != null)
            {
                throw new ArgumentException(String.Format(
                                                "Specified Component '{0}' is already part of another GameObject '{1}'",
                                                Log.Type(newComp.GetType()),
                                                newComp.gameobj.FullName));
            }

            Type cType = newComp.GetType();

            if (this.compMap.ContainsKey(cType))
            {
                return(this.compMap[cType] as T);
            }

            newComp.gameobj = this;
            this.compMap.Add(cType, newComp);
            this.compList.Add(newComp);

            if (newComp is Components.Transform)
            {
                this.compTransform = (Components.Transform)(Component) newComp;
            }

            this.OnComponentAdded(newComp);
            return(newComp);
        }
Example #3
0
        private static void CleanInputSources(Assembly invalidAssembly)
        {
            string warningText = string.Format(
                "Found leaked input source '{1}' defined in invalid Assembly '{0}'. " +
                "This is a common problem when registering input sources from within a CorePlugin " +
                "without properly unregistering them later. Please make sure that all sources are " +
                "unregistered in CorePlugin::OnDisposePlugin().",
                invalidAssembly.GetShortAssemblyName(),
                "{0}");

            if (mouse.Source != null && mouse.Source.GetType().Assembly == invalidAssembly)
            {
                mouse.Source = null;
                Log.Core.WriteWarning(warningText, Log.Type(mouse.Source.GetType()));
            }
            if (keyboard.Source != null && keyboard.Source.GetType().Assembly == invalidAssembly)
            {
                keyboard.Source = null;
                Log.Core.WriteWarning(warningText, Log.Type(keyboard.Source.GetType()));
            }
            foreach (JoystickInput joystick in joysticks.ToArray())
            {
                if (joystick.Source != null && joystick.Source.GetType().Assembly == invalidAssembly)
                {
                    joysticks.RemoveSource(joystick.Source);
                    Log.Core.WriteWarning(warningText, Log.Type(joystick.Source.GetType()));
                }
            }
        }
Example #4
0
 /// <summary>
 /// Returns a string that can be used for representing a <see cref="System.Reflection.TypeInfo"/> in log entries.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static string Type(TypeInfo type)
 {
     if (type == null)
     {
         return("null");
     }
     return(Log.Type(type.AsType()));
 }
Example #5
0
        private static void CleanEventBindings(Assembly invalidAssembly)
        {
            // Note that this method is only a countermeasure against common mistakes. It doesn't guarantee
            // full error safety in all cases. Event bindings inbetween different plugins aren't checked,
            // for example.

            string warningText = string.Format(
                "Found leaked event bindings to invalid Assembly '{0}' from {1}. " +
                "This is a common problem when registering global events from within a CorePlugin " +
                "without properly unregistering them later. Please make sure that all events are " +
                "unregistered in CorePlugin::OnDisposePlugin().",
                invalidAssembly.GetShortAssemblyName(),
                "{0}");

            if (ReflectionHelper.CleanEventBindings(typeof(DualityApp), invalidAssembly))
            {
                Log.Core.WriteWarning(warningText, Log.Type(typeof(DualityApp)));
            }
            if (ReflectionHelper.CleanEventBindings(typeof(Scene), invalidAssembly))
            {
                Log.Core.WriteWarning(warningText, Log.Type(typeof(Scene)));
            }
            if (ReflectionHelper.CleanEventBindings(typeof(Resource), invalidAssembly))
            {
                Log.Core.WriteWarning(warningText, Log.Type(typeof(Resource)));
            }
            if (ReflectionHelper.CleanEventBindings(typeof(ContentProvider), invalidAssembly))
            {
                Log.Core.WriteWarning(warningText, Log.Type(typeof(ContentProvider)));
            }
            if (ReflectionHelper.CleanEventBindings(DualityApp.Keyboard, invalidAssembly))
            {
                Log.Core.WriteWarning(warningText, Log.Type(typeof(DualityApp)) + ".Keyboard");
            }
            if (ReflectionHelper.CleanEventBindings(DualityApp.Mouse, invalidAssembly))
            {
                Log.Core.WriteWarning(warningText, Log.Type(typeof(DualityApp)) + ".Mouse");
            }
            foreach (JoystickInput joystick in DualityApp.Joysticks)
            {
                if (ReflectionHelper.CleanEventBindings(joystick, invalidAssembly))
                {
                    Log.Core.WriteWarning(warningText, Log.Type(typeof(DualityApp)) + ".Joysticks");
                }
            }
            foreach (GamepadInput gamepad in DualityApp.Gamepads)
            {
                if (ReflectionHelper.CleanEventBindings(gamepad, invalidAssembly))
                {
                    Log.Core.WriteWarning(warningText, Log.Type(typeof(DualityApp)) + ".Gamepads");
                }
            }
        }
Example #6
0
        private static FieldInfo GetField(Type type, string name)
        {
            FieldInfo result = type.GetRuntimeFields().FirstOrDefault(m => !m.IsStatic && m.Name == name);

            if (result == null)
            {
                Log.Core.WriteError(
                    "Unable to retrieve field '{0}' of type '{1}'.",
                    name,
                    Log.Type(type));
            }
            return(result);
        }
Example #7
0
        private static PropertyInfo GetProperty(Type type, string name)
        {
            PropertyInfo result = type.GetRuntimeProperties().FirstOrDefault(m => !m.IsStatic() && m.Name == name);

            if (result == null)
            {
                Log.Core.WriteError(
                    "Unable to retrieve property '{0}' of type '{1}'.",
                    name,
                    Log.Type(type));
            }
            return(result);
        }
Example #8
0
 public override string ToString()
 {
     if (this.SkipIfExists > 0)
     {
         return(string.Format("Skip {0} if {1} exists",
                              this.SkipIfExists,
                              Log.Type(this.RequiredType)));
     }
     else
     {
         return(string.Format("Require {0} or create {1}",
                              Log.Type(this.RequiredType),
                              Log.Type(this.CreateType)));
     }
 }
        /// <summary>
        /// Adds an already loaded plugin Assembly to the internal Duality T registry.
        /// You shouldn't need to call this method in general, since Duality manages its plugins
        /// automatically.
        /// </summary>
        /// <remarks>
        /// This method can be useful in certain cases when it is necessary to treat an Assembly as a
        /// Duality plugin, even though it isn't located in the Plugins folder, or is not available
        /// as a file at all. A typical case for this is Unit Testing where the testing Assembly may
        /// specify additional Duality types such as Components, Resources, etc.
        /// </remarks>
        /// <param name="pluginAssembly"></param>
        /// <param name="pluginFilePath"></param>
        /// <returns></returns>
        public T LoadPlugin(Assembly pluginAssembly, string pluginFilePath)
        {
            this.disposedPlugins.Remove(pluginAssembly);

            string asmName = pluginAssembly.GetShortAssemblyName();
            T      plugin  = this.pluginRegistry.Values.FirstOrDefault(p => p.AssemblyName == asmName);

            if (plugin != null)
            {
                return(plugin);
            }

            try
            {
                TypeInfo pluginType = pluginAssembly.ExportedTypes
                                      .Select(t => t.GetTypeInfo())
                                      .FirstOrDefault(t => typeof(T).GetTypeInfo().IsAssignableFrom(t));

                if (pluginType == null)
                {
                    throw new Exception(string.Format(
                                            "Plugin does not contain a public {0} class.",
                                            typeof(T).Name));
                }

                plugin = (T)pluginType.CreateInstanceOf();

                if (plugin == null)
                {
                    throw new Exception(string.Format(
                                            "Failed to instantiate {0} class.",
                                            Log.Type(pluginType.GetType())));
                }

                plugin.FilePath = pluginFilePath;
                plugin.FileHash = this.pluginLoader.GetAssemblyHash(pluginFilePath);

                this.pluginRegistry.Add(plugin.AssemblyName, plugin);
            }
            catch (Exception e)
            {
                this.pluginLog.WriteError("Error loading plugin: {0}", Log.Exception(e));
                this.disposedPlugins.Add(pluginAssembly);
                plugin = null;
            }

            return(plugin);
        }
Example #10
0
            public void EnsureCreationChain(ComponentRequirementMap map)
            {
                if (this.initCreationChain == RecursiveInit.Initialized)
                {
                    return;
                }
                if (this.initCreationChain == RecursiveInit.InProgress)
                {
                    Log.Core.WriteWarning(
                        "Detected a cyclic Component requirement in {0}. Requirements can not be ensured for cyclic dependencies.",
                        Log.Type(this.Component));
                    return;
                }

                this.initCreationChain = RecursiveInit.InProgress;
                this.InitCreationChain(map);
                this.initCreationChain = RecursiveInit.Initialized;
            }
        /// <summary>
        /// Clears the specified constraint graph of all loops.
        /// </summary>
        /// <param name="graph"></param>
        private static void ResolveConstraintLoops(Dictionary <Type, List <OrderConstraint> > graph)
        {
            while (true)
            {
                List <OrderConstraint> loop = FindConstraintLoop(graph);
                if (loop == null)
                {
                    return;
                }

                // Found a loop? Find the weakest link in it
                OrderConstraint weakestLink = loop[0];
                for (int i = 1; i < loop.Count; i++)
                {
                    OrderConstraint link = loop[i];
                    if ((int)link.Priority < (int)weakestLink.Priority)
                    {
                        weakestLink = link;
                    }
                }

                // If the loops weakest link was an explicit constraint, log a warning
                if ((int)weakestLink.Priority >= (int)ConstraintPriority.ExplicitWeak)
                {
                    Log.Core.WriteWarning(
                        "Found a loop in the component execution order constraint graph. Ignoring the weakest constraint " +
                        "({0} must be executed before {1}). Please check your ExecutionOrder attributes.",
                        Log.Type(weakestLink.FirstType),
                        Log.Type(weakestLink.LastType));
                }

                // Remove the weakest link
                List <OrderConstraint> links = graph[weakestLink.FirstType];
                links.Remove(weakestLink);
                if (links.Count == 0)
                {
                    graph.Remove(weakestLink.FirstType);
                }
            }
        }
Example #12
0
        /// <summary>
        /// Adds the specified <see cref="Component"/> to this GameObject, if no Component of that Type is already part of this GameObject.
        /// Simply uses the already added Component otherwise.
        /// </summary>
        /// <typeparam name="T">The Components Type.</typeparam>
        /// <param name="newComp">The Component instance to add to this GameObject.</param>
        /// <returns>A reference to a Component of the specified Type</returns>
        /// <exception cref="System.ArgumentException">Thrown if the specified Component is already attached to a GameObject</exception>
        public T AddComponent <T>(T newComp) where T : Component
        {
            if (newComp.gameobj != null)
            {
                throw new ArgumentException(String.Format(
                                                "Specified Component '{0}' is already part of another GameObject '{1}'",
                                                Log.Type(newComp.GetType()),
                                                newComp.gameobj.FullName));
            }

            Type      type = newComp.GetType();
            Component existing;

            if (this.compMap.TryGetValue(type, out existing))
            {
                return(existing as T);
            }

            this.AddComponent(newComp, type);

            return(newComp);
        }
Example #13
0
        /// <summary>
        /// Returns an existing <see cref="ProfileCounter"/> with the specified name.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="name">The <see cref="ProfileCounter"/> name to use for this measurement. For nested measurements, use path strings, e.g. "ParentCounter\ChildCounter"</param>
        /// <returns></returns>
        public static T GetCounter <T>(string name) where T : ProfileCounter
        {
            if (name == null)
            {
                return(null);
            }

            ProfileCounter c;

            if (!counterMap.TryGetValue(name, out c))
            {
                return(null);
            }

            T cc = c as T;

            if (cc == null)
            {
                throw new InvalidOperationException(string.Format("The specified performance counter '{0}' is not a {1}.", name, Log.Type(typeof(T))));
            }
            return(cc);
        }
Example #14
0
        private static CreateMethod CreateObjectActivator(TypeInfo typeInfo, out object firstResult)
        {
            CreateMethod activator;

            firstResult = null;

            // Filter out non-instantiatable Types
            if (typeInfo.IsAbstract || typeInfo.IsInterface || typeInfo.IsGenericTypeDefinition)
            {
                activator = nullObjectActivator;
            }
            // If the caller wants a string, just return an empty one
            else if (typeInfo.AsType() == typeof(string))
            {
                activator = () => "";
            }
            // If the caller wants an array, create an empty one
            else if (typeInfo.IsArray && typeInfo.GetArrayRank() == 1)
            {
                activator = () => Array.CreateInstance(typeInfo.GetElementType(), 0);
            }
            // For structs, boxing a default(T) is sufficient
            else if (typeInfo.IsValueType)
            {
                var lambda = Expression.Lambda <CreateMethod>(Expression.Convert(Expression.Default(typeInfo.AsType()), typeof(object)));
                activator = lambda.Compile();
            }
            else
            {
                activator = nullObjectActivator;

                // Retrieve constructors, sorted from trivial to parameter-rich
                ConstructorInfo[] constructors = typeInfo.DeclaredConstructors
                                                 .Where(c => !c.IsStatic)
                                                 .Select(c => new { Info = c, ParamCount = c.GetParameters().Length })
                                                 .OrderBy(s => s.ParamCount)
                                                 .Select(s => s.Info)
                                                 .ToArray();

                Exception lastError = null;
                foreach (ConstructorInfo con in constructors)
                {
                    // Prepare constructor argument values - just use default(T) for all of them.
                    ParameterInfo[] conParams = con.GetParameters();
                    Expression[]    args      = new Expression[conParams.Length];
                    for (int i = 0; i < args.Length; i++)
                    {
                        Type paramType = conParams[i].ParameterType;
                        args[i] = Expression.Default(paramType);
                    }

                    // Compile a lambda method invoking the constructor
                    var lambda = Expression.Lambda <CreateMethod>(Expression.New(con, args));
                    activator = lambda.Compile();

                    // Does it work?
                    firstResult = CheckActivator(activator, out lastError);
                    if (firstResult != null)
                    {
                        break;
                    }
                }

                // If all constructors failed, inform someone. This is not ideal.
                if (firstResult == null)
                {
                    Log.Core.WriteWarning("Failed to create object of Type {0}. Make sure there is a trivial constructor.", Log.Type(typeInfo));
                }
            }

            // Test whether our activation method really works, replace with dummy if not
            if (firstResult == null)
            {
                Exception error;
                firstResult = CheckActivator(activator, out error);

                // If we fail to initialize the Type due to a problem in its static constructor, it's likely a user problem. Let him know.
                if (error is TypeInitializationException)
                {
                    Log.Core.WriteError("Failed to initialize Type {0}: {1}",
                                        Log.Type(typeInfo),
                                        Log.Exception(error.InnerException));
                }
            }

            // If we still don't have anything, just use a dummy.
            if (firstResult == null)
            {
                activator = nullObjectActivator;
            }

            return(activator);
        }
Example #15
0
        internal static void InitBackend <T>(out T target, Func <Type, IEnumerable <TypeInfo> > typeFinder = null) where T : class, IDualityBackend
        {
            if (typeFinder == null)
            {
                typeFinder = GetAvailDualityTypes;
            }

            Log.Core.Write("Initializing {0}...", Log.Type(typeof(T)));
            Log.Core.PushIndent();

            // Generate a list of available backends for evaluation
            List <IDualityBackend> backends = new List <IDualityBackend>();

            foreach (TypeInfo backendType in typeFinder(typeof(IDualityBackend)))
            {
                if (backendType.IsInterface)
                {
                    continue;
                }
                if (backendType.IsAbstract)
                {
                    continue;
                }
                if (!backendType.IsClass)
                {
                    continue;
                }
                if (!typeof(T).GetTypeInfo().IsAssignableFrom(backendType))
                {
                    continue;
                }

                IDualityBackend backend = backendType.CreateInstanceOf() as IDualityBackend;
                if (backend == null)
                {
                    Log.Core.WriteWarning("Unable to create an instance of {0}. Skipping it.", backendType.FullName);
                    continue;
                }
                backends.Add(backend);
            }

            // Sort backends from best to worst
            backends.StableSort((a, b) => b.Priority > a.Priority ? 1 : -1);

            // Try to initialize each one and select the first that works
            T selectedBackend = null;

            foreach (T backend in backends)
            {
                if (appData != null &&
                    appData.SkipBackends != null &&
                    appData.SkipBackends.Any(s => string.Equals(s, backend.Id, StringComparison.OrdinalIgnoreCase)))
                {
                    Log.Core.Write("Backend '{0}' skipped because of AppData settings.", backend.Name);
                    continue;
                }

                bool available = false;
                try
                {
                    available = backend.CheckAvailable();
                    if (!available)
                    {
                        Log.Core.Write("Backend '{0}' reports to be unavailable. Skipping it.", backend.Name);
                    }
                }
                catch (Exception e)
                {
                    available = false;
                    Log.Core.WriteWarning("Backend '{0}' failed the availability check with an exception: {1}", backend.Name, Log.Exception(e));
                }
                if (!available)
                {
                    continue;
                }

                Log.Core.Write("{0}...", backend.Name);
                Log.Core.PushIndent();
                {
                    try
                    {
                        backend.Init();
                        selectedBackend = backend;
                    }
                    catch (Exception e)
                    {
                        Log.Core.WriteError("Failed: {0}", Log.Exception(e));
                    }
                }
                Log.Core.PopIndent();

                if (selectedBackend != null)
                {
                    break;
                }
            }

            // If we found a proper backend and initialized it, add it to the list of active backends
            if (selectedBackend != null)
            {
                target = selectedBackend;

                TypeInfo selectedBackendType = selectedBackend.GetType().GetTypeInfo();
                pluginManager.LockPlugin(selectedBackendType.Assembly);
            }
            else
            {
                target = null;
            }

            Log.Core.PopIndent();
        }
Example #16
0
 /// <summary>
 /// Returns a string that can be used for representing a <see cref="System.Reflection.TypeInfo"/> in log entries.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static string Type(TypeInfo type)
 {
     return(Log.Type(type.AsType()));
 }