示例#1
0
        ///Create uninitialized object of type
		public static object CreateObjectUninitialized(this Type type) {
            if ( type == null ) return null;
            return FormatterServices.GetUninitializedObject(type);
        }
 static partial void RealInstanceFactory(ref ServiceDefinition real, string callerName)
 {
     real = (ServiceDefinition)FormatterServices.GetUninitializedObject(typeof(ServiceDefinition));
 }
        public void TagImages(string directory, string textFileName)
        {
            int[] tagDecimal = { 40091, 50971, 40094, 40095, 40092, 36867, 270 };

            /* Decimal Representation of relevant Exif properties tag ID
             * 40091 XPtitle ()              0
             * 50971 Date/time ISO8601       1
             * 40094 XPkeywords (category)   2
             * 40095 XPsubject (description) 3
             * 40092 XPcomment               4
             * 36867 DateTimeOriginal
             *  270  ImageComment
             */


            //Initialise needed items, strings need to be encoded
            //PropertyItem will hold our tag then write the tag to a bit map of our image of our image which will finally be saved
            PropertyItem    propertyItem;
            ASCIIEncoding   ascii = new ASCIIEncoding();
            UnicodeEncoding uni   = new UnicodeEncoding();

            //PropertyItem contains no constructor that can be called without arguments, has a constructor with descernable arguments
            propertyItem = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));


            Image         imageToTag;
            DataExtractor fromFile  = new DataExtractor(directory, textFileName);
            DataStore     dataStore = new DataStore(fromFile.GetArray());

            //get jpg source location

            /*string destination = "";
             * FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
             * if (directory != "")
             * {
             *  folderBrowser.SelectedPath = directory;
             *  destination = directory.Substring(0, directory.Length - 2);
             * }
             *
             * //Get folder for destination of images
             * if (folderBrowser.ShowDialog() == DialogResult.OK)
             * {
             *  destination = folderBrowser.SelectedPath;
             * }
             * else
             * {
             *
             * }
             */

            string destination = directory.Substring(0, directory.Length - 2);

            //Loop to store all images in batch
            for (int i = 0; i < dataStore.ImageCount; i++)
            {
                string extention = dataStore.imageData[i].FileName.Substring(dataStore.imageData[i].FileName.Length - 4, 4); // (dataExtractor.imageData[i].data[n].Equals(input, StringComparison.OrdinalIgnoreCase))
                if (extention.Equals(".jpg", StringComparison.OrdinalIgnoreCase))
                {
                    imageToTag = new Bitmap(directory + dataStore.imageData[i].FileName);       //Generate a bitmap image of our source image

                    for (int j = 0; j <= 4; j++)
                    {
                        propertyItem.Id = tagDecimal[j];        //Set property item id to the relevant tag decimal tag ID
                        if (j == 1)
                        {
                            propertyItem.Value = ascii.GetBytes(dataStore.imageData[i].Date);       //Date tag needs ascii encoding
                        }
                        else
                        {
                            propertyItem.Value = uni.GetBytes(dataStore.imageData[i].data[j]);      //All other tags unicode
                        }
                        propertyItem.Type = 1;
                        propertyItem.Len  = propertyItem.Value.Length;      //relevante property item details set
                        imageToTag.SetPropertyItem(propertyItem);           //PropertyItems set in our image bitmap
                    }

                    imageToTag.Save(destination + dataStore.imageData[i].FileName);     //Save the bitmap with propertyItems now set to a jpg
                }
            }
        }
示例#4
0
 public object CreateToDeserialize()
 {
     return(FormatterServices.GetUninitializedObject(DeclaredType));
 }
 static partial void RealInstanceFactory(ref WorkItemSyncData real, string callerName)
 {
     real = (WorkItemSyncData)FormatterServices.GetUninitializedObject(typeof(WorkItemSyncData));
 }
