public async Task Update(DocumentModel model) { if (Disposed) { throw new ObjectDisposedException(nameof(model)); } var entry = await _index.Get(model.Id); var oldModel = _documentSerializer.Deserialize(_records.Find(entry.Item2)); _records.Update(entry.Item2, _documentSerializer.Serialize(model)); var oldDict = _indexingOperations.CreateIndexes(oldModel.Value, oldModel).Result; foreach (var(k, v) in oldDict) { await _secondaryIndex.Delete(k, v); } var dict = await _indexingOperations.CreateIndexes(model.Value, model); foreach (var(k, v) in dict) { await _secondaryIndex.Insert(k, v); } }
// TDeserialize can be : InheritedCommandResult<TResult>, DocumentInheritedCommandResult<TResult> // method should be used when TResult can be change tracked public async Task <ICommandResult <TResult> > RequestGenericSingleResult <TResult, TDeserialize>(object data = null) where TDeserialize : new() { var response = await SendCommandAsync(data).ConfigureAwait(false); ICommandResult <TResult> result = null; using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { var serializer = new DocumentSerializer(db); if (EnableChangeTracking) { result = new TDeserialize() as ICommandResult <TResult>; BaseResult baseResult = null; result.Result = serializer.DeserializeSingleResult <TResult>(stream, out baseResult); result.BaseResult = baseResult; } else { result = serializer.Deserialize <TDeserialize>(stream) as ICommandResult <TResult>; } } new BaseResultAnalyzer(db).ThrowIfNeeded(result.BaseResult); return(result); }
public ViewResult <T> DeserializeList <T>(string json) { if (string.IsNullOrEmpty(json)) { return(new ViewResult <T>()); } var type = typeof(T); var viewType = typeof(ViewResult <T>); ViewResult <T> viewResult = null; using (var reader = new StringReader(json)) viewResult = (ViewResult <T>)DocumentSerializer.Deserialize(reader, viewType); using (var reader = new StringReader(json)) if (!type.IsInstanceOfType(typeof(BaseDocument))) { var metadataView = (ViewResult <DocumentMetadata>) MetadataSerialzier.Deserialize(reader, typeof(ViewResult <DocumentMetadata>)); for (int i = 0; i < viewResult.Rows.Length; i++) { var metadata = metadataView.Rows[i]; var document = viewResult.Rows[i]; var key = KeyAccessor.GetId(document.Model, type); MetadataProvider.SetMetadata(key, metadata.Model); } } return(viewResult); }
public async Task ReceiveHugeEnvelopeWithoutCorruptingChars() { var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory); var content = File.ReadAllLines(Path.Combine(path, "builder.txt")); var serializer = new DocumentSerializer(new DocumentTypeResolver().WithMessagingDocuments()); var envelope = serializer.Deserialize(string.Join("", content), MediaType.ApplicationJson); var count = 50; Parallel.For(0, count, async(x) => { await _clientTransport.SendAsync(new Command { Id = x.ToString(), Resource = envelope, To = "*****@*****.**" }, _cancellationToken); }); for (int i = 0; i < count; i++) { var response = await _serverTransport.ReceiveAsync(_cancellationToken); var json = JsonConvert.SerializeObject(((Command)response).Resource); json.ShouldNotContain("�"); } }
private UpdateResult UpdateDocuments(IEnumerable <TDocument> documents, UpdateDefinition <TDocument> update) { var matchedCount = 0; var modifiedCount = 0; var bsobUpdate = update.Render(DocumentSerializer, Settings.SerializerRegistry).AsBsonDocument; foreach (var docObject in documents) { var docIndex = docObjects.IndexOf(docObject); if (docIndex == -1) { throw new InvalidOperationException(); } var doc = docs[docIndex]; var docId = GetDocumentIdValue(doc); var updatedDoc = doc.DeepClone().AsBsonDocument; foreach (var updateElement in bsobUpdate) { var operationName = updateElement.Name; switch (operationName) { case "$set": { var setDoc = updateElement.Value.AsBsonDocument; updatedDoc = updatedDoc.Merge(setDoc, true); modifiedCount += setDoc.ElementCount; break; } default: throw new NotSupportedException($"Not supported update operation {operationName}."); } } var updatedId = GetDocumentIdValue(updatedDoc); using (var bsonReader = new BsonDocumentReader(updatedDoc)) { var bsonDeserializationContext = BsonDeserializationContext.CreateRoot(bsonReader); var updatedDocObject = DocumentSerializer.Deserialize(bsonDeserializationContext); docObjects[docIndex] = updatedDocObject; } if (updatedId != docId) { if (!docIds.Remove(docId)) { throw new InvalidOperationException(); } docIds.Add(updatedId, docIndex); } matchedCount++; } return(new UpdateResult.Acknowledged(matchedCount, modifiedCount, null)); }
// T can be any type // method should be used when base result is provided on server errors public async Task <ICommandResult <T> > RequestDistinctResult <T>(object data = null, Func <StreamWriter, Task> onStreamReady = null, bool?throwForServerErrors = null) { DistinctCommandResult <T> result = new DistinctCommandResult <T>(); HttpResponseMessage response = null; if (onStreamReady == null) { response = await SendCommandAsync(data).ConfigureAwait(false); } else { response = await SendStreamCommandAsync(onStreamReady).ConfigureAwait(false); } var serializer = new DocumentSerializer(db); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { if (EnableChangeTracking) { JObject jObject = null; result.Result = response.IsSuccessStatusCode ? serializer.DeserializeSingleResult <T>(stream, out jObject) : default(T); if (response.IsSuccessStatusCode) { db.ChangeTracker.TrackChanges(result.Result, jObject); } } else { result.Result = response.IsSuccessStatusCode ? serializer.Deserialize <T>(stream) : default(T); } // response has not BaseResult if If-None-Match point to a match revision (status: HttpStatusCode.NotModified) result.BaseResult = response.IsSuccessStatusCode == false && response.StatusCode != HttpStatusCode.NotModified ? serializer.Deserialize <BaseResult>(stream) : new BaseResult(); } if (throwForServerErrors.HasValue == false || throwForServerErrors.Value == true) { new BaseResultAnalyzer(db).ThrowIfNeeded(result.BaseResult); } return(result); }
public void DocumentTest3() { var a = new TestStruct { a = 3, b = "testString" }; var doc = DocumentSerializer.Serialize(a); var a_deserialized = DocumentSerializer.Deserialize <TestStruct>(doc); }
public void ВщсгьутеDictionaryTest() { var a = new DictionaryClass(); a.SetValues(); var serializedData = DocumentSerializer.Serialize(a); var a1 = DocumentSerializer.Deserialize <DictionaryClass>(serializedData); }
async Task <bool> SetCurrent() { while (readerState.ReadNextProperty(jsonTextReader)) { readerState.ReadNextPropertyValue(jsonTextReader); CursorResult.SetFromJsonTextReader(readerState.PropertyName, readerState.Token, readerState.Value); } if (jsonTextReader.TokenType == JsonToken.EndObject) { new BaseResultAnalyzer(db).ThrowIfNeeded(CursorResult); if (db.Setting.ThrowForServerErrors == false && CursorResult.HasError()) { return(false); } } if (readerState.ReadNextArrayValue(jsonTextReader)) { var documentSerializer = new DocumentSerializer(db); if (db.Setting.DisableChangeTracking == true || jsonTextReader.TokenType != JsonToken.StartObject) { Current = documentSerializer.Deserialize <T>(jsonTextReader); } else { JObject jObject = null; Current = documentSerializer.DeserializeSingleResult <T>(jsonTextReader, out jObject); db.ChangeTracker.TrackChanges(Current, jObject); } return(true); } else { while (readerState.ReadNextProperty(jsonTextReader)) { readerState.ReadNextPropertyValue(jsonTextReader); CursorResult.SetFromJsonTextReader(readerState.PropertyName, readerState.Token, readerState.Value); } if (CursorResult.HasMore) { Dispose(); await MakeNextRequest().ConfigureAwait(false); readerState.InitiateRead(jsonTextReader); return(await SetCurrent().ConfigureAwait(false)); } else { Dispose(); return(false); } } }
public void DocumentTest1() { var a = new TestClassA(); a.SetValues(); var doc = DocumentSerializer.Serialize(a); var b = DocumentSerializer.Deserialize <TestClassA>(doc); }
public void DocumentTest2() { var a = new DerivedA(); a.SetValues(); var doc = DocumentSerializer.Serialize(a); var b = DocumentSerializer.Deserialize <Interface>(doc); }
// T can be any type // method should be used when base result is provided on server errors public async Task <ICommandResult <T> > RequestDistinctResult <T>(object data = null, Func <StreamWriter, Task> onStreamReady = null) { DistinctCommandResult <T> result = new DistinctCommandResult <T>(); HttpResponseMessage response = null; if (onStreamReady == null) { response = await SendCommandAsync(data).ConfigureAwait(false); } else { response = await SendStreamCommandAsync(onStreamReady).ConfigureAwait(false); } var serializer = new DocumentSerializer(db); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { if (EnableChangeTracking) { JObject jObject = null; result.Result = response.IsSuccessStatusCode ? serializer.DeserializeSingleResult <T>(stream, out jObject) : default(T); if (response.IsSuccessStatusCode) { db.ChangeTracker.TrackChanges(result.Result, jObject); } } else { result.Result = response.IsSuccessStatusCode ? serializer.Deserialize <T>(stream) : default(T); } result.BaseResult = !response.IsSuccessStatusCode ? serializer.Deserialize <BaseResult>(stream) : new BaseResult { Code = (int)response.StatusCode }; } new BaseResultAnalyzer(db).ThrowIfNeeded(result.BaseResult); return(result); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var jObject = JObject.Load(reader); return(new Message { Id = jObject["id"].ToString(), Type = jObject["type"].ToString(), Content = _serializer.Deserialize(jObject["content"].ToString(), MediaType.Parse(jObject["type"].ToString())) }); }
public async Task <Document> ReplaceVariablesInDocumentAsync(Document source, UserContext userContext) { var documentSerialized = _serializer.Serialize(source); var replaced = await ReplaceVariablesInStringAsync(documentSerialized, userContext); if (replaced != documentSerialized) { return(_serializer.Deserialize(replaced, source.GetMediaType())); } return(source); }
// T can be any type that derived from BaseResult and results are not change tracked // method could be used if we dont want to change track T here public async Task <ICommandResult <T> > RequestMergedResult <T>(object data = null) { DistinctCommandResult <T> result = new DistinctCommandResult <T>(); var response = await SendCommandAsync(data).ConfigureAwait(false); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { var serializer = new DocumentSerializer(db); result.Result = serializer.Deserialize <T>(stream); result.BaseResult = result.Result as BaseResult; } new BaseResultAnalyzer(db).ThrowIfNeeded(result.BaseResult); return(result); }
public async Task <TypeRelationshipDocument> AnalyzeInheritanceAsync(string assemblyLocation, bool ignoreDotNetTypes, TypeDescriptor typeToAnalyse, CancellationToken cancellationToken) { var msg = new GetInheritanceGraphMessage { IgnoreDotNetTypes = ignoreDotNetTypes, AssemblyLocation = assemblyLocation, TypeToAnalyze = typeToAnalyse }; var response = await this.ProcessAsync(typeof(InheritanceActor), msg, cancellationToken); if (response is InheritanceGraphMessage m) { var serializer = new DocumentSerializer(); return(serializer.Deserialize <TypeRelationshipDocument>(m.Document)); } else { return(null); } }
public T Deserialize <T>(string json) { if (string.IsNullOrEmpty(json)) { return(default(T)); } var type = typeof(T); object document = null; using (var reader = new StringReader(json)) document = DocumentSerializer.Deserialize(reader, type); using (var reader = new StringReader(json)) if (!type.IsInstanceOfType(typeof(BaseDocument))) { var key = KeyAccessor.GetId(document, type); var metadata = (DocumentMetadata)MetadataSerialzier.Deserialize(reader, typeof(DocumentMetadata)); MetadataProvider.SetMetadata(key, metadata); } return((T)document); }
public async Task <AnalysisDocument> AnalyseAsync(AnalysisRequest request, CancellationToken cancellationToken) { var msg = new AnalysisMessage { Spec = SpecUtils.Zip(request.Spec), PackagesToAnalyze = request.PackagesToAnalyze, OutputFile = Path.GetTempFileName(), UsedTypesOnly = request.UsedTypesOnly, AllEdges = request.AllEdges, CreateClustersForNamespaces = request.CreateClustersForNamespaces }; if (request.Spec.Length * 2 > 4000000) { throw new NotSupportedException("Spec is too big"); } var response = await this.ProcessAsync(typeof(PackageAnalysisActor), msg, cancellationToken); try { if (response is AnalysisResponse m) { var serializer = new DocumentSerializer(); return(serializer.Deserialize <AnalysisDocument>(m.File)); } else { return(null); } } finally { File.Delete(msg.OutputFile); } }
public async Task <List <ICommandResult <T> > > RequestMultipleMergedResult <T>(object data = null) { var results = new List <ICommandResult <T> >(); var response = await SendCommandAsync(data).ConfigureAwait(false); using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { var serializer = new DocumentSerializer(db); var _results = serializer.Deserialize <List <T> >(stream); foreach (var r in _results) { var distinctResult = new DistinctCommandResult <T> { Result = r, BaseResult = r as BaseResult }; results.Add(distinctResult); } } return(results); }