public static void TraceHtmlReader_v2(string file, string traceFile, bool disableScriptTreatment = false, bool useReadAttributeValue_v2 = false) { try { __srTraceHtmlReader = zFile.CreateText(traceFile); __traceJsonSettings = new JsonWriterSettings(); __traceJsonSettings.Indent = true; using (StreamReader sr = zfile.OpenText(file)) { HtmlReader_v2 htmlReader = new HtmlReader_v2(sr); htmlReader.Trace = TraceHtmlReader; htmlReader.DisableScriptTreatment = disableScriptTreatment; htmlReader.UseReadAttributeValue_v2 = useReadAttributeValue_v2; htmlReader.ReadAll(); } } finally { if (__srTraceHtmlReader != null) { __srTraceHtmlReader.Close(); __srTraceHtmlReader = null; } __traceJsonSettings = null; } }
public void TestIndentedEmptyDocument() { BsonDocument document = new BsonDocument(); var settings = new JsonWriterSettings { Indent = true }; string json = document.ToJson(settings); string expected = "{ }"; Assert.AreEqual(expected, json); }
public void TestInt64TenGen() { var document = new BsonDocument { { "a", 1L } }; var settings = new JsonWriterSettings { OutputMode = JsonOutputMode.TenGen }; var json = document.ToJson(settings); var expected = "{ 'a' : NumberLong(1) }".Replace("'", "\""); Assert.AreEqual(expected, json); }
public void TestIndentedOneElement() { BsonDocument document = new BsonDocument() { { "name", "value" } }; var settings = new JsonWriterSettings { Indent = true }; string json = document.ToJson(settings); string expected = "{\r\n \"name\" : \"value\"\r\n}"; Assert.AreEqual(expected, json); }
/// <summary> /// 导出到JSON /// </summary> /// <param name="dataList"></param> /// <param name="filename"></param> /// <param name="settings"></param> private static void ExportToJson(List<BsonDocument> dataList, string filename, JsonWriterSettings settings) { var file = new FileStream(filename, FileMode.Create); var sw = new StreamWriter(file); sw.Write(dataList.ToJson(settings)); sw.Flush(); }
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer) { //value = ObjectId.GenerateNewId(); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; JObject b = JObject.Parse(value.ToJson(jsonWriterSettings)); serializer.Serialize(writer, b); }
public void TestIndentedTwoElements() { BsonDocument document = new BsonDocument() { { "a", "x" }, { "b", "y" } }; var settings = new JsonWriterSettings { Indent = true }; string json = document.ToJson(settings); string expected = "{\r\n \"a\" : \"x\",\r\n \"b\" : \"y\"\r\n}"; Assert.AreEqual(expected, json); }
// constructors /// <summary> /// Initializes a new instance of the JsonWriter class. /// </summary> /// <param name="writer">A TextWriter.</param> /// <param name="settings">Optional JsonWriter settings.</param> public JsonWriter(TextWriter writer, JsonWriterSettings settings) : base(settings) { _textWriter = writer; _jsonWriterSettings = settings; // already frozen by base class _context = new JsonWriterContext(null, ContextType.TopLevel, ""); State = BsonWriterState.Initial; }
/// <summary> /// Initializes a new instance of the JsonWriter class. /// </summary> /// <param name="writer">A TextWriter.</param> /// <param name="settings">Optional JsonWriter settings.</param> public JsonWriter( TextWriter writer, JsonWriterSettings settings ) { this.textWriter = writer; this.settings = settings.Freeze(); context = new JsonWriterContext(null, ContextType.TopLevel, ""); state = BsonWriterState.Initial; }
public JsonTraceDataWriter(string file, FileOption option, Encoding encoding = null, JsonWriterSettings settings = null) { file = file.zRootPath(zapp.GetAppDirectory()); if (option == FileOption.IndexedFile) file = zfile.GetNewIndexedFileName(zPath.GetDirectoryName(file), zPath.GetFileName(file)); //_streamWriter = zFile.CreateText(file); Open(file, encoding, option != FileOption.RazFile); _closeStreamWriter = true; InitSettings(settings); }
// GET api/values/5 public string Get(string id) { rvService svc = new rvService(getMongoDB()); DataTableParamModel para = new DataTableParamModel(); para.sDate =Convert.ToDateTime(id); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; string rtn = svc.Read(para).ToJson(jsonWriterSettings); //rtn = "{\"data\":" + rtn + "}"; return rtn; }
// GET api/Categories/5 public async Task<string> GetAsync(string id) { MongoHelper<Category> categoryHelper = new MongoHelper<Category>(); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; Category cat = await categoryHelper.Collection .Find(c => c.Id.Equals(ObjectId.Parse(id))) // TODO filter by userId .FirstAsync(); return cat.ToJson(jsonWriterSettings); }
// GET api/Categories/5 public async Task<string> GetAsync(string id) { MongoHelper<PaymentType> paymentTypeHelper = new MongoHelper<PaymentType>(); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; PaymentType paymentType = await paymentTypeHelper.Collection .Find(p => p.Id.Equals(ObjectId.Parse(id))) // TODO filter by userId .FirstAsync(); return paymentType.ToJson(jsonWriterSettings); }
/// <summary> /// Initializes a new instance of the JsonWriter class. /// </summary> /// <param name="writer">A TextWriter.</param> /// <param name="settings">Optional JsonWriter settings.</param> public JsonWriter(TextWriter writer, JsonWriterSettings settings) : base(settings) { if (writer == null) { throw new ArgumentNullException("writer"); } _textWriter = writer; _jsonWriterSettings = settings; // already frozen by base class _context = new JsonWriterContext(null, ContextType.TopLevel, ""); State = BsonWriterState.Initial; }
/// <summary> /// Initializes a new instance of the JsonWriter class. /// </summary> /// <param name="writer">A TextWriter.</param> /// <param name="settings">Optional JsonWriter settings.</param> public JsonWriter(TextWriter writer, JsonWriterSettings settings) : base(settings) { if (writer == null) { throw new ArgumentNullException("writer"); } _textWriter = writer; _jsonWriterSettings = settings; // already frozen by base class _context = new JsonWriterContext(null, ContextType.TopLevel, ""); State = BsonWriterState.Initial; }
//Retourne les indices d'un pays donné trié par un champ par exemple le prix, le volume, market cap etc... public Dictionary<string, int> aggregateCountryNumberOfIndustrySortedDesc(string _country) { Dictionary<string, int> dictionnary = new Dictionary<string, int>(); var aggregate = collection.Aggregate() .Match(new BsonDocument { { "Country", _country } }) .Group(new BsonDocument { { "_id", new BsonDocument { { "Industry", "$Industry" } } }, { "number", new BsonDocument { { "$sum", 1 } } } }) .Sort(new BsonDocument { { "number", -1 } }).ToListAsync().Result; var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; foreach (BsonDocument bsd in aggregate) { dictionnary.Add(bsd.GetValue("_id").ToBsonDocument().GetValue("Industry").ToString(),Convert.ToInt32(bsd.GetValue("number"))); } return dictionnary; }
//Retourne les indices d'un pays donné trié par un champ par exemple le prix, le volume, market cap etc... public List<Stockobject> aggregateCountrySorted(string _country, string _sortBy, bool _asc) { int i = 0; if (_asc) i = 1; else i = -1; List<Stockobject> list = new List<Stockobject>(); var aggregate = collection.Aggregate() .Match(new BsonDocument { { "Country", _country } }) .Sort(new BsonDocument { { _sortBy, i } }).ToListAsync().Result; var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; foreach (BsonDocument bsd in aggregate) { list.Add(BsonSerializer.Deserialize<Stockobject>(bsd.ToJson())); } return list; }
// GET api/ExpenseApi public async Task<IEnumerable<string>> GetAsync() { MongoHelper<Expense> expenseHelper = new MongoHelper<Expense>(); IList<string> returnList = new List<string>(); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; await expenseHelper.Collection.Find(e => e.Value > 0) // TODO filter by userId .ForEachAsync(expenseDocument => { string docJson = expenseDocument.ToJson(jsonWriterSettings); returnList.Add(docJson); } ); return returnList.ToArray(); }
public void TestDateTime() { DateTime jan_1_2010 = new DateTime(2010, 1, 1); double expectedValue = (jan_1_2010.ToUniversalTime() - BsonConstants.UnixEpoch).TotalMilliseconds; BsonDocument document = new BsonDocument() { { "date", jan_1_2010 } }; var settings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; string json = document.ToJson(settings); string expected = "{ \"date\" : { \"$date\" : # } }".Replace("#", expectedValue.ToString()); Assert.AreEqual(expected, json); settings = new JsonWriterSettings { OutputMode = JsonOutputMode.JavaScript }; json = document.ToJson(settings); expected = "{ \"date\" : Date(#) }".Replace("#", expectedValue.ToString()); Assert.AreEqual(expected, json); }
// GET api/CategoryApi public async Task<IEnumerable<string>> GetAsync() { MongoHelper<Category> categoryHelper = new MongoHelper<Category>(); IList<string> returnList = new List<string>(); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; await categoryHelper.Collection.Find(e => e.Name != null) // TODO filter by userId .ForEachAsync(categoryDocument => { string docJson = categoryDocument.ToJson(jsonWriterSettings); returnList.Add(docJson); } ); return returnList.ToArray(); }
// protected methods /// <summary> /// Creates a clone of the settings. /// </summary> /// <returns>A clone of the settings.</returns> protected override BsonWriterSettings CloneImplementation() { var clone = new JsonWriterSettings { #pragma warning disable 618 Encoding = _encoding, #pragma warning restore GuidRepresentation = GuidRepresentation, Indent = _indent, IndentChars = _indentChars, MaxSerializationDepth = MaxSerializationDepth, NewLineChars = _newLineChars, OutputMode = _outputMode, ShellVersion = _shellVersion }; return(clone); }
// GET: api/UserProfiles public async Task<HttpResponseMessage> Get( [FromUri] string repository, [FromUri] string display_name, [FromUri] string month ) { EasyAnalysis.Framework.ConnectionStringProviders.IConnectionStringProvider mongoDBCSProvider = EasyAnalysis.Framework.ConnectionStringProviders.ConnectionStringProvider.CreateConnectionStringProvider(EasyAnalysis.Framework.ConnectionStringProviders.ConnectionStringProvider.ConnectionStringProviderType.MongoDBConnectionStringProvider); var client = new MongoClient(mongoDBCSProvider.GetConnectionString(repository)); var database = client.GetDatabase(repository); var userProfiles = database.GetCollection<BsonDocument>("asker_activities"); var builder = Builders<BsonDocument>.Filter; FilterDefinition<BsonDocument> filter = "{}"; if (!string.IsNullOrEmpty(display_name)) { filter = filter & builder.Regex("display_name", BsonRegularExpression.Create(new Regex("^" + display_name, RegexOptions.IgnoreCase))); } if (!string.IsNullOrEmpty(month)) { filter = filter & builder.Eq("month", month); } var result = await userProfiles .Find(filter) .Sort("{ total: -1 }") .ToListAsync(); var response = Request.CreateResponse(); response.StatusCode = HttpStatusCode.OK; var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; response.Content = new StringContent(result.ToJson(jsonWriterSettings), Encoding.UTF8, "application/json"); return response; }
public static void Test_BsonWriter_01() { string bsonFile = @"c:\pib\dev_data\exe\runsource\test\bson.txt"; StreamWriter sw = null; BsonWriter bsonWriter = null; try { sw = zFile.CreateText(bsonFile); JsonWriterSettings jsonSettings = new JsonWriterSettings(); jsonSettings.Indent = true; //jsonSettings.NewLineChars = "\r\n"; //jsonSettings.OutputMode = JsonOutputMode.Shell; bsonWriter = JsonWriter.Create(sw, jsonSettings); //bsonWriter.WriteString("test"); bsonWriter.WriteStartDocument(); bsonWriter.WriteString("test", "test"); bsonWriter.WriteEndDocument(); sw.WriteLine(); bsonWriter.WriteName("test"); // ??? pour éviter l'erreur : WriteString can only be called when State is Value or Initial, not when State is Name (System.InvalidOperationException) bsonWriter.WriteStartDocument(); bsonWriter.WriteString("test", "test"); bsonWriter.WriteEndDocument(); sw.WriteLine(); bsonWriter.WriteName("test"); bsonWriter.WriteString("test"); sw.WriteLine(); bsonWriter.WriteName("test"); bsonWriter.WriteNull(); sw.WriteLine(); } finally { if (bsonWriter != null) bsonWriter.Close(); if (sw != null) sw.Close(); } }
/// <summary> /// Creates a JsonWriter for this encoder. /// </summary> /// <returns>A JsonWriter.</returns> public JsonWriter CreateJsonWriter() { if (_textWriter == null) { throw new InvalidOperationException("No TextWriter was provided."); } var writerSettings = new JsonWriterSettings(); if (_encoderSettings != null) { writerSettings.GuidRepresentation = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.GuidRepresentation, GuidRepresentation.CSharpLegacy); writerSettings.Indent = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.Indent, false); writerSettings.IndentChars = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.IndentChars, ""); writerSettings.MaxSerializationDepth = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.MaxSerializationDepth, BsonDefaults.MaxSerializationDepth); writerSettings.NewLineChars = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.NewLineChars, ""); writerSettings.OutputMode = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.OutputMode, JsonOutputMode.Shell); writerSettings.ShellVersion = _encoderSettings.GetOrDefault(MessageEncoderSettingsName.ShellVersion, new Version(2, 6, 0)); } return new JsonWriter(_textWriter, writerSettings); }
public static MessageJsonModel GetJson(BsonDocument document) { if (document == null) return new MessageJsonModel(); var sett = new JsonWriterSettings(); sett.Indent = true; var evntBson = document; var metadata = evntBson.GetBsonDocument("Metadata"); evntBson.Remove("Metadata"); evntBson.Remove("_t"); metadata.Remove("_t"); return new MessageJsonModel() { Message = evntBson.ToJson(sett), Metadata = metadata.ToJson(sett) }; }
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowIndex > -1) { if (((Account)e.Row.DataItem).status == "Blocked") { e.Row.Cells[1].ForeColor = System.Drawing.Color.Red; } e.Row.Cells[2].Text = ((Account)e.Row.DataItem).pwd.Substring(0, 2) + "..."; if (((Account)e.Row.DataItem).purchase.pdate.Date.ToString("yyyyMMdd")=="10000101") e.Row.Cells[3].Text = ""; else e.Row.Cells[3].Text = Convert.ToDateTime(((Account)e.Row.DataItem).purchase.pdate, new CultureInfo("zh-TW")).ToString("yyyy/MM/dd HH:mm:ss"); e.Row.Cells[4].Text = ((Account)e.Row.DataItem).purchase.pitem; e.Row.Cells[5].Text = ((Account)e.Row.DataItem).purchase.ptel; string _card = ((Account)e.Row.DataItem).purchase.pcardno; if (_card.Length <= 3) { HyperLink lnk = new HyperLink(); lnk.Text = _card; lnk.Attributes.Add("onclick", "openCardInfo('" + _card + "','" + cardJson + "')"); lnk.NavigateUrl = "#"; e.Row.Cells[6].Controls.Add(lnk); } else e.Row.Cells[6].Text = _card; HyperLink hl = new HyperLink(); hl.Text = ((Account)e.Row.DataItem).review.Count.ToString(); if (((Account)e.Row.DataItem).review.Count > 0) { //hl.Attributes.Add("rvdata", ((Account)e.Row.DataItem).review.ToJson()); var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; hl.Attributes.Add("onclick", "openReview('" + ((Account)e.Row.DataItem).email + "','" + ((Account)e.Row.DataItem).review.ToJson(jsonWriterSettings) + "')"); hl.NavigateUrl = "#"; } e.Row.Cells[7].Controls.Add(hl); e.Row.Cells[8].Text = ((Account)e.Row.DataItem).vpn; } }
private static void Main(string[] args) { var settings = new JsonWriterSettings { Indent = true }; // Its XML Time using (var strm = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.SomeXml.xml")) { var xmlDocument = new XmlDocument(); xmlDocument.Load(strm); Console.Write("XML: "); Console.WriteLine(xmlDocument.OuterXml); Console.WriteLine(); Console.Write("XML2JSON: "); Console.WriteLine(xmlDocument.DocumentElement.ToBsonDocument().ToJson(settings)); Console.WriteLine(); } Console.WriteLine("Press Any Key To Continue . . ."); Console.ReadKey(true); }
// GET: api/DupDetection public async Task<HttpResponseMessage> Get( [FromUri] string repository) { var client = new MongoClient("mongodb://app-svr.cloudapp.net:27017/" + repository); var database = client.GetDatabase(repository); var dupDetection = database.GetCollection<BsonDocument>("dup_detection"); var result = await dupDetection .Find("{}") .Sort("{percentage: -1}") .ToListAsync(); var response = Request.CreateResponse(); response.StatusCode = HttpStatusCode.OK; var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; response.Content = new StringContent(result.ToJson(jsonWriterSettings), Encoding.UTF8, "application/json"); return response; }
/// <summary> /// Creates a BsonWriter to a JSON TextWriter. /// </summary> /// <param name="writer">A TextWriter.</param> /// <param name="settings">Optional JsonWriterSettings.</param> /// <returns>A BsonWriter.</returns> public static BsonWriter Create(TextWriter writer, JsonWriterSettings settings) { return new JsonWriter(writer, settings); }
/// <summary> /// forSeller와 통신하기 위해 클래스를 Json형식으로 변환후 Base64로 인코딩한다. /// </summary> /// <param name="data">포셀러에 전송하기 위한 다이나믹 클래스</param> /// <returns></returns> private string CreateJsonData(eBayItemsData data) { JsonWriterSettings jset = new JsonWriterSettings(); jset.OutputMode = JsonOutputMode.JavaScript; return Util.EncodeTo64(data.dynamicData.ToJson<eBayItemsDataForSeller>(jset)); // base64(json)로 데이터 생성 }
// protected methods /// <summary> /// Creates a clone of the settings. /// </summary> /// <returns>A clone of the settings.</returns> protected override BsonWriterSettings CloneImplementation() { var clone = new JsonWriterSettings { #pragma warning disable 618 Encoding = _encoding, #pragma warning restore GuidRepresentation = GuidRepresentation, Indent = _indent, IndentChars = _indentChars, MaxSerializationDepth = MaxSerializationDepth, NewLineChars = _newLineChars, OutputMode = _outputMode, ShellVersion = _shellVersion }; return clone; }
public void TestRegularExpressionStrict() { var json = "{ \"$regex\" : \"pattern\", \"$options\" : \"imxs\" }"; using (bsonReader = BsonReader.Create(json)) { Assert.AreEqual(BsonType.RegularExpression, bsonReader.ReadBsonType()); string pattern, options; bsonReader.ReadRegularExpression(out pattern, out options); Assert.AreEqual("pattern", pattern); Assert.AreEqual("imxs", options); Assert.AreEqual(BsonReaderState.Done, bsonReader.State); } var settings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; Assert.AreEqual(json, BsonSerializer.Deserialize<BsonRegularExpression>(new StringReader(json)).ToJson(settings)); }
/// <summary> /// Creates a BsonWriter to a JSON TextWriter. /// </summary> /// <param name="writer">A TextWriter.</param> /// <param name="settings">Optional JsonWriterSettings.</param> /// <returns>A BsonWriter.</returns> public static BsonWriter Create(TextWriter writer, JsonWriterSettings settings) { return(new JsonWriter(writer, settings)); }
protected void Page_Load(object sender, EventArgs e) { var connectionString = System.Configuration.ConfigurationSettings.AppSettings["MongoConnectStr"].ToString(); var client = new MongoClient(connectionString); var db = client.GetDatabase("mydb"); var collection = db.GetCollection <BsonDocument>("bar"); JObject j = new JObject(); BsonDocument b = new BsonDocument(); b["iiid"] = 1; b["CreateTime"] = DateTime.Now; b["buer"] = true; // collection.InsertOne(new BsonDocument(b)); // var jc = BsonJavaScript.Create(""); List <BsonDocument> list = collection.Find(BsonDocument.Parse("{iiid:2}")).ToList(); foreach (BsonDocument item in list) { var iii = item.ToJson(); var str1 = item["_id"].ToString(); } MongoDB.Bson.IO.JsonWriterSettings st = new MongoDB.Bson.IO.JsonWriterSettings(); st.GuidRepresentation = GuidRepresentation.Standard; st.Indent = true; st.OutputMode = JsonOutputMode.Strict; BsonSerializationArgs args = default(BsonSerializationArgs); args.SerializeAsNominalType = true; args.SerializeIdFirst = true; Action <BsonSerializationContext.Builder> configurator; list.ToJson(st, null, null, args); string str = list.ToJson(); // JsonData jj = JsonMapper.ToObject("{OrderId:" + OrderId + "}"); // string str="[{ "_id" : ObjectId("5854a625d77f05e25ca56f33"), "Name" : "Jack" }, { "_id" : ObjectId("5854a629d77f05e25ca56f34"), "Name" : "Jack" }, { "_id" : ObjectId("5854a62ad77f05e25ca56f35"), "Name" : "Jack" }, { "_id" : ObjectId("5854a752d77f06e25cbc794c"), "test" : 1, "name" : "测试" }, { "_id" : ObjectId("5854a7a6d77f07e25cef3b19"), "test" : 1, "name" : "测试", "testJson" : { "二级测试" : "二级测试", "二级测试2" : "二级测试2" } }]" var js = new JsonSerializerSettings(); JArray JArrayObj = (JArray)Newtonsoft.Json.JsonConvert.DeserializeObject(list.ToJson()); Response.Write(JArrayObj.ToString()); Response.End(); }