Represents a reader that provides fast, non-cached, forward-only access to serialized Json data.
Inheritance: JsonReader
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
        {
            var taskCompletionSource = new TaskCompletionSource<object>();

            try
            {
                BsonReader reader = new BsonReader(readStream);
                if (typeof(IEnumerable).IsAssignableFrom(type)) reader.ReadRootValueAsArray = true;

                using (reader)
                {
                    var jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                    var output = jsonSerializer.Deserialize(reader, type);
                    if (formatterLogger != null)
                    {
                        jsonSerializer.Error += (sender, e) =>
                        {
                            Exception exception = e.ErrorContext.Error;
                            formatterLogger.LogError(e.ErrorContext.Path, exception.Message);
                            e.ErrorContext.Handled = true;
                        };
                    }
                    taskCompletionSource.SetResult(output);
                }
            }
            catch (Exception ex)
            {
                if (formatterLogger == null) throw;
                formatterLogger.LogError(String.Empty, ex.Message);
                taskCompletionSource.SetResult(GetDefaultValueForType(type));
            }

            return taskCompletionSource.Task;
        }
Esempio n. 2
0
        private object ReadBson(BsonReader reader)
        {
            string regexText = (string)reader.Value;
            int patternOptionDelimiterIndex = regexText.LastIndexOf(@"/");

            string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1);
            string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1);

            RegexOptions options = RegexOptions.None;
            foreach (char c in optionsText)
            {
            switch (c)
            {
            case 'i':
            options |= RegexOptions.IgnoreCase;
            break;
            case 'm':
            options |= RegexOptions.Multiline;
            break;
            case 's':
            options |= RegexOptions.Singleline;
            break;
            case 'x':
            options |= RegexOptions.ExplicitCapture;
            break;
            }
            }

            return new Regex(patternText, options);
        }
Esempio n. 3
0
        public void UseBsonSerializer()
        {
            var message = GetMyJsonTestMessage();

            var serializer = new JsonSerializer();
            byte[] serializedMessage;

            using (var stream = new MemoryStream())
            using (var writer = new BsonWriter(stream))
            {
                serializer.Serialize(writer, message);

                serializedMessage = stream.GetBuffer();
            }

            MyJsonTestMessage deserializedMessage;
            using (var stream = new MemoryStream(serializedMessage))
            using (var reader = new BsonReader(stream))
            {

                deserializedMessage = serializer.Deserialize<MyJsonTestMessage>(reader);
            }

            Console.Out.WriteLine(deserializedMessage.GetHashCode() == message.GetHashCode());
        }
 public static object Deserialize(Stream stream, System.Type type)
 {
     using (var reader = new BsonReader(stream))
     {
         return serializer.Deserialize(reader, type);
     }
 }
 public void Import(Stream stream)
 {
     using (BsonReader reader = new BsonReader(stream))
     {
         _jsonSerializer.Populate(reader, _cardsByID);
     }
 }