示例#6
0
        public void ThrowsWhenItemSchemaIsNeverSet()
        {
            var schema = (ArraySchema)FormatterServices.GetUninitializedObject(typeof(ArraySchema));

            Assert.Throws <InvalidOperationException>(() => schema.Item);
        }
        public static async Task InvokeAsync(HttpContext context)
        {
            var logger       = context.RequestServices.GetService <ILoggerFactory>().CreateLogger(typeof(CommandEndpointRequestHandler));
            var timer        = Stopwatch.StartNew();
            var endpoint     = context.GetEndpoint();
            var registration = endpoint.Metadata.GetMetadata <CommandEndpointRegistration>();
            var requestId    = string.Empty;

            // prepare request model
            object requestModel;

            if (context.Request.ContentLength.GetValueOrDefault() != 0)
            {
                try
                {
                    // warning: json properties are case sensitive
                    requestModel = await JsonSerializer.DeserializeAsync(context.Request.Body, registration.RequestType, null, context.RequestAborted).ConfigureAwait(false);
                }
                catch (JsonException exception)
                {
                    logger.LogError($"deserialize: [{exception.GetType().Name}] {exception.Message}", exception);
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                    return;
                }
                catch (Exception exception) when(exception is FormatException || exception is OverflowException)
                {
                    logger.LogError($"deserialize: [{exception.GetType().Name}] {exception.Message}", exception);
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                    return;
                }
            }
            else
            {
                if (registration.RequestType.HasDefaultConstructor())
                {
                    requestModel = Activator.CreateInstance(registration.RequestType); // calls ctor
                }
                else
                {
                    requestModel = FormatterServices.GetUninitializedObject(registration.RequestType); //does not call ctor
                }
            }

            // map path and querystring values to created request model
            var parameterItems = GetParameterValues(registration.Pattern, context.Request.Path, context.Request.QueryString.Value);

            ReflectionHelper.SetProperties(requestModel, parameterItems);

            if (requestModel is ICommand command)
            {
                requestId = command.CommandId;
                logger.LogDebug("request: starting command (type={commandRequestType}, id={commandId}), method={commandRequestMethod}) {commandRequestUri}", registration.RequestType.Name, requestId, context.Request.Method.ToUpper(), context.Request.GetUri().ToString());
                context.Response.Headers.Add("X-CommandId", requestId);
            }
            else if (requestModel is IQuery query)
            {
                requestId = query.QueryId;
                logger.LogDebug("request: starting query (type={queryRequestType}, id={queryId}), method={queryRequestMethod}) {commandRequestUri}", registration.RequestType.Name, requestId, context.Request.Method.ToUpper(), context.Request.GetUri().ToString());
                context.Response.Headers.Add("X-QueryId", requestId);
            }
            else
            {
                // TODO: throw if unknown type
            }

            await SendRequest(context, registration, requestModel, requestId).ConfigureAwait(false);

            timer.Stop();
            if (requestModel is ICommand)
            {
                logger.LogDebug("request: finished command (type={commandRequestType}, id={commandId})) -> took {elapsed} ms", registration.RequestType.Name, requestId, timer.ElapsedMilliseconds);
            }
            else if (requestModel is IQuery)
            {
                logger.LogDebug("request: finished query (type={queryRequestType}, id={queryId})) -> took {elapsed} ms", registration.RequestType.Name, requestId, timer.ElapsedMilliseconds);
            }
        }
示例#8
0
        // Helpers.

        private object GetInstanceOf(Type type)
        {
            return(type.GetConstructor(Type.EmptyTypes) != null
                ? Activator.CreateInstance(type)
                : FormatterServices.GetUninitializedObject(type));
        }
