當前位置: 首頁>>代碼示例>>C#>>正文


C# Bson.BsonWriter類代碼示例

本文整理匯總了C#中Newtonsoft.Json.Bson.BsonWriter的典型用法代碼示例。如果您正苦於以下問題:C# BsonWriter類的具體用法?C# BsonWriter怎麽用?C# BsonWriter使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


BsonWriter類屬於Newtonsoft.Json.Bson命名空間,在下文中一共展示了BsonWriter類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: WriteValues

    public void WriteValues()
    {
      MemoryStream ms = new MemoryStream();
      BsonWriter writer = new BsonWriter(ms);

      writer.WriteStartArray();
      writer.WriteValue(long.MaxValue);
      writer.WriteValue((ulong)long.MaxValue);
      writer.WriteValue(int.MaxValue);
      writer.WriteValue((uint)int.MaxValue);
      writer.WriteValue(byte.MaxValue);
      writer.WriteValue(sbyte.MaxValue);
      writer.WriteValue('a');
      writer.WriteValue(decimal.MaxValue);
      writer.WriteValue(double.MaxValue);
      writer.WriteValue(float.MaxValue);
      writer.WriteValue(true);
      writer.WriteValue(new byte[] { 0, 1, 2, 3, 4 });
      writer.WriteValue(new DateTimeOffset(2000, 12, 29, 12, 30, 0, TimeSpan.Zero));
      writer.WriteValue(new DateTime(2000, 12, 29, 12, 30, 0, DateTimeKind.Utc));
      writer.WriteEnd();

      string bson = MiscellaneousUtils.BytesToHex(ms.ToArray());
      Assert.AreEqual("8C-00-00-00-12-30-00-FF-FF-FF-FF-FF-FF-FF-7F-12-31-00-FF-FF-FF-FF-FF-FF-FF-7F-10-32-00-FF-FF-FF-7F-10-33-00-FF-FF-FF-7F-10-34-00-FF-00-00-00-10-35-00-7F-00-00-00-02-36-00-02-00-00-00-61-00-01-37-00-00-00-00-00-00-00-F0-45-01-38-00-FF-FF-FF-FF-FF-FF-EF-7F-01-39-00-00-00-00-E0-FF-FF-EF-47-08-31-30-00-01-05-31-31-00-05-00-00-00-02-00-01-02-03-04-09-31-32-00-40-C5-E2-BA-E3-00-00-00-09-31-33-00-40-C5-E2-BA-E3-00-00-00-00", bson);
    }
開發者ID:RecursosOnline,項目名稱:c-sharp,代碼行數:25,代碼來源:BsonWriterTests.cs

示例2: ExecuteResultAsync

        /// <inheritdoc />
        public override Task ExecuteResultAsync(ActionContext context)
        {
            var response = context.HttpContext.Response;

            response.ContentType = ContentType.Bson;

            if (StatusCode != null)
            {
                response.StatusCode = StatusCode.Value;
            }

            var serializerSettings = _serializerSettings;
            if (serializerSettings == null)
            {
                serializerSettings = context
                    .HttpContext
                    .RequestServices
                    .GetRequiredService<IOptions<MvcJsonOptions>>()
                    .Value
                    .SerializerSettings;
            }

            using (var bsonWriter = new BsonWriter(response.Body))
            {
                bsonWriter.CloseOutput = false;
                var jsonSerializer = JsonSerializer.Create(serializerSettings);
                jsonSerializer.Serialize(bsonWriter, Value);
            }

            return Task.FromResult(true);
        }
開發者ID:netusers2014,項目名稱:ASP.NET-MVC-Boilerplate,代碼行數:32,代碼來源:BsonResult.cs

示例3: Export

 public void Export(Stream stream)
 {
     using (BsonWriter writer = new BsonWriter(stream))
     {
         _jsonSerializer.Serialize(writer, _cardsByID);
     }
 }
開發者ID:Gohla,項目名稱:MTGCardDetection,代碼行數:7,代碼來源:ReferenceCardDatabase.cs

示例4: PackFileTransferMessageAsync

        public static async Task<byte[]> PackFileTransferMessageAsync(SongTransferMessage message)
        {
            byte[] serialized;

            using (var ms = new MemoryStream())
            {
                using (var writer = new BsonWriter(ms))
                {
                    var serializer = new JsonSerializer();

                    await Task.Run(() => serializer.Serialize(writer, message));
                }

                // Don't return earlier here, we don't know of the BsonWriter is finished.
                serialized = ms.ToArray();
            }

            byte[] length = BitConverter.GetBytes(serialized.Length); // We have a fixed size of 4 bytes

            var returnData = new byte[length.Length + serialized.Length];

            // We could simply call .ToArray() everywhere, but with Buffer.BlockCopy, we are
            // reducing memory pressure and CPU time on mobile devices by an order of magnitude
            Buffer.BlockCopy(length, 0, returnData, 0, length.Length);
            Buffer.BlockCopy(serialized, 0, returnData, length.Length, serialized.Length);

            return returnData;
        }
開發者ID:modulexcite,項目名稱:Espera.Network,代碼行數:28,代碼來源:NetworkHelpers.cs

示例5: SendCmdRequest

        public bool SendCmdRequest(CmdRequest request)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                socket.Connect("127.0.0.1", Port);
                using (NetworkStream stream = new NetworkStream(socket))
                {
                    using (BsonWriter writer = new BsonWriter(stream))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        serializer.Serialize(writer, request);
                        writer.Flush();
                        writer.Close();
                    }
                   
                    stream.Close();
                }
            }
            catch(Exception ex)
            {
                Logger.AddError(string.Format("Failed to send cmd request to checker with port = {0}", Port), ex);
                return false;
            }

            return true;
        }