Esempio n. 6
0
        public void DateTimeKindHandling()
        {
            DateTime value = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Utc);

              MemoryStream ms = new MemoryStream();
              BsonWriter writer = new BsonWriter(ms);

              writer.WriteStartObject();
              writer.WritePropertyName("DateTime");
              writer.WriteValue(value);
              writer.WriteEndObject();

              byte[] bson = ms.ToArray();

              JObject o;
              BsonReader reader;

              reader = new BsonReader(new MemoryStream(bson), false, DateTimeKind.Utc);
              o = (JObject)JToken.ReadFrom(reader);
              Assert.AreEqual(value, (DateTime)o["DateTime"]);

              reader = new BsonReader(new MemoryStream(bson), false, DateTimeKind.Local);
              o = (JObject)JToken.ReadFrom(reader);
              Assert.AreEqual(value.ToLocalTime(), (DateTime)o["DateTime"]);

              reader = new BsonReader(new MemoryStream(bson), false, DateTimeKind.Unspecified);
              o = (JObject)JToken.ReadFrom(reader);
              Assert.AreEqual(DateTime.SpecifyKind(value.ToLocalTime(), DateTimeKind.Unspecified), (DateTime)o["DateTime"]);
        }
 public override object Deserialize(Stream stream, System.Type type)
 {
     using (var reader = new BsonReader(stream))
     {
         return this.Deserialize(reader, type);
     }
 }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                MessageEnvelope envelope;
                using (Stream body = receiveContext.GetBody())
                using (var jsonReader = new BsonReader(body))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
        /// <inheritdoc />
        public virtual IDictionary<string, object> LoadTempData([NotNull] HttpContext context)
        {
            if (!IsSessionEnabled(context))
            {
                // Session middleware is not enabled. No-op
                return null;
            }

            var tempDataDictionary = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            var session = context.Session;
            byte[] value;

            if (session != null && session.TryGetValue(TempDataSessionStateKey, out value))
            {
                using (var memoryStream = new MemoryStream(value))
                using (var writer = new BsonReader(memoryStream))
                {
                    tempDataDictionary = jsonSerializer.Deserialize<Dictionary<string, object>>(writer);
                }

                // If we got it from Session, remove it so that no other request gets it
                session.Remove(TempDataSessionStateKey);
            }
            else
            {
                // Since we call Save() after the response has been sent, we need to initialize an empty session
                // so that it is established before the headers are sent.
                session[TempDataSessionStateKey] = new byte[] { };
            }

            return tempDataDictionary;
        }
        public ConsumeContext Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                MessageEnvelope envelope;
                using (Stream body = receiveContext.GetBody())
                using (Stream cryptoStream = _provider.GetDecryptStream(body, receiveContext))
                using (var jsonReader = new BsonReader(cryptoStream))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, _sendEndpointProvider, _publishEndpoint, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
		public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState)
		{
			var tableResult = await _table.ExecuteAsync(TableOperation.Retrieve<DynamicTableEntity>(grainReference.ToKeyString(), grainType));
			if (tableResult.Result == null)
			{
				return;
			}
			var entity = tableResult.Result as DynamicTableEntity;

			var serializer = new JsonSerializer();
			using (var memoryStream = new MemoryStream())
			{
				foreach (var propertyName in entity.Properties.Keys.Where(p => p.StartsWith("d")).OrderBy(p => p))
				{
					var dataPart = entity.Properties[propertyName];
					await memoryStream.WriteAsync(dataPart.BinaryValue, 0, dataPart.BinaryValue.Length);
				}

				memoryStream.Position = 0;
				using (var bsonReader = new BsonReader(memoryStream))
				{
					var data = serializer.Deserialize<Dictionary<string, object>>(bsonReader);
					grainState.SetAll(data);
				}
			}
		}
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var tcs = new TaskCompletionSource<object>();
            if (content != null && content.Headers.ContentLength == 0) return null;

            try
            {
                var reader = new BsonReader(readStream);

                if (typeof(IEnumerable).IsAssignableFrom(type)) reader.ReadRootValueAsArray = true;

                using (reader)
                {
                    var jsonSerializer = JsonSerializer.Create(_jsonSerializerSettings);
                    var output = jsonSerializer.Deserialize(reader, type);
                    tcs.SetResult(output);
                }
            }
            catch (Exception)
            {
                tcs.SetResult(GetDefaultValueForType(type));
            }

            return tcs.Task;
        }
Esempio n. 13
0
        public override async Task<CreditInfo> RetrieveCreditInfo(string username, string password, string Type, Guid dev_id)
        {

            var dsrz = new JsonSerializer();
            using (var httpclient = new HttpClient())
            {
                httpclient.DefaultRequestHeaders.ExpectContinue = false;
                httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));
                using (var httpstrAuthJson = await httpclient.PostAsync("https://wauth.apphb.com/api/AuthServ/GetData", new StringContent(JsonConvert.SerializeObject(new { q = username, x = password, t = Type, dev_id = dev_id }), Encoding.UTF8, "application/json")))
                {
                    using (var strData = await httpstrAuthJson.Content.ReadAsStreamAsync())
                    {

                        var bson = new BsonReader(strData);

                        if (httpstrAuthJson.StatusCode == HttpStatusCode.BadRequest)
                        {
                            var obj = dsrz.Deserialize<MessageError>(bson);
                            throw new Exception(obj.Message);
                        }

                        if (httpstrAuthJson.StatusCode == HttpStatusCode.NotFound)
                        {
                            var obj = new { Message = "Error during server connection." };
                            throw new Exception(obj.Message);
                        }

                        httpstrAuthJson.RequestMessage.Content.Dispose();
                        return dsrz.Deserialize<CreditInfo>(bson);
                    }


                }
            }
        }