示例#9
0
        IEnumerator Unpack(MsgPackReader reader, Type t)
        {
            if (t.IsPrimitive)
            {
                reader.Read();
                if (t.Equals(typeof(int)) && reader.IsSigned())
                {
                    yield return(reader.ValueSigned);
                }
                else if (t.Equals(typeof(uint)) && reader.IsUnsigned())
                {
                    yield return(reader.ValueUnsigned);
                }
                else if (t.Equals(typeof(float)) && reader.Type == TypePrefixes.Float)
                {
                    yield return(reader.ValueFloat);
                }
                else if (t.Equals(typeof(double)) && reader.Type == TypePrefixes.Double)
                {
                    yield return(reader.ValueDouble);
                }
                else if (t.Equals(typeof(long)))
                {
                    if (reader.IsSigned64())
                    {
                        yield return(reader.ValueSigned64);
                    }
                    if (reader.IsSigned())
                    {
                        yield return((long)reader.ValueSigned);
                    }
                }
                else if (t.Equals(typeof(ulong)))
                {
                    if (reader.IsUnsigned64())
                    {
                        yield return(reader.ValueUnsigned64);
                    }
                    if (reader.IsUnsigned())
                    {
                        yield return((ulong)reader.ValueUnsigned);
                    }
                }
                else if (t.Equals(typeof(bool)) && reader.IsBoolean())
                {
                    yield return(reader.Type == TypePrefixes.True);
                }
                else if (t.Equals(typeof(byte)) && reader.IsUnsigned())
                {
                    yield return((byte)reader.ValueUnsigned);
                }
                else if (t.Equals(typeof(sbyte)) && reader.IsSigned())
                {
                    yield return((sbyte)reader.ValueSigned);
                }
                else if (t.Equals(typeof(short)) && reader.IsSigned())
                {
                    yield return((short)reader.ValueSigned);
                }
                else if (t.Equals(typeof(ushort)) && reader.IsUnsigned())
                {
                    yield return((ushort)reader.ValueUnsigned);
                }
                else if (t.Equals(typeof(char)) && reader.IsUnsigned())
                {
                    yield return((char)reader.ValueUnsigned);
                }
                else
                {
                    throw new NotSupportedException();
                }
            }

            UnpackDelegate unpacker;

            if (UnpackerMapping.TryGetValue(t, out unpacker))
            {
                yield return(unpacker(this, reader));
            }

            if (t.IsArray)
            {
                reader.Read();
                if (!reader.IsArray() && reader.Type != TypePrefixes.Nil)
                {
                    throw new FormatException();
                }
                if (reader.Type == TypePrefixes.Nil)
                {
                    yield return(null);
                }
                Type  et  = t.GetElementType();
                Array ary = Array.CreateInstance(et, (int)reader.Length);
                for (int i = 0; i < ary.Length; i++)
                {
                    ary.SetValue(Unpack(reader, et), i);
                }
                yield return(ary);
            }

            reader.Read();
            if (reader.Type == TypePrefixes.Nil)
            {
                yield return(null);
            }
            if (t.IsInterface)
            {
                if (reader.Type != TypePrefixes.FixArray && reader.Length != 2)
                {
                    throw new FormatException();
                }
                reader.Read();
                if (!reader.IsBinary())
                {
                    throw new FormatException();
                }
                Reserve(reader.Length);
                reader.ReadRawBytes(_buf);
                string name = reader.StringifyBytes(_buf);
                t = Type.GetType(name);
                reader.Read();
                if (reader.Type == TypePrefixes.Nil)
                {
                    throw new FormatException();
                }
            }
            if (!reader.IsMap())
            {
                throw new FormatException();
            }

            object o = FormatterServices.GetUninitializedObject(t);
            ReflectionCacheEntry entry = ReflectionCache.Lookup(t);
            int members = (int)reader.Length;

            for (int i = 0; i < members; i++)
            {
                reader.Read();
                if (!reader.IsBinary())
                {
                    throw new FormatException();
                }
                Reserve(reader.Length);
                reader.ReadRawBytes(_buf);
                string    name = reader.StringifyBytes(_buf);
                FieldInfo f;
                if (!entry.FieldMap.TryGetValue(name, out f))
                {
                    throw new FormatException();
                }
                f.SetValue(o, Unpack(reader, f.FieldType));
            }

            IDeserializationCallback callback = o as IDeserializationCallback;

            if (callback != null)
            {
                callback.OnDeserialization(this);
            }
            yield return(o);
        }
