ReadDecimal() public method

public ReadDecimal ( ) : decimal
return decimal
 public override object Read(BinaryReader buffer, Type resultType, TypeDescription typeDescriptor, byte code, BinaryJSONReader binaryJsonReader)
 {
     switch (code)
     {
         case BinaryValue.BYTE:
             return Convert.ChangeType(buffer.ReadByte(), resultType);
         case BinaryValue.SBYTE:
             return Convert.ChangeType(buffer.ReadSByte(), resultType);
         case BinaryValue.INT16:
             return Convert.ChangeType(buffer.ReadInt16(), resultType);
         case BinaryValue.UINT16:
             return Convert.ChangeType(buffer.ReadUInt16(), resultType);
         case BinaryValue.INT32:
             return Convert.ChangeType(buffer.ReadInt32(), resultType);
         case BinaryValue.UINT32:
             return Convert.ChangeType(buffer.ReadUInt32(), resultType);
         case BinaryValue.INT64:
             return Convert.ChangeType(buffer.ReadInt64(), resultType);
         case BinaryValue.UINT64:
             return Convert.ChangeType(buffer.ReadUInt64(), resultType);
         case BinaryValue.FLOAT:
             return Convert.ChangeType(buffer.ReadSingle(), resultType);
         case BinaryValue.BOOLEAN:
             return Convert.ChangeType(buffer.ReadBoolean(), resultType);
         case BinaryValue.DOUBLE:
             return Convert.ChangeType(buffer.ReadDouble(), resultType);
         case BinaryValue.DECIMAL:
             return Convert.ChangeType(buffer.ReadDecimal(), resultType);
         case BinaryValue.CHAR:
             return Convert.ChangeType(buffer.ReadChar(), resultType);
     }
     return null;
 }
Example #2
0
        private static bool Load(BinaryReader reader, out Value value)
        {
            List<KeyValuePair<Value, Value>>	array;
            Value								arrayKey;
            Value								arrayValue;
            int									count;
            ValueContent						type;

            type = (ValueContent)reader.ReadInt32 ();

            switch (type)
            {
                case ValueContent.Boolean:
                    value = reader.ReadBoolean () ? BooleanValue.True : BooleanValue.False;

                    break;

                case ValueContent.Map:
                    count = reader.ReadInt32 ();
                    array = new List<KeyValuePair<Value, Value>> (count);

                    while (count-- > 0)
                    {
                        if (!ValueAccessor.Load (reader, out arrayKey) || !ValueAccessor.Load (reader, out arrayValue))
                        {
                            value = null;

                            return false;
                        }

                        array.Add (new KeyValuePair<Value, Value> (arrayKey, arrayValue));
                    }

                    value = array;

                    break;

                case ValueContent.Number:
                    value = reader.ReadDecimal ();

                    break;

                case ValueContent.String:
                    value = reader.ReadString ();

                    break;

                case ValueContent.Void:
                    value = VoidValue.Instance;

                    break;

                default:
                    value = null;

                    return false;
            }

            return true;
        }
        public static void Main(string[] args)
        {
            BinaryFile classObject = new BinaryFile();
            try
            {
                using (BinaryWriter writerObject = new BinaryWriter(File.Open("file.bin", FileMode.OpenOrCreate)))
                {
                    writerObject.Write(classObject._number);
                    writerObject.Write(classObject._sentence);
                    writerObject.Write(classObject._decimalNumber);
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e);
            }

            try
            {

                using (BinaryReader readerObject = new BinaryReader(File.Open("file.bin", FileMode.OpenOrCreate)))
                {
                    Console.WriteLine(readerObject.ReadInt32());
                    Console.WriteLine(readerObject.ReadString());
                    Console.WriteLine(readerObject.ReadDecimal());

                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e);
            }

            Console.ReadKey();
        }
        private static string FormatAs(byte[] bytes, params string[] types)
        {
            var formatted = new List<string>();

            using (var reader = new BinaryReader(new MemoryStream(bytes)))
            {
                foreach (var type in types)
                {
                    switch (type.ToLower())
                    {
                        case "int32":
                            formatted.Add(reader.ReadInt32().ToString("0000000000"));
                            break;
                        case "single":
                            formatted.Add(reader.ReadSingle().ToString());
                            break;
                        case "double":
                            formatted.Add(reader.ReadDouble().ToString());
                            break;
                        case "decimal":
                            formatted.Add(reader.ReadDecimal().ToString());
                            break;
                        default:
                            throw new Exception();
                    }
                }
            }

            return String.Join(" ", formatted);
        }
        private static object ReadPrimitive(BinaryReader reader, Type type)
        {
            if (type == typeof (byte))
                return reader.ReadByte();
            if (type == typeof (float))
                return reader.ReadSingle();
            if (type == typeof (double))
                return reader.ReadDouble();
            if (type == typeof (decimal))
                return reader.ReadDecimal();
            if (type == typeof (int))
                return reader.ReadInt32();
            if (type == typeof (uint))
                return reader.ReadUInt32();
            if (type == typeof (short))
                return reader.ReadInt16();
            if (type == typeof (ushort))
                return reader.ReadUInt16();
            if (type == typeof (long))
                return reader.ReadInt64();
            if (type == typeof (ulong))
                return reader.ReadUInt64();
            if (type == typeof (bool))
                return reader.ReadBoolean();
            if (type == typeof (string))
                return reader.ReadString();
            if (type == typeof (char))
                return reader.ReadChar();
            if (type == typeof (Guid))
                return new Guid(reader.ReadBytes(16));
            if (type == typeof (DateTime))
                return new DateTime(reader.ReadInt64());

            throw new ArgumentException($"Failed to read '{type.FullName}', type not supported", nameof(type));
        }
Example #6
0
        private void ValidateDisposedExceptions(BinaryReader binaryReader)
        {
            byte[] byteBuffer = new byte[10];
            char[] charBuffer = new char[10];

            Assert.Throws<ObjectDisposedException>(() => binaryReader.PeekChar());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.Read());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(byteBuffer, 0, 1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.Read(charBuffer, 0, 1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadBoolean());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadByte());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadBytes(1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadChar());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadChars(1));
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadDecimal());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadDouble());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadInt16());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadInt32());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadInt64());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadSByte());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadSingle());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadString());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadUInt16());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadUInt32());
            Assert.Throws<ObjectDisposedException>(() => binaryReader.ReadUInt64());
        }