Esempio n. 14
0
        // Constructor
        /// <summary>
        /// Open a profile (create if not exist) and load it.
        /// </summary>
        /// <param name="profileDirectory">The root directory of the profile</param>
        public CraftitudeProfile(DirectoryInfo profileDirectory)
        {
            Directory = profileDirectory;

            _craftitudeDirectory = Directory.CreateSubdirectory("craftitude");
            _craftitudeDirectory.CreateSubdirectory("repositories"); // repository package lists
            _craftitudeDirectory.CreateSubdirectory("packages"); // cached package setups

            _bsonFile = _craftitudeDirectory.GetFile("profile.bson");

            if (!_bsonFile.Exists)
            {
                ProfileInfo = new ProfileInfo();
            }
            else
            {
                using (FileStream bsonStream = _bsonFile.Open(FileMode.OpenOrCreate))
                {
                    using (var bsonReader = new BsonReader(bsonStream))
                    {
                        var jsonSerializer = new JsonSerializer();
                        ProfileInfo = jsonSerializer.Deserialize<ProfileInfo>(bsonReader) ?? new ProfileInfo();
                    }
                }
            }
        }
        public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            var request = context.HttpContext.Request;
            using (var reader = new BsonReader(request.Body))
            {
                var successful = true;
                EventHandler<ErrorEventArgs> errorHandler = (sender, eventArgs) =>
                {
                    successful = false;
                    var exception = eventArgs.ErrorContext.Error;
                    eventArgs.ErrorContext.Handled = true;
                };                
                var jsonSerializer = CreateJsonSerializer();
                jsonSerializer.Error += errorHandler;
                var type = context.ModelType;
                object model;
                try
                {
                    model = jsonSerializer.Deserialize(reader, type);
                }
                finally
                {
                    _jsonSerializerPool.Return(jsonSerializer);
                }

                if (successful)
                {
                    return InputFormatterResult.SuccessAsync(model);
                }

                return InputFormatterResult.FailureAsync();
            }
        }
Esempio n. 16
0
 public object Deserialize(Stream s)
 {
     using (var r = new BsonReader(s))
       {
     return Serializer.Deserialize(r);
       }
 }
Esempio n. 17
0
 private object ReadBson(BsonReader reader)
 {
   string str1 = (string) reader.Value;
   int num = str1.LastIndexOf('/');
   string pattern = str1.Substring(1, num - 1);
   string str2 = str1.Substring(num + 1);
   RegexOptions options = RegexOptions.None;
   foreach (char ch in str2)
   {
     switch (ch)
     {
       case 's':
         options |= RegexOptions.Singleline;
         break;
       case 'x':
         options |= RegexOptions.ExplicitCapture;
         break;
       case 'i':
         options |= RegexOptions.IgnoreCase;
         break;
       case 'm':
         options |= RegexOptions.Multiline;
         break;
     }
   }
   return (object) new Regex(pattern, options);
 }
Esempio n. 18
0
    public void ReadSingleObject()
    {
      byte[] data = MiscellaneousUtils.HexToBytes("0F-00-00-00-10-42-6C-61-68-00-01-00-00-00-00");
      MemoryStream ms = new MemoryStream(data);
      BsonReader reader = new BsonReader(ms);

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(JsonToken.StartObject, reader.TokenType);

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(JsonToken.PropertyName, reader.TokenType);
      Assert.AreEqual("Blah", reader.Value);
      Assert.AreEqual(typeof(string), reader.ValueType);

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(JsonToken.Integer, reader.TokenType);
      Assert.AreEqual(1L, reader.Value);
      Assert.AreEqual(typeof(long), reader.ValueType);

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(JsonToken.EndObject, reader.TokenType);

      Assert.IsFalse(reader.Read());
      Assert.AreEqual(JsonToken.None, reader.TokenType);
    }