示例#10
0
        private object DeserializeObject(
            Type type,
            long id,
            long parentId,
            MemberInfo parentMemberInfo,
            int[] indices)
        {
            SerializationInfo info      = null;
            bool NeedsSerializationInfo = false;
            bool hasFixup;

            // in case of String & TimeSpan we should allways use 'ReadInternalSoapValue' method
            // in case of other internal types, we should use ReadInternalSoapValue' only if it is NOT
            // the root object, means it is a data member of another object that is being serialized.
            bool shouldReadInternal = (type == typeof(String) || type == typeof(TimeSpan));

            if (shouldReadInternal || mapper.IsInternalSoapType(type) && (indices != null || parentMemberInfo != null))
            {
                object obj = mapper.ReadInternalSoapValue(this, type);

                if (id != 0)
                {
                    RegisterObject(id, obj, info, parentId, parentMemberInfo, indices);
                }

                return(obj);
            }
            object objReturn =
                FormatterServices.GetUninitializedObject(type);

            objMgr.RaiseOnDeserializingEvent(objReturn);
            if (objReturn is ISerializable)
            {
                NeedsSerializationInfo = true;
            }

            if (_surrogateSelector != null && NeedsSerializationInfo == false)
            {
                ISurrogateSelector      selector;
                ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate(
                    type,
                    _context,
                    out selector);
                NeedsSerializationInfo |= (surrogate != null);
            }

            if (NeedsSerializationInfo)
            {
                objReturn =
                    DeserializeISerializableObject(objReturn, id, out info, out hasFixup);
            }
            else
            {
                objReturn =
                    DeserializeSimpleObject(objReturn, id, out hasFixup);
                if (!hasFixup && objReturn is IObjectReference)
                {
                    objReturn = ((IObjectReference)objReturn).GetRealObject(_context);
                }
            }

            RegisterObject(id, objReturn, info, parentId, parentMemberInfo, indices);
            xmlReader.ReadEndElement();
            return(objReturn);
        }
    public void Deserialize(IReader reader)
    {
        success = (reader.ReadByte() != 0);
        failed  = (reader.ReadByte() != 0);
        int num = reader.ReadInt32();

        for (int i = 0; i < num; i++)
        {
            string typeName = reader.ReadKleiString();
            Type   type     = Type.GetType(typeName);
            if (type != null)
            {
                ColonyAchievementRequirement colonyAchievementRequirement = (ColonyAchievementRequirement)FormatterServices.GetUninitializedObject(type);
                colonyAchievementRequirement.Deserialize(reader);
                requirements.Add(colonyAchievementRequirement);
            }
        }
    }
示例#12
0
 public static AnanOneVoice CreateInstance()
 {
     return(FormatterServices.GetUninitializedObject(typeof(AnanOneVoice)) as AnanOneVoice);
 }
        public void DoWork()
        {
            T employee = (T)FormatterServices.GetUninitializedObject(typeof(T));

            employee.Constructor("John Doe", 105);
        }
 internal static object GetUninitializedObject(this Type type)
 {
     return(FormatterServices.GetUninitializedObject(type));
 }
示例#15
0
 private static SqlException GetSqlException() =>
 (SqlException)FormatterServices.GetUninitializedObject(typeof(SqlException));
示例#16
0
        private object CreateServiceProxy(IServiceDefinition serviceDefinition, ServiceId serviceId, string[] additionalInterfaces)
        {
            Type proxyType;

            if (serviceDefinition.Implementation != null)
            {
                proxyType = _proxyTypeBuilder.Build(serviceDefinition.Implementation);
            }
            else
            {
                var interfacesTypes = new HashSet <Type>();

                if (serviceDefinition.Interfaces?.Length > 0)
                {
                    foreach (var interfaceType in serviceDefinition.Interfaces)
                    {
                        interfacesTypes.Add(interfaceType);
                    }
                }

                if (additionalInterfaces != null)
                {
                    foreach (var typeFullName in additionalInterfaces)
                    {
#warning Use better type resolver?
                        var type = Type.GetType(typeFullName, throwOnError: false);
                        if (type != null)
                        {
                            interfacesTypes.Add(type);
                        }
                    }
                }

                proxyType = _proxyTypeBuilder.Build(interfacesTypes);
            }

            var allInterfaces = proxyType
                                .GetInterfaces()
                                .Where(i => i != typeof(IProxy))
                                .Select(i => i.AssemblyQualifiedName);

            if (additionalInterfaces != null)
            {
                allInterfaces = allInterfaces.Union(additionalInterfaces).Distinct();
            }

            var serviceProxyContext = new ServiceProxyContext
            {
                Definition = serviceDefinition,

                Descriptor = new ServiceDescriptor
                {
                    Id         = serviceId,
                    Interfaces = allInterfaces.ToArray()
                }
            };

            var proxy = (IProxy)FormatterServices.GetUninitializedObject(proxyType);
            proxy.Executor = _proxyMethodExecutor;
            proxy.Context  = serviceProxyContext;
            ActivateServiceProxyInstance(proxyType, proxy);
            return(proxy);
        }
        /** <inheritdoc /> */
        public T ReadBinary <T>(BinaryReader reader, IBinaryTypeDescriptor desc, int pos, Type typeOverride)
        {
            object res;
            var    ctx = GetStreamingContext(reader);

            var type = typeOverride ?? desc.Type;

            // Read additional information from raw part, if flag is set.
            IEnumerable <string> fieldNames;
            Type customType = null;
            ICollection <int> dotNetFields = null;

            if (reader.GetCustomTypeDataFlag())
            {
                var oldPos = reader.Stream.Position;
                reader.SeekToRaw();

                fieldNames   = ReadFieldNames(reader, desc);
                customType   = ReadCustomTypeInfo(reader);
                dotNetFields = ReadDotNetFields(reader);

                // Restore stream position.
                reader.Stream.Seek(oldPos, SeekOrigin.Begin);
            }
            else
            {
                fieldNames = GetBinaryTypeFields(reader, desc);
            }

            try
            {
                if (customType != null)
                {
                    // Custom type is present, which returns original type via IObjectReference.
                    var serInfo = ReadSerializationInfo(reader, fieldNames, type, dotNetFields);

                    res = ReadAsCustomType(customType, serInfo, ctx);

                    // Handle is added after entire object is deserialized,
                    // because handles should not point to a custom type wrapper.
                    reader.AddHandle(pos, res);

                    DeserializationCallbackProcessor.Push(res);
                }
                else
                {
                    res = FormatterServices.GetUninitializedObject(type);

                    _serializableTypeDesc.OnDeserializing(res, ctx);

                    DeserializationCallbackProcessor.Push(res);

                    reader.AddHandle(pos, res);

                    // Read actual data and call constructor.
                    var serInfo = ReadSerializationInfo(reader, fieldNames, type, dotNetFields);
                    _serializableTypeDesc.SerializationCtorUninitialized(res, serInfo, ctx);
                }

                _serializableTypeDesc.OnDeserialized(res, ctx);
                DeserializationCallbackProcessor.Pop();
            }
            catch (Exception)
            {
                DeserializationCallbackProcessor.Clear();
                throw;
            }

            return((T)res);
        }