Example #7
0
		public static List<Product> GetProducts()
		{
			// if the directory doesn't exist, create it
			if (!Directory.Exists(dir))
				Directory.CreateDirectory(dir);

			// create the object for the input stream for a binary file
			BinaryReader binaryIn = 
				new BinaryReader(
				new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

			// create the array list
			List<Product> products = new List<Product>();

			// read the data from the file and store it in the List<Product>
			while (binaryIn.PeekChar() != -1)
			{
				Product product = new Product();
				product.Code = binaryIn.ReadString();
				product.Description = binaryIn.ReadString();
				product.Price = binaryIn.ReadDecimal();
				products.Add(product);
			}

			// close the input stream for the binary file
			binaryIn.Close();

			return products;
		}
 protected virtual Decimal DeserializeDecimal(ArraySegment<byte> value)
 {
     using (var stream = new MemoryStream(value.Array, value.Offset, value.Count)) {
           using (var binaryReader = new BinaryReader(stream)) {
               return binaryReader.ReadDecimal();
           }
       }
 }
        // very manual writer... but want to see how small I can get the data.
        public static CompleteSignature ReadBinaryCompleteSignature(Stream s)
        {
            var sig = new CompleteSignature();

            var l = new List<BlockSignature>();

            var reader = new BinaryReader(s);

            int numberOfEntries = reader.ReadInt32();

            for (var i = 0; i < numberOfEntries; i++)
            {
                var entry = new BlockSignature();

                // 8 bytes. offset
                long offset = reader.ReadInt64();

                // 4 bytes. size
                int size = reader.ReadInt32();

                // 4 bytes. Block Number;
                int blockNumber = reader.ReadInt32();

                // 4 bytes. Rolling Signature.
                decimal sig1 = reader.ReadDecimal();
                decimal sig2 = reader.ReadDecimal();
                RollingSignature rollingSig = new RollingSignature() { Sig1 = sig1, Sig2 = sig2 };

                // should be 16 bytes.
                byte[] md5 = reader.ReadBytes(16);

                entry.BlockNumber = (UInt32)blockNumber;
                entry.RollingSig = (RollingSignature)rollingSig;
                entry.MD5Signature = md5;
                entry.Offset = offset;
                entry.Size = (uint)size;

                l.Add(entry);
            }
            sig.SignatureList = l.ToArray<BlockSignature>();
            return sig;
        }
        public static decimal GetDecimalValue(this DatasourceRecord record)
        {
            ThrowExceptionOnInvalidConversion(record.DataType, DatasourceRecord.DataTypeEnum.Decimal);

            using (var memoryStream = new MemoryStream(record.Value))
            {
                using (var binaryReader = new BinaryReader(memoryStream))
                {
                    return binaryReader.ReadDecimal();
                }
            }
        }
 public static decimal BytesToDecimal(byte[] buffer)
 {
     //if (buffer.Length == 1) return Decimal.Parse(((char)buffer[0]).ToString());
     if (buffer.Length == 2) {
         if (buffer[1] == 1) return decimal.MinValue;
         else return decimal.MaxValue;
     }
     using (var ms = new MemoryStream(buffer)) {
         using (var br = new BinaryReader(ms)) {
             return br.ReadDecimal(); ;
         }
     }
 }
Example #12
0
        public static void RetrieveAndDisplayData(BinaryReader binReader)
        {
            // Read string data from the file
            Console.WriteLine(binReader.ReadString());

            // Read integer data from the file
            for (int i = 0; i < 11; i++)
            {
                Console.WriteLine(binReader.ReadInt32());
            }

            // Read decimal data from the file
            Console.WriteLine(binReader.ReadDecimal());
        }
Example #13
0
        /// <summary>
        /// Byte array to Decimal
        /// </summary>
        /// <param name="src">byte array</param>
        /// <returns>decimal</returns>
        public static Decimal BytesToDecimal(byte[] src)
        {
            if (src.Length == 1)
            {
                return Decimal.Parse(((char)src[0]).ToString());
            }

            using (System.IO.MemoryStream stream = new System.IO.MemoryStream(src))
            {
                using (System.IO.BinaryReader reader = new System.IO.BinaryReader(stream))
                {
                    return reader.ReadDecimal();
                }

            }
        }
Example #14
0
        public void WriteDecimal()
        {
            MemoryStream stream = new MemoryStream();
            OutputChannel channel = new OutputChannel(new BinaryWriter(stream));

            decimal dc = 12.34m;

            channel.Write(dc);

            stream.Seek(0, SeekOrigin.Begin);

            BinaryReader reader = new BinaryReader(stream);

            Assert.AreEqual((byte)Types.Decimal, reader.ReadByte());
            Assert.AreEqual(dc, reader.ReadDecimal());
            Assert.AreEqual(-1, reader.PeekChar());

            reader.Close();
        }
Example #15
0
 public static decimal ByteArrayToDecimal(byte[] src)
 {
     decimal num3;
     if (src.Length < 0x10)
     {
         byte[] buffer = new byte[0x10];
         int num = 0;
         foreach (byte num2 in src)
         {
             buffer[num++] = num2;
         }
         src = buffer;
     }
     using (MemoryStream stream = new MemoryStream(src))
     {
         using (BinaryReader reader = new BinaryReader(stream))
         {
             num3 = reader.ReadDecimal();
         }
     }
     return num3;
 }
Example #16
0
        public void CreateEachDataType()
        {
            var idx = ObjectIndex.Create("Index_Name1", 5);
            Assert.AreEqual("Index_Name1", idx.Name);
            Assert.AreEqual(5, idx.GetObjectValue());
            Assert.AreEqual(ObjectIndexType.Integer, idx.DataType);
            Assert.AreEqual(5, BitConverter.ToInt32(idx.Value, 0));

            idx = ObjectIndex.Create("Index_Name1", "test val");
            Assert.AreEqual("Index_Name1", idx.Name);
            Assert.AreEqual("test val", idx.GetObjectValue());
            Assert.AreEqual(ObjectIndexType.String, idx.DataType);
            Assert.AreEqual("test val", Encoding.UTF8.GetString(idx.Value));

            idx = ObjectIndex.Create("Index_Name1", new Decimal(5));
            Assert.AreEqual("Index_Name1", idx.Name);
            Assert.AreEqual(new Decimal(5), idx.GetObjectValue());
            Assert.AreEqual(ObjectIndexType.Decimal, idx.DataType);
            var reader = new BinaryReader(new MemoryStream(idx.Value));
            Assert.AreEqual(new Decimal(5), reader.ReadDecimal());

            var binValue = Encoding.UTF8.GetBytes("test bin");
            idx = ObjectIndex.Create("Index_Name1", binValue);
            Assert.AreEqual("Index_Name1", idx.Name);
            Assert.AreEqual(binValue, idx.GetObjectValue());
            Assert.AreEqual(ObjectIndexType.Binary, idx.DataType);
            Assert.AreEqual(binValue, idx.Value);

            var dtVal = DateTime.Now;
            var val = dtVal.ToBinary();
            idx = ObjectIndex.Create("Index_Name1", dtVal);
            Assert.AreEqual("Index_Name1", idx.Name);
            Assert.AreEqual(dtVal, idx.GetObjectValue());
            Assert.AreEqual(ObjectIndexType.DateTime, idx.DataType);
            Assert.AreEqual(dtVal, DateTime.FromBinary(BitConverter.ToInt64(idx.Value, 0)));
        }
Example #17
0
		internal object ReadData(BinaryReader br)
		{
			const string FuncErrCode=ClassErrCode+".0006";
			try
			{
				Field f = this;
				switch(f.type)
				{
					case FieldType.ftBoolean:
						return br.ReadBoolean();
					case FieldType.ftDecimal:
						return br.ReadDecimal();
					case FieldType.ftDateTime:
						return new DateTime(br.ReadInt64());
					case FieldType.ftInt32:
						return br.ReadInt32();
					case FieldType.ftInt64:
						return br.ReadInt64();
					case FieldType.ftString: //long total = 2*len+8 bytes
						long p = br.BaseStream.Position;
						byte[] bytes = new byte[br.ReadInt32()];
						bytes=br.ReadBytes(bytes.Length);
						string str =System.Text.Encoding.Unicode.GetString(bytes);
						br.BaseStream.Position = p+DataSize();
						return str;
					default:
						return null;
				}
			}
			catch(Exception ex)
			{
				throw new Exception(ex.Message+"\n"+FuncErrCode+": Inner exception.");
			}
		}
Example #18
0
		internal static object Deserialize (BinaryReader r)
		{
			TypeCode typeCode = (TypeCode)r.ReadByte();
			switch (typeCode) {
			case TypeCode.Boolean:
				return r.ReadBoolean ();
			case TypeCode.Byte:
				return r.ReadByte ();
			case TypeCode.Char:
				return r.ReadChar ();
			case TypeCode.DateTime:
				return new DateTime (r.ReadInt64 ());
			case TypeCode.DBNull:
				return DBNull.Value;
			case TypeCode.Decimal:
				return r.ReadDecimal ();
			case TypeCode.Double:
				return r.ReadDouble ();
			case TypeCode.Empty:
				return null;
			case TypeCode.Int16:
				return r.ReadInt16 ();
			case TypeCode.Int32:
				return r.ReadInt32 ();
			case TypeCode.Int64:
				return r.ReadInt64 ();
			case TypeCode.Object:
				BinaryFormatter bf = new BinaryFormatter ();
				return bf.Deserialize (r.BaseStream);
			case TypeCode.SByte:
				return r.ReadSByte ();
			case TypeCode.Single:
				return r.ReadSingle ();
			case TypeCode.String:
				return r.ReadString ();
			case TypeCode.UInt16:
				return r.ReadUInt16 ();
			case TypeCode.UInt32:
				return r.ReadUInt32 ();
			case TypeCode.UInt64:
				return r.ReadUInt64 ();
			default:
				throw new ArgumentOutOfRangeException ("TypeCode:" + typeCode);
			}
		}
Example #19
0
		object DeserializeObject (BinaryReader reader)
		{
			TypeId tid = (TypeId)reader.ReadByte ();

			if (tid == TypeId.NULL)
				return null;

			if (tid == TypeId.String) {
				return reader.ReadString ();
			}
			
			if (tid == TypeId.Int32) {
				return reader.ReadInt32 ();
			}
			
			if (tid == TypeId.Int64) {
				return reader.ReadInt64 ();
			}
			
			if (tid == TypeId.UInt32) {
				return reader.ReadUInt32 ();
			}
			
			if (tid == TypeId.UInt64) {
				return reader.ReadUInt64 ();
			}
			
			if (tid == TypeId.Boolean) {
				return reader.ReadBoolean ();
			}
			
			if (tid == TypeId.Byte) {
				return reader.ReadByte ();
			}
			
			if (tid == TypeId.SByte) {
				return reader.ReadSByte ();
			}
			
			if (tid == TypeId.Char) {
				return reader.ReadChar ();
			}
			
			if (tid == TypeId.Double) {
				return reader.ReadDouble ();
			}
			
			if (tid == TypeId.Single) {
				return reader.ReadSingle ();
			}
			
			if (tid == TypeId.Byte) {
				return reader.ReadByte ();
			}
			
			if (tid == TypeId.Int16) {
				return reader.ReadInt16 ();
			}
			
			if (tid == TypeId.UInt16) {
				return reader.ReadUInt16 ();
			}
			
			if (tid == TypeId.Decimal) {
				return reader.ReadDecimal ();
			}
			
			throw new NotSupportedException (); 
		}
Example #20
0
        /// <summary>
        /// Read column data from file.
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        internal static object[] ReadData(BinaryReader reader, int length)
        {
            object[] data = new object[length];

            for (int i = 0; i < length; i++)
            {
                #if !POCKETPC
                ColumnType type = (ColumnType)Enum.Parse( typeof(ColumnType), reader.ReadInt32().ToString() );
                #else
                ColumnType type = (ColumnType)OpenNETCF.EnumEx.Parse( typeof(ColumnType), reader.ReadInt32().ToString() );
                #endif
                object o = null;
                switch (type)
                {
                    case ColumnType.Null:
                        o = null;
                        break;

                    case ColumnType.Float:
                    case ColumnType.Real:
                        o = reader.ReadSingle();
                        break;

                    case ColumnType.DbDouble:
                        o = reader.ReadDouble();
                        break;

                    case ColumnType.VarCharIgnoreCase:
                    case ColumnType.VarChar:
                    case ColumnType.Char:
                    case ColumnType.LongVarChar:
                        o = reader.ReadString();
                        break;

                    case ColumnType.Date:
                    case ColumnType.Time:
                    case ColumnType.Timestamp:
                        o = new DateTime( reader.ReadInt64() );
                        break;

                    case ColumnType.Numeric:
                    case ColumnType.DbDecimal:
                        #if !POCKETPC
                        o = reader.ReadDecimal();
                        #else
                        int l = reader.ReadInt32();
                        byte[] bytes = reader.ReadBytes(l);
                        int[] bits = new int[bytes.Length/4];
                        for(int ix=0;ix<bits.Length;ix++)
                        {
                            bits[ix] = BitConverter.ToInt32(bytes, ix*4);
                        }
                        o = new Decimal( bits );
                        #endif
                        break;

                    case ColumnType.Bit:
                        o = reader.ReadBoolean();
                        break;

                    case ColumnType.TinyInt:
                        o = reader.ReadByte();
                        break;

                    case ColumnType.SmallInt:
                        o = reader.ReadInt16();
                        break;

                    case ColumnType.Integer:
                        o = reader.ReadInt32();
                        break;

                    case ColumnType.BigInt:
                        o = reader.ReadInt64();
                        break;

                    case ColumnType.Binary:
                    case ColumnType.VarBinary:
                    case ColumnType.LongVarBinary:
                        int len = reader.ReadInt32();
                        o = reader.ReadBytes(len);
                        break;

                    case ColumnType.Other:
                        int other = reader.ReadInt32();
                        o = ByteArray.Deserialize(reader.ReadBytes(other));
                        break;

                    case ColumnType.UniqueIdentifier:
                        o = new Guid(reader.ReadString());
                        break;

                    default:
                        throw TracingHelper.Error(TracingHelper.WRONG_DATA_TYPE, (int)type);
                }

                data[i] = o;
            }

            return data;
        }
        private object ConvertToObject(byte[] data, string resourceType)
        {
            MemoryStream dataStream = new MemoryStream(data);
            BinaryReader reader = new BinaryReader(dataStream);

            if (resourceType.Equals("ResourceTypeCode.Null"))
                return null;
            else if (resourceType.Equals("ResourceTypeCode.String"))
                return reader.ReadString();
            else if (resourceType.Equals("ResourceTypeCode.Boolean"))
                return reader.ReadBoolean();
            else if (resourceType.Equals("ResourceTypeCode.Char"))
                return (char) reader.ReadUInt16();
            else if (resourceType.Equals("ResourceTypeCode.Byte"))
                return reader.ReadByte();
            else if (resourceType.Equals("ResourceTypeCode.SByte"))
                return reader.ReadSByte();
            else if (resourceType.Equals("ResourceTypeCode.Int16"))
                return reader.ReadInt16();
            else if (resourceType.Equals("ResourceTypeCode.UInt16"))
                return reader.ReadUInt16();
            else if (resourceType.Equals("ResourceTypeCode.Int32"))
                return reader.ReadInt32();
            else if (resourceType.Equals("ResourceTypeCode.UInt32"))
                return reader.ReadUInt32();
            else if (resourceType.Equals("ResourceTypeCode.Int64"))
                return reader.ReadInt64();
            else if (resourceType.Equals("ResourceTypeCode.UInt64"))
                return reader.ReadUInt64();
            else if (resourceType.Equals("ResourceTypeCode.Single"))
                return reader.ReadSingle();
            else if (resourceType.Equals("ResourceTypeCode.Double"))
                return reader.ReadDouble();
            else if (resourceType.Equals("ResourceTypeCode.Decimal"))
                return reader.ReadDecimal();
            else if (resourceType.Equals("ResourceTypeCode.DateTime"))
            {
                // Use DateTime's ToBinary & FromBinary.
                Int64 dateData = reader.ReadInt64();
                return DateTime.FromBinary(dateData);
            }
            else if (resourceType.Equals("ResourceTypeCode.TimeSpan"))
            {
                Int64 ticks = reader.ReadInt64();
                return new TimeSpan(ticks);
            }
            // Special types
            else if (resourceType.Equals("ResourceTypeCode.ByteArray"))
            {
                int len = reader.ReadInt32();
                return reader.ReadBytes(len);
            }
            else if (resourceType.Equals("ResourceTypeCode.Stream"))
            {
                int len = reader.ReadInt32();
                return new MemoryStream(reader.ReadBytes(len));
            }
            else
            {
                // weitere Klassen
                BinaryFormatter bf = new BinaryFormatter();
                return bf.Deserialize(dataStream);
            }
        }
Example #22
0
		/// <summary>
		/// Reads a definition to disk
		/// </summary>
		/// <param name="br"></param>
		/// <returns></returns>
		internal static Variant ReadFromFieldDef(BinaryReader br)
		{
			Variant v= new Variant();
			const string FuncErrCode=ClassErrCode+".0002";
			try{
				//BinaryReader br = new BinaryReader(_br.BaseStream,System.Text.Encoding.Unicode);
				v.type=(FieldType)br.ReadInt32();
				switch(v.type)
				{
					case FieldType.ftBoolean:
						v.obj=br.ReadBoolean();
						break;
					case FieldType.ftDecimal:
						v.obj=br.ReadDecimal();
						break;
					case FieldType.ftDateTime:
						v.obj=new DateTime(br.ReadInt64());
						break;
					case FieldType.ftInt32:
						v.obj=br.ReadInt32();
						break;
					case FieldType.ftInt64:
						v.obj=br.ReadInt64();
						break;
					case FieldType.ftString: 
						v.obj=br.ReadString();
						break;
					default:
						throw new Exception(FuncErrCode+": Field type not recognized");
				}
				return v;
			}
			catch(Exception ex)
			{
				throw new Exception(ex.Message+"\n"+FuncErrCode+": Inner exception.");
			}
		}
Example #23
0
		private void ReadArrayOfPrimitiveType (BinaryReader reader, out long objectId, out object val)
		{
			objectId = (long) reader.ReadUInt32 ();
			int length = reader.ReadInt32 ();
			Type elementType = ReadType (reader, TypeTag.PrimitiveType);

			switch (Type.GetTypeCode (elementType))
			{
				case TypeCode.Boolean: {
					bool[] arr = new bool [length];
					for (int n = 0; n < length; n++) arr [n] = reader.ReadBoolean();
					val = arr;
					break;
				}

				case TypeCode.Byte: {
					byte[] arr = new byte [length];
					int pos = 0;
					while (pos < length) {
						int nr = reader.Read (arr, pos, length - pos);
						if (nr == 0) break;
						pos += nr;
					}
					val = arr;
					break;
				}

				case TypeCode.Char: {
					char[] arr = new char [length];
					int pos = 0;
					while (pos < length) {
						int nr = reader.Read (arr, pos, length - pos);
						if (nr == 0) break;
						pos += nr;
					}
					val = arr;
					break;
				}

				case TypeCode.DateTime: {
					DateTime[] arr = new DateTime [length];
					for (int n = 0; n < length; n++) {
						arr [n] = DateTime.FromBinary (reader.ReadInt64 ());
					}
					val = arr;
					break;
				}

				case TypeCode.Decimal: {
					Decimal[] arr = new Decimal [length];
					for (int n = 0; n < length; n++) arr [n] = reader.ReadDecimal();
					val = arr;
					break;
				}

				case TypeCode.Double: {
					Double[] arr = new Double [length];
					if (length > 2)
						BlockRead (reader, arr, 8);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadDouble();
					val = arr;
					break;
				}

				case TypeCode.Int16: {
					short[] arr = new short [length];
					if (length > 2)
						BlockRead (reader, arr, 2);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadInt16();
					val = arr;
					break;
				}

				case TypeCode.Int32: {
					int[] arr = new int [length];
					if (length > 2)
						BlockRead (reader, arr, 4);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadInt32();
					val = arr;
					break;
				}

				case TypeCode.Int64: {
					long[] arr = new long [length];
					if (length > 2)
						BlockRead (reader, arr, 8);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadInt64();
					val = arr;
					break;
				}

				case TypeCode.SByte: {
					sbyte[] arr = new sbyte [length];
					if (length > 2)
						BlockRead (reader, arr, 1);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadSByte();
					val = arr;
					break;
				}

				case TypeCode.Single: {
					float[] arr = new float [length];
					if (length > 2)
						BlockRead (reader, arr, 4);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadSingle();
					val = arr;
					break;
				}

				case TypeCode.UInt16: {
					ushort[] arr = new ushort [length];
					if (length > 2)
						BlockRead (reader, arr, 2);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt16();
					val = arr;
					break;
				}

				case TypeCode.UInt32: {
					uint[] arr = new uint [length];
					if (length > 2)
						BlockRead (reader, arr, 4);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt32();
					val = arr;
					break;
				}

				case TypeCode.UInt64: {
					ulong[] arr = new ulong [length];
					if (length > 2)
						BlockRead (reader, arr, 8);
					else
						for (int n = 0; n < length; n++) arr [n] = reader.ReadUInt64();
					val = arr;
					break;
				}

				case TypeCode.String: {
					string[] arr = new string [length];
					for (int n = 0; n < length; n++) arr [n] = reader.ReadString();
					val = arr;
					break;
				}

				default: {
					if (elementType == typeof(TimeSpan)) {
						TimeSpan[] arr = new TimeSpan [length];
						for (int n = 0; n < length; n++) arr [n] = new TimeSpan (reader.ReadInt64 ());
						val = arr;
					}
					else
						throw new NotSupportedException ("Unsupported primitive type: " + elementType.FullName);
					break;
				}
			}			
		}
        public object[] ReceiveParameters(BinaryReader reader)
        {
            int parameterCount = reader.ReadInt32();
            object[] parameters = new object[parameterCount];
            for (int i = 0; i < parameterCount; i++)
            {
                //read type byte
                byte typeByte = reader.ReadByte();
                if (typeByte == ParameterTypes.Null)
                    parameters[i] = null;
                else
                {
                    switch (typeByte)
                    {
                        case ParameterTypes.Bool:
                            parameters[i] = reader.ReadBoolean();
                            break;
                        case ParameterTypes.Byte:
                            parameters[i] = reader.ReadByte();
                            break;
                        case ParameterTypes.ByteArray:
                            parameters[i] = reader.ReadBytes(reader.ReadInt32());
                            break;
                        case ParameterTypes.CompressedByteArray:
                            parameters[i] = reader.ReadBytes(reader.ReadInt32()).FromGZipBytes();
                            break;
                        case ParameterTypes.Char:
                            parameters[i] = reader.ReadChar();
                            break;
                        case ParameterTypes.CharArray:
                            parameters[i] = reader.ReadChars(reader.ReadInt32());
                            break;
                        case ParameterTypes.CompressedCharArray:
                            var ccBytes = reader.ReadBytes(reader.ReadInt32()).FromGZipBytes();
                            parameters[i] = Encoding.UTF8.GetChars(ccBytes);
                            break;
                        case ParameterTypes.Decimal:
                            parameters[i] = reader.ReadDecimal();
                            break;
                        case ParameterTypes.Double:
                            parameters[i] = reader.ReadDouble();
                            break;
                        case ParameterTypes.Float:
                            parameters[i] = reader.ReadSingle();
                            break;
                        case ParameterTypes.Int:
                            parameters[i] = reader.ReadInt32();
                            break;
                        case ParameterTypes.Long:
                            parameters[i] = reader.ReadInt64();
                            break;
                        case ParameterTypes.SByte:
                            parameters[i] = reader.ReadSByte();
                            break;
                        case ParameterTypes.Short:
                            parameters[i] = reader.ReadInt16();
                            break;
                        case ParameterTypes.String:
                            parameters[i] = reader.ReadString();
                            break;
                        case ParameterTypes.CompressedString:
                            var csBytes = reader.ReadBytes(reader.ReadInt32()).FromGZipBytes();
                            parameters[i] = Encoding.UTF8.GetString(csBytes);
                            break;
                        case ParameterTypes.UInt:
                            parameters[i] = reader.ReadUInt32();
                            break;
                        case ParameterTypes.ULong:
                            parameters[i] = reader.ReadUInt64();
                            break;
                        case ParameterTypes.UShort:
                            parameters[i] = reader.ReadUInt16();
                            break;
                        case ParameterTypes.Type:
                            var typeName = reader.ReadString();
                            parameters[i] = Type.GetType(typeName);
                            break;
                        case ParameterTypes.Guid:
                            parameters[i] = new Guid(reader.ReadBytes(16));
                            break;
                        case ParameterTypes.DateTime:
                            var dtstr = reader.ReadString();
                            parameters[i] = DateTime.Parse(dtstr, null, DateTimeStyles.RoundtripKind);
                            break;

                        case ParameterTypes.ArrayBool:
                            var blen = reader.ReadInt32();
                            var bs = new bool[blen];
                            for (int x = 0; x < blen; x++) bs[x] = reader.ReadBoolean();
                            parameters[i] = bs;
                            break;
                        case ParameterTypes.ArraySByte:
                            var sblen = reader.ReadInt32();
                            var sbs = new sbyte[sblen];
                            for (int x = 0; x < sblen; x++) sbs[x] = reader.ReadSByte();
                            parameters[i] = sbs;
                            break;
                        case ParameterTypes.ArrayDecimal:
                            var dclen = reader.ReadInt32();
                            var dcs = new decimal[dclen];
                            for (int x = 0; x < dclen; x++) dcs[x] = reader.ReadDecimal();
                            parameters[i] = dcs;
                            break;
                        case ParameterTypes.ArrayDouble:
                            var dblen = reader.ReadInt32();
                            var dbs = new double[dblen];
                            for (int x = 0; x < dblen; x++) dbs[x] = reader.ReadDouble();
                            parameters[i] = dbs;
                            break;
                        case ParameterTypes.ArrayFloat:
                            var flen = reader.ReadInt32();
                            var fs = new float[flen];
                            for (int x = 0; x < flen; x++) fs[x] = reader.ReadSingle();
                            parameters[i] = fs;
                            break;
                        case ParameterTypes.ArrayInt:
                            var ilen = reader.ReadInt32();
                            var iss = new int[ilen];
                            for (int x = 0; x < ilen; x++) iss[x] = reader.ReadInt32();
                            parameters[i] = iss;
                            break;
                        case ParameterTypes.ArrayUInt:
                            var uilen = reader.ReadInt32();
                            var uis = new uint[uilen];
                            for (int x = 0; x < uilen; x++) uis[x] = reader.ReadUInt32();
                            parameters[i] = uis;
                            break;
                        case ParameterTypes.ArrayLong:
                            var llen = reader.ReadInt32();
                            var ls = new long[llen];
                            for (int x = 0; x < llen; x++) ls[x] = reader.ReadInt64();
                            parameters[i] = ls;
                            break;
                        case ParameterTypes.ArrayULong:
                            var ullen = reader.ReadInt32();
                            var uls = new ulong[ullen];
                            for (int x = 0; x < ullen; x++) uls[x] = reader.ReadUInt64();
                            parameters[i] = uls;
                            break;
                        case ParameterTypes.ArrayShort:
                            var sslen = reader.ReadInt32();
                            var sss = new short[sslen];
                            for (int x = 0; x < sslen; x++) sss[x] = reader.ReadInt16();
                            parameters[i] = sss;
                            break;
                        case ParameterTypes.ArrayUShort:
                            var ulen = reader.ReadInt32();
                            var us = new ushort[ulen];
                            for (int x = 0; x < ulen; x++) us[x] = reader.ReadUInt16();
                            parameters[i] = us;
                            break;
                        case ParameterTypes.ArrayString:
                            var slen = reader.ReadInt32();
                            var ss = new string[slen];
                            for (int x = 0; x < slen; x++) ss[x] = reader.ReadString();
                            parameters[i] = ss;
                            break;
                        case ParameterTypes.ArrayType:
                            var tlen = reader.ReadInt32();
                            var ts = new Type[tlen];
                            for (int x = 0; x < tlen; x++) ts[x] = Type.GetType(reader.ReadString());
                            parameters[i] = ts;
                            break;
                        case ParameterTypes.ArrayGuid:
                            var glen = reader.ReadInt32();
                            var gs = new Guid[glen];
                            for (int x = 0; x < glen; x++) gs[x] = new Guid(reader.ReadBytes(16));
                            parameters[i] = gs;
                            break;
                        case ParameterTypes.ArrayDateTime:
                            var dlen = reader.ReadInt32();
                            var dts = new DateTime[dlen];
                            for (int x = 0; x < dlen; x++)
                            {
                                var adtstr = reader.ReadString();
                                dts[x] = DateTime.Parse(adtstr, null, DateTimeStyles.RoundtripKind);
                            }
                            parameters[i] = dts;
                            break;

                        case ParameterTypes.Unknown:
                            var typeConfigName = reader.ReadString();
                            var bytes = reader.ReadBytes(reader.ReadInt32());
                            parameters[i] = bytes.ToDeserializedObject(typeConfigName);
                            break;
                        case ParameterTypes.CompressedUnknown:
                            var cuTypeConfigName = reader.ReadString();
                            var cuBytes = reader.ReadBytes(reader.ReadInt32()).FromGZipBytes();
                            parameters[i] = cuBytes.ToDeserializedObject(cuTypeConfigName);
                            break;
                        default:
                            throw new Exception(string.Format("Unknown type byte '0x{0:X}'", typeByte));
                    }
                }
            }
            return parameters;
        }
Example #25
0
		private static bool LoadPrimitiveData(ref object data, Type type, BinaryReader reader)
		{
			switch (Type.GetTypeCode(type))
			{
				case TypeCode.Boolean:
					data = reader.ReadBoolean();
					return true;
				case TypeCode.Byte:
					data = reader.ReadByte();
					return true;
				case TypeCode.Char:
					data = reader.ReadChar();
					return true;
				case TypeCode.Decimal:
					data = reader.ReadDecimal();
					return true;
				case TypeCode.Double:
					data = reader.ReadDouble();
					return true;
				case TypeCode.Single:
					data = reader.ReadSingle();
					return true;
				case TypeCode.Int16:
					data = reader.ReadInt16();
					return true;
				case TypeCode.Int32:
					data = reader.ReadInt32();
					return true;
				case TypeCode.Int64:
					data = reader.ReadInt64();
					return true;
				case TypeCode.String:
					data = reader.ReadString();
					return true;
				case TypeCode.SByte:
					data = reader.ReadSByte();
					return true;
				case TypeCode.UInt16:
					data = reader.ReadUInt16();
					return true;
				case TypeCode.UInt32:
					data = reader.ReadUInt32();
					return true;
				case TypeCode.UInt64:
					data = reader.ReadUInt64();
					return true;
			}
			return false;
		}
Example #26
0
        public object[] Deserialize(byte[] data)
        {
            MemoryStream Stream = new MemoryStream(data);
            BinaryReader Reader = new BinaryReader(Stream, Encoding.UTF8);
            List<object> Items = new List<object>();
            byte Current = 0;
            byte Count = Reader.ReadByte();

            for (int I = 0; I < Count; I++)
            {
                Current = Reader.ReadByte();

                switch (Current)
                {
                    case 0:
                        Items.Add(Reader.ReadBoolean());
                        break;
                    case 1:
                        Items.Add(Reader.ReadByte());
                        break;
                    case 2:
                        Items.Add(Reader.ReadBytes(Reader.ReadInt32()));
                        break;
                    case 3:
                        Items.Add(Reader.ReadChar());
                        break;
                    case 4:
                        Items.Add(Reader.ReadString().ToCharArray());
                        break;
                    case 5:
                        Items.Add(Reader.ReadDecimal());
                        break;
                    case 6:
                        Items.Add(Reader.ReadDouble());
                        break;
                    case 7:
                        Items.Add(Reader.ReadInt32());
                        break;
                    case 8:
                        Items.Add(Reader.ReadInt64());
                        break;
                    case 9:
                        Items.Add(Reader.ReadSByte());
                        break;
                    case 10:
                        Items.Add(Reader.ReadInt16());
                        break;
                    case 11:
                        Items.Add(Reader.ReadSingle());
                        break;
                    case 12:
                        Items.Add(Reader.ReadString());
                        break;
                    case 13:
                        Items.Add(Reader.ReadUInt32());
                        break;
                    case 14:
                        Items.Add(Reader.ReadUInt64());
                        break;
                    case 15:
                        Items.Add(Reader.ReadUInt16());
                        break;
                    case 16:
                        Items.Add(DateTime.FromBinary(Reader.ReadInt64()));
                        break;
                }
            }

            Reader.Close();
            return Items.ToArray();
        }
        /// <summary>
        /// Decodes a byte array (stored in the memory stream) into an object
        /// If the GUID is one of the internal versions, then the type is assumed
        /// to be byte array.
        /// If however, the guid is of unknown origin or not v1 internal, then the type
        ///     information is assumed to be stored in the first 2 bytes of the stream.
        /// </summary>
        /// <param name="guid">Guid of property - to detect origin</param>
        /// <param name="memStream">Buffer of data</param>
        /// <param name="type">the type info stored in the stream</param>
        /// <returns>object stored in data buffer</returns>
        /// <remarks>The buffer stream passed in to the method will be closed after reading</remarks>
        internal static object DecodeAttribute(Guid guid, Stream memStream, out VarEnum type)
        {
            // First determine the object type
            using (BinaryReader br = new BinaryReader(memStream))
            {
                //
                // if usesEmbeddedTypeInfo is true, we do not 
                // read the variant type from the ISF stream.  Instead, 
                // we assume it to be a byte[]
                //
                bool usesEmbeddedTypeInfo = UsesEmbeddedTypeInformation(guid);

                // if the Id has embedded type information then retrieve it from the stream
                if (usesEmbeddedTypeInfo)
                {
                    // We must read the data type from the stream
                    type = (VarEnum)br.ReadUInt16();
                }
                else
                {
                    // The data is stored as byte array
                    type = (VarEnum.VT_ARRAY | VarEnum.VT_UI1);
                }
                switch (type)
                {
                    case (VarEnum.VT_ARRAY | VarEnum.VT_I1):
                        return br.ReadChars((int)(memStream.Length - 2));
                    case (VarEnum.VT_ARRAY | VarEnum.VT_UI1):
                        {
                            //
                            // note: for (VarEnum.VT_ARRAY | VarEnum.VT_UI1),
                            // we might be reading data that didn't have the 
                            // type embedded in the ISF stream, in which case
                            // we must not assume we've already read two bytes
                            //
                            int previouslyReadBytes = 2;
                            if (!usesEmbeddedTypeInfo)
                            {
                                previouslyReadBytes = 0;
                            }
                            return br.ReadBytes((int)(memStream.Length - previouslyReadBytes));
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_I2):
                        {
                            int count = (int)(memStream.Length - 2) / 2;    // 2 is the size of one element
                            short[] val = new short[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadInt16();
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_UI2):
                        {
                            int count = (int)(memStream.Length - 2) / 2;    // 2 is the size of one element
                            ushort[] val = new ushort[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadUInt16();
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_I4):
                        {
                            int count = (int)(memStream.Length - 2) / 4;    // 2 is the size of one element
                            int[] val = new int[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadInt32();
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_UI4):
                        {
                            int count = (int)(memStream.Length - 2) / 4;    // size of one element
                            uint[] val = new uint[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadUInt32();
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_I8):
                        {
                            int count = (int)(memStream.Length - 2) / Native.BitsPerByte;    // size of one element
                            long[] val = new long[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadInt64();
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_UI8):
                        {
                            int count = (int)(memStream.Length - 2) / Native.BitsPerByte;    // size of one element
                            ulong[] val = new ulong[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadUInt64();
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_R4):
                        {
                            int count = (int)(memStream.Length - 2) / 4;    // size of one element
                            float[] val = new float[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadSingle();
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_R8):
                        {
                            int count = (int)(memStream.Length - 2) / Native.BitsPerByte;    // size of one element
                            double[] val = new double[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadDouble();
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_DATE):
                        {
                            int count = (int)(memStream.Length - 2) / Native.BitsPerByte;    // size of one element
                            DateTime[] val = new DateTime[count];
                            for (int i = 0; i < count; i++)
                            {
                                val[i] = DateTime.FromOADate(br.ReadDouble());
                            }
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_BOOL):
                        {
                            int count = (int)(memStream.Length - 2);    // size of one element
                            bool[] val = new bool[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadBoolean();
                            return val;
                        }
                    case (VarEnum.VT_ARRAY | VarEnum.VT_DECIMAL):
                        {
                            int count = (int)((memStream.Length - 2) / Native.SizeOfDecimal);    // size of one element
                            decimal[] val = new decimal[count];
                            for (int i = 0; i < count; i++)
                                val[i] = br.ReadDecimal();
                            return val;
                        }
                    case (VarEnum.VT_I1):
                        return br.ReadChar();
                    case (VarEnum.VT_UI1):
                        return br.ReadByte();
                    case (VarEnum.VT_I2):
                        return br.ReadInt16();
                    case (VarEnum.VT_UI2):
                        return br.ReadUInt16();
                    case (VarEnum.VT_I4):
                        return br.ReadInt32();
                    case (VarEnum.VT_UI4):
                        return br.ReadUInt32();
                    case (VarEnum.VT_I8):
                        return br.ReadInt64();
                    case (VarEnum.VT_UI8):
                        return br.ReadUInt64();
                    case (VarEnum.VT_R4):
                        return br.ReadSingle();
                    case (VarEnum.VT_R8):
                        return br.ReadDouble();
                    case (VarEnum.VT_DATE):
                        return DateTime.FromOADate(br.ReadDouble());
                    case (VarEnum.VT_BOOL):
                        return br.ReadBoolean();
                    case (VarEnum.VT_DECIMAL):
                        return br.ReadDecimal();
                    case (VarEnum.VT_BSTR):
                        {
                            byte[] bytestring = br.ReadBytes((int)memStream.Length);
                            return System.Text.Encoding.Unicode.GetString(bytestring);
                        }
                    default:
                        {
                            throw new InvalidOperationException(SR.Get(SRID.InvalidEpInIsf));
                        }
                }
            }
        }
Example #28
0
        private static object ReadValueCore(Type type, BinaryReader reader)
        {
            try {
                if (type == typeof (byte[])) {
                    return ReadArrayOfByte(reader);
                }
                if (type == typeof (string)) {
                    return reader.ReadString();
                }
                if (type == typeof (bool)) {
                    return reader.ReadBoolean();
                }
                if (type == typeof (byte)) {
                    return reader.ReadByte();
                }
                if (type == typeof (char)) {
                    return reader.ReadChar();
                }
                if (type == typeof (DateTime)) {
                    return new DateTime(reader.ReadInt64());
                }
                if (type == typeof (Guid)) {
                    return new Guid(reader.ReadBytes(16));
                }
            #if DEBUG || PORTABLE || SILVERLIGHT
                if (type == typeof (decimal)) {
                    return ReadDecimal(reader);
                }
            #else
                if (type == typeof (Decimal)) return reader.ReadDecimal();
            #endif
                if (type == typeof (double)) {
                    return reader.ReadDouble();
                }
                if (type == typeof (short)) {
                    return reader.ReadInt16();
                }
                if (type == typeof (int)) {
                    return reader.ReadInt32();
                }
                if (type == typeof (long)) {
                    return reader.ReadInt64();
                }
                if (type == typeof (sbyte)) {
                    return reader.ReadSByte();
                }
                if (type == typeof (float)) {
                    return reader.ReadSingle();
                }
                if (type == typeof (ushort)) {
                    return reader.ReadUInt16();
                }
                if (type == typeof (uint)) {
                    return reader.ReadUInt32();
                }
                if (type == typeof (ulong)) {
                    return reader.ReadUInt64();
                }

                if (type == typeof (TimeSpan)) {
                    return new TimeSpan(reader.ReadInt64());
                }

                // Enumeration
                if (type.IsEnum) {
                    return ReadEnumeration(type, reader);
                }

                // Type
                if (IsType(type)) {
                    var typeName = reader.ReadString();
                    return Type.GetType(typeName, true);
                }

                throw new InvalidOperationException(string.Format("Unknown simple type: {0}", type.FullName));
            }
            catch (Exception ex) {
                throw new SimpleValueParsingException(string.Format("Invalid type: {0}. See details in the inner exception.", type), ex);
            }
        }
 /// <summary>
 /// Creates an instance of the specified type contained in the specified stream.
 /// </summary>
 public static object CreateInstance(Type type, Stream stream)
 {
     BinaryReader br = new BinaryReader(stream, Encoding.ASCII);
     object obj = Activator.CreateInstance(type);
     foreach(FieldInfo field in type.GetFields())
     {
         if((!field.IsPublic) || (field.IsStatic))
             continue;
         if(field.FieldType == typeof(Boolean))
             field.SetValue(obj, br.ReadBoolean());
         else if(field.FieldType == typeof(Byte))
             field.SetValue(obj, br.ReadByte());
         else if(field.FieldType == typeof(Char))
             field.SetValue(obj, br.ReadChar());
         else if(field.FieldType == typeof(Decimal))
             field.SetValue(obj, br.ReadDecimal());
         else if(field.FieldType == typeof(Double))
             field.SetValue(obj, br.ReadDouble());
         else if(field.FieldType == typeof(Int16))
             field.SetValue(obj, br.ReadInt16());
         else if(field.FieldType == typeof(Int32))
             field.SetValue(obj, br.ReadInt32());
         else if(field.FieldType == typeof(Int64))
             field.SetValue(obj, br.ReadInt64());
         else if(field.FieldType == typeof(SByte))
             field.SetValue(obj, br.ReadSByte());
         else if(field.FieldType == typeof(Single))
             field.SetValue(obj, br.ReadSingle());
         else if(field.FieldType == typeof(UInt16))
             field.SetValue(obj, br.ReadUInt16());
         else if(field.FieldType == typeof(UInt32))
             field.SetValue(obj, br.ReadUInt32());
         else if(field.FieldType == typeof(UInt64))
             field.SetValue(obj, br.ReadUInt64());
         else if(field.FieldType == typeof(Byte[]))
         {
             ArrayLengthAttribute[] attrs = (ArrayLengthAttribute[])field.GetCustomAttributes(typeof(ArrayLengthAttribute), true);
             if(attrs.Length != 1)
                 throw new InvalidOperationException("Required a single specified length given by the ArrayLength Attribute");
             field.SetValue(obj, br.ReadBytes(attrs[0].ArrayLength));
         }
         else if(field.FieldType == typeof(Char[]))
         {
             ArrayLengthAttribute[] attrs = (ArrayLengthAttribute[])field.GetCustomAttributes(typeof(ArrayLengthAttribute), true);
             if(attrs.Length != 1)
                 throw new InvalidOperationException("Required a single specified length given by the ArrayLength Attribute");
             field.SetValue(obj, br.ReadChars(attrs[0].ArrayLength));
         }
         else if(field.FieldType == typeof(String))
         {
             ArrayLengthAttribute[] attrs = (ArrayLengthAttribute[])field.GetCustomAttributes(typeof(ArrayLengthAttribute), true);
             if(attrs.Length == 1)
                 field.SetValue(obj, new string(br.ReadChars(attrs[0].ArrayLength)));
             else
                 field.SetValue(obj, br.ReadString());
         }
         else
             throw new NotSupportedException("Type not supported in read");
     }
     return obj;
 }
Example #30
0
        /// <summary>
        /// Deserialisiert den Player aus dem angegebenen BinaryReader.
        /// </summary>
        /// <param name="reader">Der BinaryWriter, mit dem gelesen wird.</param>
        /// <param name="definitionManager">Der aktuell verwendete <see cref="IDefinitionManager"/>.</param>
        public override void Deserialize(BinaryReader reader, IDefinitionManager definitionManager)
        {
            // Entity
            base.Deserialize(reader, definitionManager);

            // Radius
            Radius = reader.ReadSingle();

            // Angle
            Angle = reader.ReadSingle();

            // Height
            Height = reader.ReadSingle();

            // Tilt
            Tilt = reader.ReadSingle();

            // FlyMode
            FlyMode = reader.ReadBoolean();

            // Inventory Limit
            // TODO: Noch nicht persistiert

            // Inventory
            int inventoryCount = reader.ReadInt32();
            for (int i = 0; i < inventoryCount; i++)
            {
                string definitionName = reader.ReadString();
                decimal amount = reader.ReadDecimal();

                var definition = definitionManager.GetItemDefinitions().FirstOrDefault(d => d.GetType().FullName.Equals(definitionName));
                if (definition != null)
                {
                    InventorySlot slot = new InventorySlot();
                    slot.Definition = definition;
                    slot.Amount = amount;
                    Inventory.Add(slot);
                }
            }

            // Inventory Tools (Index auf Inventory)
            byte toolCount = reader.ReadByte();
            for (byte i = 0; i < toolCount; i++)
            {
                byte index = reader.ReadByte();
                string definitionType = reader.ReadString();

                InventorySlot slot = Inventory.FirstOrDefault(s => s.Definition.GetType().FullName.Equals(definitionType));
                if (slot != null)
                    Tools[index] = slot;
            }
        }