Esempio n. 19
0
        public static async Task<SongTransferMessage> ReadNextFileTransferMessageAsync(this Stream stream)
        {
            byte[] messageLength = await stream.ReadAsync(4);

            if (messageLength.Length == 0)
            {
                return null;
            }

            int realMessageLength = BitConverter.ToInt32(messageLength, 0);

            byte[] messageContent = await stream.ReadAsync(realMessageLength);

            if (messageContent.Length == 0)
            {
                return null;
            }

            using (var memoryStream = new MemoryStream(messageContent))
            {
                using (var reader = new BsonReader(memoryStream))
                {
                    var deserializer = new JsonSerializer();

                    return deserializer.Deserialize<SongTransferMessage>(reader);
                }
            }
        }
Esempio n. 20
0
 public static JObject Read(FileStream stream)
 {
     using (var br = new Newtonsoft.Json.Bson.BsonReader(stream))
     {
         var serializer = new Newtonsoft.Json.JsonSerializer();
         return((JObject)serializer.Deserialize(br));
     }
 }
Esempio n. 21
0
 public object Deserialize(byte[] data)
 {
     using (var s = new MemoryStream(data))
       using (var r = new BsonReader(s))
       {
     return Serializer.Deserialize(r);
       }
 }
 protected override object OnReadFromStream(Type type, Stream stream, HttpContentHeaders contentHeaders)
 {
     var serializer = new JsonSerializer();
     using (var reader = new BsonReader(stream)) {
         var result = serializer.Deserialize(reader, type);
         return result;
     }
 }
Esempio n. 23
0
 public virtual object Deserialize(byte[] data, Type type)
 {
     using (var inStream = new MemoryStream(data))
     using (var bsonReader = new BsonReader(inStream))
     {
         return CreateSerializer().Deserialize(bsonReader, type);
     }
 }
Esempio n. 24
0
 private static object DeserializeInternal(byte[] bytes, Type type)
 {
     using (var ms = new MemoryStream(bytes))
     using (var reader = new BsonReader(ms))
     {
         var serializer = new JsonSerializer();
         return serializer.Deserialize(reader, type);
     }
 }
Esempio n. 25
0
 public static StoredEvent<JObject> ReadStoredEvent(this byte[] eventBytes, Guid id, long version)
 {
     var input = new MemoryStream(eventBytes);
     var reader = new BinaryReader(input);
     var bsonReader = new BsonReader(input);
     return new StoredEvent<JObject>(new Guid(reader.ReadBytes(16)), new DateTime(reader.ReadInt64()),
                                     reader.ReadString(), new Version(reader.ReadString()), id, version,
                                     JObject.Load(bsonReader));
 }
Esempio n. 26
0
		public static object Deserialize(byte[] bsonData)
		{
			using (MemoryStream memoryStream = new MemoryStream(bsonData))
			{
				object objReturn = null;
				using (BsonReader reader = new BsonReader(memoryStream))
				{
					JsonSerializer serializer = new JsonSerializer();
					BsonObject bsonObject = serializer.Deserialize<BsonObject>(reader);

					string type = bsonObject.Payload[0] as string;
					Type objectType = bsonObject.Payload[1].GetType();
					if (objectType == typeof(JArray))
					{
						if (type.Contains("List"))
						{
							Type genericType = Type.GetType(type);
							objReturn = JsonConvert.DeserializeObject(bsonObject.Payload[1].ToString(), genericType);
						}
						else
						{
							//TODO: map and others collections!
						}
					}
					else if (objectType != Type.GetType(type))
					{
						switch (type)
						{
							case "System.Int32":
								objReturn = Convert.ToInt32(bsonObject.Payload[1]);
								break;
							case "System.UInt32":
								objReturn = Convert.ToUInt32(bsonObject.Payload[1]);
								break;
							case "System.Int16":
								objReturn = Convert.ToUInt16(bsonObject.Payload[1]);
								break;
							case "System.UInt16":
								objReturn = Convert.ToUInt16(bsonObject.Payload[1]);
								break;
							case "System.Double":
								objReturn = Convert.ToDouble(bsonObject.Payload[1]);
								break;
							case "System.Single":
								objReturn = Convert.ToSingle(bsonObject.Payload[1]);
								break;
						}
					}
					else
					{
						objReturn = bsonObject.Payload[1];
					}
				}
				return objReturn;
			}
		}
 public object Deserialize(byte[] messageBytes, Type messageType)
 {
     using (var stream = new MemoryStream(messageBytes))
     {
         using (var reader = new BsonReader(stream))
         {
             return JsonSerializer.Deserialize(reader, messageType);
         }
     }
 }