示例#18
0
 private static T CreateUninitialized <T>()
 {
     return((T)FormatterServices.GetUninitializedObject(typeof(T)));
 }
示例#19
0
        public override object ReadWithoutReference(Stream stream)
        {
            Type type = stream.ReadType();

            return(FormatterServices.GetUninitializedObject(type));
        }
示例#20
0
        /// <summary>
        /// Create a new, empty object of a given type
        /// </summary>
        /// <param name="type">The type of object to construct</param>
        /// <param name="typeRegistry">A type registry for constructing unknown types</param>
        /// <param name="initializer">An optional initializer to use to create the object</param>
        /// <param name="dimensions">For array types, the dimensions of the array to create</param>
        /// <returns></returns>
        public object CreateEmptyObject(Type type, TypeRegistry typeRegistry, Func <object> initializer, params object[] dimensions)
        {
            var objectType = type;

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

            // check the type registry for a custom type mapping
            if (typeRegistry?.ContainsType(objectType) == true)
            {
                objectType = typeRegistry.GetMapping(objectType);
            }
            // check the type registry for a custom type factory
            if (typeRegistry?.ContainsFactoryType(objectType) == true)
            {
                return(typeRegistry.GetFactory(objectType).Invoke());
            }

            var typeSupport = new ExtendedType(objectType);

            // if we are asked to create an instance of an interface, try to initialize using a valid concrete type
            if (typeSupport.IsInterface && !typeSupport.IsEnumerable)
            {
                // try a known concrete type from typeSupport
                var concreteType = typeSupport.KnownConcreteTypes.FirstOrDefault();
                if (concreteType == null)
                {
                    throw new TypeSupportException(objectType, $"Unable to locate a concrete type for '{typeSupport.Type.FullName}'! Cannot create instance.");
                }

                typeSupport = new ExtendedType(concreteType);
            }

            if (typeSupport.IsArray)
            {
                object[] createParameters = dimensions;
                // we also want to allow passing of collections/lists/arrays so do some conversion first
                if (createParameters?.Length > 0)
                {
                    var parameterType = createParameters[0].GetType();
                    if (parameterType.IsArray)
                    {
                        var ar = (Array)createParameters[0];
                        createParameters = ar.Cast <object>().ToArray();
                    }
                    else if (typeof(ICollection).IsAssignableFrom(parameterType) ||
                             typeof(IList).IsAssignableFrom(parameterType))
                    {
                        var ar = (ICollection)createParameters[0];
                        createParameters = ar.Cast <object>().ToArray();
                    }
                }
                if (createParameters != null && createParameters.Length > 1)
                {
                    createParameters.Reverse();
                }
                if (createParameters == null || createParameters.Length == 0)
                {
                    createParameters = new object[] { 0 }
                }
                ;
                return(Activator.CreateInstance(typeSupport.Type, createParameters));
            }
            else if (typeSupport.IsDictionary)
            {
                var genericType = typeSupport.Type.GetGenericArguments().ToList();
                if (genericType.Count != 2)
                {
                    throw new TypeSupportException(objectType, "IDictionary should contain 2 element types.");
                }
                Type[] typeArgs = { genericType[0], genericType[1] };

                var listType      = typeof(Dictionary <,>).MakeGenericType(typeArgs);
                var newDictionary = Activator.CreateInstance(listType) as IDictionary;
                return(newDictionary);
            }
            else if (typeSupport.IsEnumerable && !typeSupport.IsImmutable)
            {
                var genericType = typeSupport.Type.GetGenericArguments().FirstOrDefault();
                // test specifically for ICollection and List
                var isGenericCollection = typeSupport.Type.IsGenericType &&
                                          typeSupport.Type.GetGenericTypeDefinition() == typeof(ICollection <>);
                var isGenericList = typeSupport.Type.IsGenericType &&
                                    typeSupport.Type.GetGenericTypeDefinition() == typeof(List <>);
                var isGenericIList = typeSupport.Type.IsGenericType &&
                                     typeSupport.Type.GetGenericTypeDefinition() == typeof(IList <>);
                if (!isGenericList && !isGenericIList && !isGenericCollection)
                {
                    var constructors = typeSupport.Type.GetConstructors(ConstructorOptions.All);
                    if (typeSupport.HasEmptyConstructor)
                    {
                        var newList = Activator.CreateInstance(typeSupport.Type);
                        return(newList);
                    }
                    else if (typeSupport.Constructors.Any())
                    {
                        // special handling is required here as custom collections can't be properly
                        // initialized using FormatterServices.GetUninitializedObject()
                        var constructor = typeSupport.Constructors.First();
                        var parameters  = constructor.GetParameters();
                        var param       = new List <object>();
                        // initialize using defaults for constructor parameters
                        foreach (var p in parameters)
                        {
                            param.Add(CreateEmptyObject(p.ParameterType));
                        }
                        var newList = Activator.CreateInstance(typeSupport.Type, param.ToArray());
                        return(newList);
                    }
                }
                else if (genericType != null)
                {
                    var listType = typeof(List <>).MakeGenericType(genericType);
                    var newList  = (IList)Activator.CreateInstance(listType);
                    return(newList);
                }
                return(Enumerable.Empty <object>());
            }
            else if (typeSupport.Type.ContainsGenericParameters)
            {
                // create a generic type and create an instance
                // to accomplish this, we need to create a new generic type using the type arguments from the interface
                // and the concrete class definition. voodoo!
                var    originalTypeSupport = new ExtendedType(objectType);
                var    genericArguments    = originalTypeSupport.Type.GetGenericArguments();
                var    newType             = typeSupport.Type.MakeGenericType(genericArguments);
                object newObject           = null;
                if (typeSupport.HasEmptyConstructor)
                {
                    newObject = Activator.CreateInstance(newType);
                }
                else
                {
                    newObject = FormatterServices.GetUninitializedObject(newType);
                }
                return(newObject);
            }
            else if (typeSupport.HasEmptyConstructor && !typeSupport.Type.ContainsGenericParameters)
            {
                return(Activator.CreateInstance(typeSupport.Type));
            }
            else if (typeSupport.IsImmutable)
            {
                return(null);
            }

            return(FormatterServices.GetUninitializedObject(typeSupport.Type));
        }
    }
        private object Unpack(MsgPackReader reader, Type t)
        {
            //IL_0591: Unknown result type (might be due to invalid IL or missing references)
            //IL_0596: Expected O, but got Unknown
            if (t.IsPrimitive)
            {
                if (!reader.Read())
                {
                    throw new FormatException();
                }
                if (t.Equals(typeof(int)) && reader.IsSigned())
                {
                    return(reader.ValueSigned);
                }
                if (t.Equals(typeof(int)) && reader.IsUnsigned())
                {
                    return((int)reader.ValueUnsigned);
                }
                if (t.Equals(typeof(uint)) && reader.IsUnsigned())
                {
                    return(reader.ValueUnsigned);
                }
                if (t.Equals(typeof(float)))
                {
                    if (reader.Type == TypePrefixes.Float)
                    {
                        return(reader.ValueFloat);
                    }
                    if (reader.Type == TypePrefixes.Double)
                    {
                        return((float)reader.ValueDouble);
                    }
                    if (reader.IsUnsigned())
                    {
                        return((float)(double)reader.ValueUnsigned);
                    }
                    if (reader.IsSigned())
                    {
                        return((float)reader.ValueSigned);
                    }
                }
                else
                {
                    if (t.Equals(typeof(double)) && reader.Type == TypePrefixes.Double)
                    {
                        return(reader.ValueDouble);
                    }
                    if (t.Equals(typeof(long)))
                    {
                        if (reader.IsSigned64())
                        {
                            return(reader.ValueSigned64);
                        }
                        if (reader.IsSigned())
                        {
                            return((long)reader.ValueSigned);
                        }
                        if (reader.IsUnsigned64())
                        {
                            return((long)reader.ValueUnsigned64);
                        }
                        if (reader.IsUnsigned())
                        {
                            return((long)reader.ValueUnsigned);
                        }
                    }
                    else
                    {
                        if (!t.Equals(typeof(ulong)))
                        {
                            if (t.Equals(typeof(bool)) && reader.IsBoolean())
                            {
                                return(reader.Type == TypePrefixes.True);
                            }
                            if (t.Equals(typeof(byte)) && reader.IsUnsigned())
                            {
                                return((byte)reader.ValueUnsigned);
                            }
                            if (t.Equals(typeof(sbyte)) && reader.IsSigned())
                            {
                                return((sbyte)reader.ValueSigned);
                            }
                            if (t.Equals(typeof(short)) && reader.IsSigned())
                            {
                                return((short)reader.ValueSigned);
                            }
                            if (t.Equals(typeof(ushort)) && reader.IsUnsigned())
                            {
                                return((ushort)reader.ValueUnsigned);
                            }
                            if (t.Equals(typeof(char)) && reader.IsUnsigned())
                            {
                                return((char)reader.ValueUnsigned);
                            }
                            throw new NotSupportedException();
                        }
                        if (reader.IsUnsigned64())
                        {
                            return(reader.ValueUnsigned64);
                        }
                        if (reader.IsUnsigned())
                        {
                            return((ulong)reader.ValueUnsigned);
                        }
                    }
                }
            }
            if (UnpackerMapping.TryGetValue(t, out UnpackDelegate value))
            {
                return(value(this, reader));
            }
            if (t.IsArray)
            {
                if (!reader.Read() || (!reader.IsArray() && reader.Type != TypePrefixes.Nil))
                {
                    throw new FormatException();
                }
                if (reader.Type == TypePrefixes.Nil)
                {
                    return(null);
                }
                Type  elementType = t.GetElementType();
                Array array       = Array.CreateInstance(elementType, (int)reader.Length);
                for (int i = 0; i < array.Length; i++)
                {
                    array.SetValue(Unpack(reader, elementType), i);
                }
                return(array);
            }
            if (t.IsEnum)
            {
                if (!reader.Read())
                {
                    throw new FormatException();
                }
                if (reader.IsSigned())
                {
                    return(Enum.ToObject(t, reader.ValueSigned));
                }
                if (reader.IsSigned64())
                {
                    return(Enum.ToObject(t, reader.ValueSigned64));
                }
                if (reader.IsUnsigned())
                {
                    return(Enum.ToObject(t, reader.ValueUnsigned));
                }
                if (reader.IsUnsigned64())
                {
                    return(Enum.ToObject(t, reader.ValueUnsigned64));
                }
                if (reader.IsRaw())
                {
                    CheckBufferSize((int)reader.Length);
                    reader.ReadValueRaw(_buf, 0, (int)reader.Length);
                    string @string = Encoding.UTF8.GetString(_buf, 0, (int)reader.Length);
                    return(Enum.Parse(t, @string));
                }
                throw new FormatException();
            }
            if (!reader.Read())
            {
                throw new FormatException();
            }
            if (reader.Type == TypePrefixes.Nil)
            {
                return(null);
            }
            if (t.IsInterface)
            {
                if (reader.Type != TypePrefixes.FixArray && reader.Length != 2)
                {
                    throw new FormatException();
                }
                if (!reader.Read() || !reader.IsRaw())
                {
                    throw new FormatException();
                }
                CheckBufferSize((int)reader.Length);
                reader.ReadValueRaw(_buf, 0, (int)reader.Length);
                t = Type.GetType(Encoding.UTF8.GetString(_buf, 0, (int)reader.Length));
                if (!reader.Read() || reader.Type == TypePrefixes.Nil)
                {
                    throw new FormatException();
                }
            }
            if (!reader.IsMap())
            {
                throw new FormatException();
            }
            object obj = (!typeof(ScriptableObject).IsAssignableFrom(t)) ? FormatterServices.GetUninitializedObject(t) : ((object)ScriptableObject.CreateInstance(t));
            ReflectionCacheEntry reflectionCacheEntry = ReflectionCache.Lookup(t);
            int length = (int)reader.Length;

            for (int j = 0; j < length; j++)
            {
                if (!reader.Read() || !reader.IsRaw())
                {
                    throw new FormatException();
                }
                CheckBufferSize((int)reader.Length);
                reader.ReadValueRaw(_buf, 0, (int)reader.Length);
                string string2 = Encoding.UTF8.GetString(_buf, 0, (int)reader.Length);
                if (!reflectionCacheEntry.FieldMap.TryGetValue(string2, out FieldInfo value2))
                {
                    new BoxingPacker().Unpack(reader);
                }
                else
                {
                    value2.SetValue(obj, Unpack(reader, value2.FieldType));
                }
            }
            (obj as IDeserializationCallback)?.OnDeserialization(this);
            return(obj);
        }
