本文整理汇总了C#中Newtonsoft.Json.Bson.BsonReader类的典型用法代码示例。如果您正苦于以下问题:C# BsonReader类的具体用法?C# BsonReader怎么用?C# BsonReader使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
BsonReader类属于Newtonsoft.Json.Bson命名空间,在下文中一共展示了BsonReader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ReadFromStreamAsync
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;
}
示例2: Deserialize
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);
}
}
示例3: UseBsonSerializer
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());
}
示例4: Deserialize
public static object Deserialize(Stream stream, System.Type type)
{
using (var reader = new BsonReader(stream))
{
return serializer.Deserialize(reader, type);
}
}
示例5: Import
public void Import(Stream stream)
{
using (BsonReader reader = new BsonReader(stream))
{
_jsonSerializer.Populate(reader, _cardsByID);
}
}
示例6: DateTimeKindHandling
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"]);
}
示例7: Deserialize
public override object Deserialize(Stream stream, System.Type type)
{
using (var reader = new BsonReader(stream))
{
return this.Deserialize(reader, type);
}
}
示例8: using
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);
}
}
示例9: LoadTempData
/// <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;
}
示例10: ReadSingleObject
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);
}
示例11: ReadFromStreamAsync
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;
}
示例12: ReadStateAsync
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);
}
}
}
示例13: RetrieveCreditInfo
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);
}
}
}
}
示例14: CraftitudeProfile
// 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();
}
}
}
}
示例15: ReadRequestBodyAsync
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();
}
}