Esempio n. 28
0
        public static JObject Deserialize(Stream stream)
        {
            JObject obj;
            using (var jsonReader = new BsonReader(stream))
            {
                jsonReader.CloseInput = true;
                obj = JObject.Load(jsonReader);
            }

            return obj;
        }
Esempio n. 29
0
        public void Execute(ClientInformation client, Stream clientStream)
        {
            using (var reader = new BsonReader(clientStream))
            using (var writer = new BsonWriter(clientStream))
            {
                try
                {
                    Log.Info("Deserializing JSON-RPC request");

                    var request = serializer.Deserialize<JsonRpcRequest>(reader);
                    if (request == null) throw new ArgumentException("No JSON-RPC request was sent");

                    var activityName = string.Format("{0} : {1}", client.RemoteAddress, request.Id);
                    using (Log.BeginActivity(activityName, request.ActivityId))
                    {
                        try
                        {
                            Log.Info("Validating request");

                            if (string.IsNullOrWhiteSpace(request.Service)) throw new ArgumentException("No service name was specified in the JSON-RPC request");
                            if (string.IsNullOrWhiteSpace(request.Method)) throw new ArgumentException("No service method was specified in the JSON-RPC request");

                            Log.InfoFormat("Resolving service {0}", request.Service);

                            var serviceType = services.GetService(request.Service);
                            if (serviceType == null)
                            {
                                throw new ArgumentException(string.Format("The service type {0} is not implemented on this server", request.Service));
                            }

                            Log.InfoFormat("Constructing service {0}", serviceType.FullName);

                            JsonRpcResponse response;
                            using (var lease = serviceFactory.CreateService(serviceType))
                            {
                                var service = lease.Service;

                                response = serviceInvoker.Invoke(service, request);
                            }

                            SendResponse(writer, response);
                        }
                        catch (Exception ex)
                        {
                            SendResponse(writer, CreateError(ex, request));
                        }
                    }
                }
                catch (Exception ex)
                {
                    SendResponse(writer, CreateError(ex, null));
                }
            }
        }
Esempio n. 30
0
        public void DeserializeLargeBsonObject()
        {
            byte[] data = System.IO.File.ReadAllBytes(@"SpaceShipV2.bson");

            MemoryStream ms = new MemoryStream(data);
            BsonReader reader = new BsonReader(ms);

            JObject o = (JObject)JToken.ReadFrom(reader);

            Assert.AreEqual("1", (string)o["$id"]);
        }
        /// <summary>
        /// Loads loads the raw data from the NCldr data file and returns an NCldrData object
        /// </summary>
        /// <returns>An INCldrData object from the NCldr data file</returns>
        public INCldrData Load()
        {
            if (!this.Exists())
            {
                return null;
            }

            NCldrData ncldrData = null;
            using (FileStream stream = File.OpenRead(this.NCldrDataFilename))
            {
                try
                {
                    BsonReader bsonReader = new BsonReader(stream);
                    JsonSerializer serializer = new JsonSerializer();
                    ncldrData = serializer.Deserialize<NCldrData>(bsonReader);
                }
                catch (SerializationException exception)
                {
                    Console.WriteLine("Failed to deserialize. Reason: " + exception.Message);
                    throw;
                }
            }

            return ncldrData;
        }