示例#22
0
        public async Task Invoke(SocketUserMessage msg)
        {
            var commandTypes = _commandCache.GetTypes();
            var commands     = new List <ICommand>();

            foreach (var cmdType in commandTypes)
            {
                var cmd = (ICommand)FormatterServices.GetUninitializedObject(cmdType);
                commands.Add(cmd);
            }

            var customCommands = await _customCommandRepository.Get().Where(x => x.GuildId == _msgContext.Guild.Id).ToListAsync();

            var args = msg.Content.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries);


            if (args.Length > 1)
            {
                var cmdArg      = args[1].Trim().ToLower();
                var selectedCmd = commands.SingleOrDefault(x =>
                                                           x.Name.ToLower() == cmdArg || x.Aliases.Any(y => y.ToLower() == cmdArg));

                if (selectedCmd == null)
                {
                    var customCmd = await _customCommandRepository.Get()
                                    .SingleOrDefaultAsync(x => x.GuildId == _msgContext.Guild.Id);

                    if (customCmd == null)
                    {
                        await msg.Channel.SendMessageAsync("I don't know that command");

                        return;
                    }

                    await msg.Channel.SendMessageAsync("Responds with a text string");
                }

                else if (!selectedCmd.Public)
                {
                    if (await _roleService.UserIsAdmin(msg))
                    {
                        await msg.Channel.SendMessageAsync(selectedCmd.Help);
                    }
                }
                else
                {
                    await msg.Channel.SendMessageAsync(selectedCmd.Help);
                }
            }
            else
            {
                var help = "Available commands:";

                if (await _roleService.UserIsAdmin(msg))
                {
                    foreach (var command in commands)
                    {
                        help += "\n";
                        help += FormatHelpCommand(command);
                    }
                }
                else
                {
                    var cmds = commands.Where(x => x.Public).ToList();

                    foreach (var command in cmds)
                    {
                        help += "\n";
                        help += FormatHelpCommand(command);
                    }
                }

                foreach (var customCommand in customCommands)
                {
                    help += "\n";
                    help += _prefix + customCommand.Name;
                }

                help += "\n";
                help += "Type !help <command> for more.";
                await msg.Channel.SendMessageAsync(help);
            }
        }
示例#23
0
 public static T UninitializedObject <T>()
 {
     return((T)FormatterServices.GetUninitializedObject(typeof(T)));
 }
示例#24
0
 // Exposed here as a more appropriate place than on FormatterServices itself,
 // which is a high level reflection heavy type.
 public static Object GetUninitializedObject(Type type)
 {
     return(FormatterServices.GetUninitializedObject(type));
 }