開發者ID:intech,項目名稱:Checker,代碼行數:28,代碼來源:ThreadProcess.cs

示例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"]);
        }
開發者ID:AndyStewart,項目名稱:docsharp,代碼行數:29,代碼來源:BsonReaderTests.cs

示例7: OnWriteToStream

        protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context)
        {

            var serializer = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
            // NOTE: we don't dispose or close these as they would 
            // close the stream, which is used by the rest of the pipeline.
            var writer = default(JsonWriter);

            if (contentHeaders.ContentType.MediaType == "application/bson")
                writer = new BsonWriter(stream);
            else
                writer = new JsonTextWriter(new StreamWriter(stream));

            if (UsesQueryComposition)
            {
                serializer.Serialize(writer, ((IEnumerable)value).OfType<object>().ToList());
            }
            else
            {
                serializer.Serialize(writer, value);
            }

            writer.Flush();

        }
開發者ID:pullpush,項目名稱:NAd,代碼行數:25,代碼來源:NewtonsoftJsonFormatter.cs

示例8: 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());
        }
開發者ID:ngbrown,項目名稱:EasyNetQ,代碼行數:25,代碼來源:JsonNetSpike.cs

示例9: Serialize

 public override void Serialize(Stream stream, object instance)
 {
     using (var writer = new BsonWriter(stream))
     {
         base.Serialize(writer, instance);
     }
 }
開發者ID:etishor,項目名稱:SerializationTests,代碼行數:7,代碼來源:NewtonsoftBsonSerializerAdapter.cs

示例10: Serialize

 public static void Serialize(Stream stream, object instance)
 {
     using (var writer = new BsonWriter(stream))
     {
         serializer.Serialize(writer, instance);
     }
 }
開發者ID:etishor,項目名稱:TestDataGenerator,代碼行數:7,代碼來源:CatalogWithSamplesObjectsTests.cs

示例11: Serialize

		public static byte[] Serialize(object[] methodParams)
		{
			List<String> complexParams = new List<String>();
			object[] payload = new object[methodParams.Length + 1];

			//elements
			int count = 1;
			foreach (object param in methodParams)
			{
				payload[count] = param;
				complexParams.Add(param.GetType().FullName);
				count++;
			}

			//header type
			payload[0] = complexParams;

			using (MemoryStream memoryStream = new MemoryStream(4096))
			{
				using (BsonWriter bsonWriter = new BsonWriter(memoryStream))
				{
					BsonObject bson = new BsonObject();
					bson.Payload = payload;

					JsonSerializer serializer = new JsonSerializer();
					serializer.Serialize(bsonWriter, bson);
				}
				return memoryStream.ToArray();
			}
		}
開發者ID:sergiosilvajr,項目名稱:mpos,代碼行數:30,代碼來源:BsonFormatter.cs

示例12: WriteBson

    private void WriteBson(BsonWriter writer, Regex regex)
    {
      // Regular expression - The first cstring is the regex pattern, the second
      // is the regex options string. Options are identified by characters, which 
      // must be stored in alphabetical order. Valid options are 'i' for case 
      // insensitive matching, 'm' for multiline matching, 'x' for verbose mode, 
      // 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode 
      // ('.' matches everything), and 'u' to make \w, \W, etc. match unicode.

      string options = null;

      if (HasFlag(regex.Options, RegexOptions.IgnoreCase))
        options += "i";

      if (HasFlag(regex.Options, RegexOptions.Multiline))
        options += "m";

      if (HasFlag(regex.Options, RegexOptions.Singleline))
        options += "s";

      options += "u";

      if (HasFlag(regex.Options, RegexOptions.ExplicitCapture))
        options += "x";

      writer.WriteRegex(regex.ToString(), options);
    }
開發者ID:rdowdall,項目名稱:Newtonsoft.Json,代碼行數:27,代碼來源:RegexConverter.cs

示例13: OnWriteToStream

 protected override void OnWriteToStream(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext context)
 {
     var serializer = new JsonSerializer();
     using (var writer = new BsonWriter(stream.PreventClose())) {
         serializer.Serialize(writer, value);
         writer.Flush();
     }
 }
開發者ID:ChrisMissal,項目名稱:WcfWebApiContrib,代碼行數:8,代碼來源:BsonFormatter.cs

示例14: CreateBsonWriter

 /// <summary>
 /// Called during serialization to create the <see cref="BsonWriter"/>.
 /// </summary>
 /// <param name="stream">The <see cref="Stream"/> to write to.</param>
 /// <returns>The <see cref="BsonWriter"/> used during serialization.</returns>
 protected virtual BsonWriter CreateBsonWriter(Stream stream)
 {
     var bsonWriter = new BsonWriter(stream)
     {
         CloseOutput = false
     };
     return bsonWriter;
 }
開發者ID:razormad,項目名稱:ASP.NET-MVC-Boilerplate,代碼行數:13,代碼來源:BsonOutputFormatter.cs

示例15: Serialize

		public override void Serialize(Stream output, object graph)
		{
			if (graph == null)
				return;

			var writer = new BsonWriter(output) { DateTimeKindHandling = DateTimeKind.Utc };
			this.Serialize(writer, graph);
		}
開發者ID:yonglehou,項目名稱:NanoMessageBus,代碼行數:8,代碼來源:BsonSerializer.cs


注:本文中的Newtonsoft.Json.Bson.BsonWriter類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。