本文整理汇总了C#中Raven.Imports.Newtonsoft.Json.JsonTextWriter类的典型用法代码示例。如果您正苦于以下问题:C# JsonTextWriter类的具体用法?C# JsonTextWriter怎么用?C# JsonTextWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JsonTextWriter类属于Raven.Imports.Newtonsoft.Json命名空间,在下文中一共展示了JsonTextWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Execute
public override void Execute(object parameter)
{
var saveFile = new SaveFileDialog
{
DefaultFileName = string.Format("Dump of {0}, {1}", ApplicationModel.Database.Value.Name, DateTimeOffset.Now.ToString("MMM dd yyyy HH-mm", CultureInfo.InvariantCulture)),
DefaultExt = ".raven.dump",
Filter = "Raven Dumps|*.raven.dump",
};
if (saveFile.ShowDialog() != true)
return;
stream = saveFile.OpenFile();
gZipStream = new GZipStream(stream, CompressionMode.Compress);
streamWriter = new StreamWriter(gZipStream);
jsonWriter = new JsonTextWriter(streamWriter)
{
Formatting = Formatting.Indented
};
taskModel.TaskStatus = TaskStatus.Started;
output(String.Format("Exporting to {0}", saveFile.SafeFileName));
output("Begin reading indexes");
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("Indexes");
jsonWriter.WriteStartArray();
ReadIndexes(0)
.Catch(exception => Infrastructure.Execute.OnTheUI(() => Finish(exception)));
}
示例2: ToJson
public static string ToJson(object obj, bool format=false)
{
if(format)
{
JsonSerializer serializer = new JsonSerializer();
StringBuilder sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
using(var jsonWriter = new JsonTextWriter(writer) { Formatting=Formatting.Indented })
{
serializer.Serialize(jsonWriter, obj);
return sb.ToString();
}
}
}
else
{
JsonSerializer serializer = new JsonSerializer();
StringBuilder sb = new StringBuilder();
using(var writer = new StringWriter(sb))
{
serializer.Serialize(writer, obj);
return sb.ToString();
}
}
}
示例3: ExportAttachments
protected override async Task<Etag> ExportAttachments(JsonTextWriter jsonWriter, Etag lastEtag)
{
var totalCount = 0;
while (true)
{
var array = GetAttachments(totalCount, lastEtag);
if (array.Length == 0)
{
var databaseStatistics = await GetStats();
if (lastEtag == null) lastEtag = Etag.Empty;
if (lastEtag.CompareTo(databaseStatistics.LastAttachmentEtag) < 0)
{
lastEtag = EtagUtil.Increment(lastEtag, SmugglerOptions.BatchSize);
ShowProgress("Got no results but didn't get to the last attachment etag, trying from: {0}", lastEtag);
continue;
}
ShowProgress("Done with reading attachments, total: {0}", totalCount);
return lastEtag;
}
totalCount += array.Length;
ShowProgress("Reading batch of {0,3} attachments, read so far: {1,10:#,#;;0}", array.Length, totalCount);
foreach (var item in array)
{
item.WriteTo(jsonWriter);
}
lastEtag = Etag.Parse(array.Last().Value<string>("Etag"));
}
}
示例4: StreamToClient
private void StreamToClient(Stream stream, int pageSize, Etag etag)
{
using (var cts = new CancellationTokenSource())
using (var timeout = cts.TimeoutAfter(FileSystemsLandlord.SystemConfiguration.DatabaseOperationTimeout))
using (var writer = new JsonTextWriter(new StreamWriter(stream)))
{
writer.WriteStartObject();
writer.WritePropertyName("Results");
writer.WriteStartArray();
Storage.Batch(accessor =>
{
var files = accessor.GetFilesAfter(etag, pageSize);
foreach (var file in files)
{
timeout.Delay();
var doc = RavenJObject.FromObject(file);
doc.WriteTo(writer);
writer.WriteRaw(Environment.NewLine);
}
});
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();
}
}
示例5: ValueFormatting
public void ValueFormatting()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.WriteStartArray();
jsonWriter.WriteValue('@');
jsonWriter.WriteValue("\r\n\t\f\b?{\\r\\n\"\'");
jsonWriter.WriteValue(true);
jsonWriter.WriteValue(10);
jsonWriter.WriteValue(10.99);
jsonWriter.WriteValue(0.99);
jsonWriter.WriteValue(0.000000000000000001d);
jsonWriter.WriteValue(0.000000000000000001m);
jsonWriter.WriteValue((string)null);
jsonWriter.WriteValue((object)null);
jsonWriter.WriteValue("This is a string.");
jsonWriter.WriteNull();
jsonWriter.WriteUndefined();
jsonWriter.WriteEndArray();
}
string expected = @"[""@"",""\r\n\t\f\b?{\\r\\n\""'"",true,10,10.99,0.99,1E-18,0.000000000000000001,null,null,""This is a string."",null,undefined]";
string result = sb.ToString();
Console.WriteLine("ValueFormatting");
Console.WriteLine(result);
Assert.AreEqual(expected, result);
}
示例6: WriteDocuments
private void WriteDocuments(JsonTextWriter jsonWriter)
{
long totalDococCount = 0;
long currentDocsCount = 0;
Etag currLastEtag = Etag.Empty;
storage.Batch(accsesor => totalDococCount = accsesor.Documents.GetDocumentsCount());
try
{
CancellationToken ct = new CancellationToken();
do
{
storage.Batch(accsesor =>
{
var docs = accsesor.Documents.GetDocumentsAfter(currLastEtag, BatchSize, ct);
foreach (var doc in docs)
{
doc.ToJson(true).WriteTo(jsonWriter);
}
currLastEtag = docs.Last().Etag;
currentDocsCount += docs.Count();
ReportProgress("documents", currentDocsCount, totalDococCount);
});
} while (totalDococCount > currentDocsCount);
}
catch (Exception e)
{
ConsoleUtils.PrintErrorAndFail("Failed to export documents, error:" + e.Message);
}
}
示例7: ExportAttachments
protected override Task<Etag> ExportAttachments(RavenConnectionStringOptions src, JsonTextWriter jsonWriter, Etag lastEtag, Etag maxEtag)
{
if (maxEtag != null)
throw new ArgumentException("We don't support maxEtag in SmugglerDatabaseApi", maxEtag);
return base.ExportAttachments(src, jsonWriter, lastEtag, null);
}
示例8: StreamToClient
private void StreamToClient(Stream stream, int pageSize, Etag etag, OrderedPartCollection<AbstractFileReadTrigger> readTriggers)
{
using (var cts = new CancellationTokenSource())
using (var timeout = cts.TimeoutAfter(FileSystemsLandlord.SystemConfiguration.DatabaseOperationTimeout))
using (var writer = new JsonTextWriter(new StreamWriter(stream)))
{
writer.WriteStartObject();
writer.WritePropertyName("Results");
writer.WriteStartArray();
Storage.Batch(accessor =>
{
var files = accessor.GetFilesAfter(etag, pageSize);
foreach (var file in files)
{
if (readTriggers.CanReadFile(file.FullPath, file.Metadata, ReadOperation.Load) == false)
continue;
timeout.Delay();
var doc = RavenJObject.FromObject(file);
doc.WriteTo(writer);
writer.WriteRaw(Environment.NewLine);
}
});
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();
}
}
示例9: Serialize
public virtual void Serialize(Stream stream, object instance)
{
using (var streamWriter = new StreamWriter(stream, Encoding.UTF8))
using (var jsonWriter = new JsonTextWriter(streamWriter))
{
RavenJToken.FromObject(instance, this.serializer).WriteTo(jsonWriter);
}
}
示例10: WriteIConvertable
public void WriteIConvertable()
{
var sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.WriteValue(new ConvertibleInt(1));
Assert.AreEqual("1", sw.ToString());
}
示例11: Execute
public override void Execute(object parameter)
{
TaskCheckBox attachmentUI = taskModel.TaskInputs.FirstOrDefault(x => x.Name == "Include Attachments") as TaskCheckBox;
includeAttachments = attachmentUI != null && attachmentUI.Value;
var saveFile = new SaveFileDialog
{
DefaultExt = ".ravendump",
Filter = "Raven Dumps|*.ravendump;*.raven.dump",
};
var name = ApplicationModel.Database.Value.Name;
var normalizedName = new string(name.Select(ch => Path.GetInvalidPathChars().Contains(ch) ? '_' : ch).ToArray());
var defaultFileName = string.Format("Dump of {0}, {1}", normalizedName, DateTimeOffset.Now.ToString("dd MMM yyyy HH-mm", CultureInfo.InvariantCulture));
try
{
saveFile.DefaultFileName = defaultFileName;
}
catch { }
if (saveFile.ShowDialog() != true)
return;
taskModel.CanExecute.Value = false;
stream = saveFile.OpenFile();
gZipStream = new GZipStream(stream, CompressionMode.Compress);
streamWriter = new StreamWriter(gZipStream);
jsonWriter = new JsonTextWriter(streamWriter)
{
Formatting = Formatting.Indented
};
taskModel.TaskStatus = TaskStatus.Started;
output(String.Format("Exporting to {0}", saveFile.SafeFileName));
jsonWriter.WriteStartObject();
Action finalized = () =>
{
jsonWriter.WriteEndObject();
Infrastructure.Execute.OnTheUI(() => Finish(null));
};
Action readAttachments = () => ReadAttachments(Guid.Empty, 0, callback: finalized);
Action readDocuments = () => ReadDocuments(Guid.Empty, 0, callback: includeAttachments ? readAttachments : finalized);
try
{
ReadIndexes(0, callback: readDocuments);
}
catch (Exception ex)
{
taskModel.ReportError(ex);
Infrastructure.Execute.OnTheUI(() => Finish(ex));
}
}
示例12: ExportDeletions
/// <summary>
///
/// </summary>
/// <param name="jsonWriter"></param>
/// <param name="options"></param>
/// <param name="result"></param>
/// <param name="maxEtags">Max etags are inclusive</param>
protected async override void ExportDeletions(JsonTextWriter jsonWriter, SmugglerOptions options, ExportDataResult result, LastEtagsInfo maxEtags)
{
jsonWriter.WritePropertyName("DocsDeletions");
jsonWriter.WriteStartArray();
result.LastDocDeleteEtag = await ExportDocumentsDeletion(options, jsonWriter, result.LastDocDeleteEtag, maxEtags.LastDocDeleteEtag.IncrementBy(1));
jsonWriter.WriteEndArray();
jsonWriter.WritePropertyName("AttachmentsDeletions");
jsonWriter.WriteStartArray();
result.LastAttachmentsDeleteEtag = await ExportAttachmentsDeletion(options, jsonWriter, result.LastAttachmentsDeleteEtag, maxEtags.LastAttachmentsDeleteEtag.IncrementBy(1));
jsonWriter.WriteEndArray();
}
示例13: ExportDeletions
public override async Task ExportDeletions(JsonTextWriter jsonWriter, ExportDataResult result, LastEtagsInfo maxEtagsToFetch)
{
jsonWriter.WritePropertyName("DocsDeletions");
jsonWriter.WriteStartArray();
result.LastDocDeleteEtag = await Operations.ExportDocumentsDeletion(jsonWriter, result.LastDocDeleteEtag, maxEtagsToFetch.LastDocDeleteEtag.IncrementBy(1));
jsonWriter.WriteEndArray();
jsonWriter.WritePropertyName("AttachmentsDeletions");
jsonWriter.WriteStartArray();
result.LastAttachmentsDeleteEtag = await Operations.ExportAttachmentsDeletion(jsonWriter, result.LastAttachmentsDeleteEtag, maxEtagsToFetch.LastAttachmentsDeleteEtag.IncrementBy(1));
jsonWriter.WriteEndArray();
}
示例14: ExportAttachments
protected override async Task<Etag> ExportAttachments(JsonTextWriter jsonWriter, Etag lastEtag)
{
int totalCount = 0;
while (true)
{
RavenJArray attachmentInfo = null;
await commands.CreateRequest("/static/?pageSize=" + SmugglerOptions.BatchSize + "&etag=" + lastEtag, "GET")
.ReadResponseJsonAsync()
.ContinueWith(task => attachmentInfo = (RavenJArray) task.Result);
if (attachmentInfo.Length == 0)
{
var databaseStatistics = await GetStats();
var lastEtagComparable = new ComparableByteArray(lastEtag);
if (lastEtagComparable.CompareTo(databaseStatistics.LastAttachmentEtag) < 0)
{
lastEtag = EtagUtil.Increment(lastEtag, SmugglerOptions.BatchSize);
ShowProgress("Got no results but didn't get to the last attachment etag, trying from: {0}", lastEtag);
continue;
}
ShowProgress("Done with reading attachments, total: {0}", totalCount);
return lastEtag;
}
totalCount += attachmentInfo.Length;
ShowProgress("Reading batch of {0,3} attachments, read so far: {1,10:#,#;;0}", attachmentInfo.Length, totalCount);
foreach (var item in attachmentInfo)
{
ShowProgress("Downloading attachment: {0}", item.Value<string>("Key"));
byte[] attachmentData = null;
await commands.CreateRequest("/static/" + item.Value<string>("Key"), "GET")
.ReadResponseBytesAsync()
.ContinueWith(task => attachmentData = task.Result);
new RavenJObject
{
{"Data", attachmentData},
{"Metadata", item.Value<RavenJObject>("Metadata")},
{"Key", item.Value<string>("Key")}
}
.WriteTo(jsonWriter);
}
lastEtag = Etag.Parse(attachmentInfo.Last().Value<string>("Etag"));
}
}
示例15: Respond
public override void Respond(IHttpContext context)
{
using (context.Response.Streaming())
{
context.Response.ContentType = "application/json; charset=utf-8";
using (var writer = new JsonTextWriter(new StreamWriter(context.Response.OutputStream)))
{
writer.WriteStartObject();
writer.WritePropertyName("Results");
writer.WriteStartArray();
Database.TransactionalStorage.Batch(accessor =>
{
var startsWith = context.Request.QueryString["startsWith"];
int pageSize = context.GetPageSize(int.MaxValue);
if (string.IsNullOrEmpty(context.Request.QueryString["pageSize"]))
pageSize = int.MaxValue;
// we may be sending a LOT of documents to the user, and most
// of them aren't going to be relevant for other ops, so we are going to skip
// the cache for that, to avoid filling it up very quickly
using (DocumentCacher.SkipSettingDocumentsInDocumentCache())
{
if (string.IsNullOrEmpty(startsWith))
{
Database.GetDocuments(context.GetStart(), pageSize, context.GetEtagFromQueryString(),
doc => doc.WriteTo(writer));
}
else
{
Database.GetDocumentsWithIdStartingWith(
startsWith,
context.Request.QueryString["matches"],
context.Request.QueryString["exclude"],
context.GetStart(),
pageSize,
doc => doc.WriteTo(writer));
}
}
});
writer.WriteEndArray();
writer.WriteEndObject();
writer.Flush();
}
}
}