public void WriteHashesFiles() { string hashesFilePath = Path.Combine(mConfiguration.Value.DriveRootDirectory, HashFileName); mSerializer.Serialize(HashToFilePathDict, hashesFilePath); WriteOnlyDuplicatesFiles(hashesFilePath); }
/// <summary> /// Saves a single item by its key. /// This method should be considered for objects that do not exceed 8k bytes during the lifetime of the application /// (refers to <see cref="SaveFileAsync{T}(string, T)"/> for complex/large objects). /// </summary> /// <typeparam name="T">Type of object saved</typeparam> /// <param name="key">Key of the value saved</param> /// <param name="value">Object to save</param> public void Save <T>(string key, T value) { var type = typeof(T); var typeInfo = type.GetTypeInfo(); Settings.Values[key] = serializer.Serialize(value); }
/// <summary> /// Writes the message to stream. /// </summary> /// <param name="messageRecord">Message record.</param> public void Write(MessageRecord messageRecord) { var messageBytes = serializer.Serialize(messageRecord.Content); var errorBytes = messageRecord.Error != null?serializer.Serialize(messageRecord.Error) : emptyBytes; var dataBytes = messageRecord.Data != null?serializer.Serialize(messageRecord.Data) : emptyBytes; lock (objLock) { WriteChunk(TokenBeginOfCommand); WriteChunk(TokenId, messageRecord.Id.ToByteArray()); // id WriteChunk(TokenType, BitConverter.GetBytes(messageRecord.Type)); // type WriteChunk(TokenContentType, Encoding.UTF8.GetBytes(messageRecord.ContentType)); // message type WriteChunk(TokenCreated, BitConverter.GetBytes(messageRecord.CreatedAt.ToBinary())); // created WriteChunk(TokenExecutionDuration, BitConverter.GetBytes(messageRecord.ExecutionDuration)); // completed WriteChunk(TokenStatus, BitConverter.GetBytes((byte)messageRecord.Status)); // status if (messageRecord.Error != null) { WriteChunk(TokenErrorDetails, errorBytes); // error } WriteChunk(TokenErrorMessage, Encoding.UTF8.GetBytes(messageRecord.ErrorMessage)); // error message WriteChunk(TokenErrorType, Encoding.UTF8.GetBytes(messageRecord.ErrorType)); // error type WriteChunk(TokenContent, messageBytes); // message object if (messageRecord.Data != null) { WriteChunk(TokenData, dataBytes); } WriteChunk(TokenEndOfCommand); } }
/// <inheritdoc /> public void Save <T>(string key, T value) { // Set the local cache Settings[key] = _serializer.Serialize(value); // Send an update to the remote. Task.Run(() => Update(_fileWithExtension, Settings)); }
/// <inheritdoc /> public void Save<T>(string key, T value) { // Set the local cache Settings[key] = _serializer.Serialize(value); // Send an update to the remote. Task.Run(() => Set(_extensionId, UserId, key, value)); }
public CouchResponseObject CreateDocument(Document doc) { var serialized = ObjectSerializer.Serialize(doc.JObject); if (doc.Id != null) { return(CreateDocument(doc.Id, serialized)); } return(CreateDocument(serialized)); }
public void Write(Stream stream) { var states = s_CachedVariables[GetType()]; foreach (var state in states) { var value = state.GetValue(this); byte[] serializedVariable = m_Serializer.Serialize(value); byte[] lengthBytes = BitConverter.GetBytes(serializedVariable.Length); stream.Write(lengthBytes, 0, lengthBytes.Length); stream.Write(serializedVariable, 0, serializedVariable.Length); } }
/// <summary> /// Saves a single item by its key. /// This method should be considered for objects that do not exceed 8k bytes during the lifetime of the application /// (refers to <see cref="SaveFileAsync{T}(string, T)"/> for complex/large objects). /// </summary> /// <typeparam name="T">Type of object saved</typeparam> /// <param name="key">Key of the value saved</param> /// <param name="value">Object to save</param> public void Save <T>(string key, T value) { var type = typeof(T); var typeInfo = type.GetTypeInfo(); if (typeInfo.IsPrimitive || type == typeof(string)) { Settings.Values[key] = value; } else { Settings.Values[key] = serializer.Serialize(value); } }
public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (!verifySuccess || (verifySuccess && (DateTime.Now - preverifyTime).TotalMinutes > 10)) { string msg = LicenseHelper.Verify(); if (!string.IsNullOrEmpty(msg)) { verifySuccess = false; context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.OK; var result = new ApiResult <string> { Code = ResultCode.License_Error, Msg = msg }; var sc = new StringContent(serializer.Serialize(result)); await sc.CopyToAsync(context.Response.Body); } else { verifySuccess = true; preverifyTime = DateTime.Now; await _next.Invoke(context); } } else { await _next.Invoke(context); } }
private void Persist( Node <TK> node, Dictionary <Int64, Node <TK> > loadedNodes, IObjectSerializer <Node <TK> > serializer, Dictionary <Int64, Node <TK> > touchedNodes, IndexMetaRecord metaRecord) { SaveChildren(node, loadedNodes, serializer, touchedNodes, metaRecord); if (!node.Dirty) { touchedNodes.Add(node.Address, node); return; } //setting it dirty now, EmptyRecordIndex nodes may become dirty while persisting due to re-use. node.ClearChanges(); var bytes = serializer.Serialize(node); var allocationStrategy = this.Session.AllocationStrategyResolver.StrategyFor(node); if (node.Address <= 0) { var record = this.RecordManager.AppendRecord(bytes, allocationStrategy); node.Address = record.Header.Address; } else { var record = this.RecordManager.GetRecord(node.Address); record = this.RecordManager.UpdateRecord(record, bytes, allocationStrategy); node.Address = record.Header.Address; } touchedNodes.Add(node.Address, node); }
/// <summary> /// Serializes an object to a binary destination. /// </summary> /// <param name="Writer">Serializer.</param> /// <param name="WriteTypeCode">If a type code is to be output.</param> /// <param name="Embedded">If the object is embedded into another.</param> /// <param name="Value">The actual object to serialize.</param> public override async Task Serialize(ISerializer Writer, bool WriteTypeCode, bool Embedded, object Value) { if (Value is null) { if (!WriteTypeCode) { throw new NullReferenceException("Value cannot be null."); } Writer.WriteBits(ObjectSerializer.TYPE_NULL, 6); } else { T[] Array = (T[])Value; Type LastType = typeof(T); IObjectSerializer S = await this.context.GetObjectSerializer(LastType); Type ItemType; bool Nullable; Writer.WriteBits(ObjectSerializer.TYPE_ARRAY, 6); Writer.WriteVariableLengthUInt64((ulong)Array.Length); if (Nullable = S.IsNullable) { Writer.WriteBits(ObjectSerializer.TYPE_NULL, 6); } else { Writer.WriteBits(ObjectSerializer.GetFieldDataTypeCode(LastType), 6); } foreach (T Item in Array) { if (Item == null) { if (Nullable) { Writer.WriteBits(ObjectSerializer.TYPE_NULL, 6); } else { throw new Exception("Elements cannot be null."); } } else { ItemType = Item.GetType(); if (ItemType != LastType) { S = await this.context.GetObjectSerializer(ItemType); LastType = ItemType; } await S.Serialize(Writer, Nullable, true, Item); } } } }
void SerializeObjectToBuffer(ushort msgType, IObjectSerializer serializer) { m_NetworkWriter.SeekZero(); m_NetworkWriter.StartMessage(msgType); serializer.Serialize(m_NetworkSyncWriter); m_NetworkWriter.FinishMessage(); }
public void Insert(WorkflowActivityDto workflowActivityDto) { if (workflowActivityDto == null) { throw new ArgumentNullException(nameof(workflowActivityDto)); } //_dbContext.WorkflowActivity.Add(new Entities.WorkflowActivity //{ // UniqueId = workflowActivityDto.UniqueId, // Context = _objectSerializer.Serialize(workflowActivityDto.Context) //}); //_dbContext.SaveChanges(); //TODO This should be deleted, just testing purpose var context = new CldpDbContext(); context.WorkflowActivity.Add(new Entities.WorkflowActivity { UniqueId = workflowActivityDto.UniqueId, Context = _objectSerializer.Serialize(workflowActivityDto.Context) }); context.SaveChanges(); }
/// <summary> /// Adds http request content /// </summary> /// <typeparam name="T"></typeparam> /// <param name="httpRequestMessage"></param> /// <param name="model"></param> protected virtual void AddHttpRequestMethodContentTypeAttributes <T>(HttpRequestMessage httpRequestMessage, T model) { var serializedMessage = _objectSerializer.Serialize(model); httpRequestMessage.Content = new StringContent(serializedMessage, _objectSerializer.Encoding, _objectSerializer.ContentType); }
/// <inheritdoc /> public Stream SerializeMessage <T>(T message) where T : IEvent { var stream = new MemoryStream(); _serializer.Serialize(stream, message); return(stream); }
/// <summary> /// Updates or create a new file on the remote with the provided content. /// </summary> /// <param name="graph">Instance of the <see cref="GraphServiceClient"/>.</param> /// <param name="userId">The id of the target Graph user.</param> /// <param name="itemPath">The path of the target item.</param> /// <param name="fileContents">The contents to put in the file.</param> /// <param name="serializer">A serializer for converting stored values.</param> /// <typeparam name="T">The type of object to save.</typeparam> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public static async Task <DriveItem> SetFileAsync <T>(this GraphServiceClient graph, string userId, string itemPath, T fileContents, IObjectSerializer serializer) { var json = serializer.Serialize(fileContents) as string; using var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)); return(await graph.Users[userId].Drive.Special.AppRoot.ItemWithPath(itemPath).Content.Request().PutAsync <DriveItem>(stream)); }
/// <summary> /// Serializes an object to a binary destination. /// </summary> /// <param name="Writer">Serializer.</param> /// <param name="WriteTypeCode">If a type code is to be output.</param> /// <param name="Embedded">If the object is embedded into another.</param> /// <param name="Value">The actual object to serialize.</param> public async Task Serialize(ISerializer Writer, bool WriteTypeCode, bool Embedded, object Value) { KeyValuePair <string, object> TypedValue = (KeyValuePair <string, object>)Value; IObjectSerializer Serializer = await this.context.GetObjectSerializer(TypedValue.Value?.GetType() ?? typeof(object)); Writer.WriteBit(true); Writer.Write(TypedValue.Key); await Serializer.Serialize(Writer, true, true, TypedValue.Value); }
public static ValueSet SerializeToValueSet(this IObjectSerializer serializer, object o) { var data = serializer.Serialize(o); return(new ValueSet { { "SerializedData", data } }); }
public void SaveMessageData(Guid messageId, object data) { using (var payloadStream = new MemoryStream()) { _serializer.Serialize(payloadStream, data); _messagePayloadRepository.Add(new MessagePayload(messageId, payloadStream.GetBuffer())); } }
private void PutInBatch(WriteBatch batch, T obj) { var keySlice = _docConverter.GetKeySlice(obj); batch.Put(keySlice, Slice.FromByteArray(_serializer.Serialize(obj))); foreach (var i in _docConverter.GetIndexKeySlices(obj)) { batch.Put(i, keySlice); } }
public override TResult Dispatch <TResult>(TDispatchable dispatchable) { try { string formattedCommand = Serializer.Serialize(dispatchable); Logger.LogQuery(formattedCommand); TResult response = Next.Dispatch <TResult>(dispatchable); string formattedResponse = Serializer.Serialize(response); Logger.LogResponse(formattedResponse); return(response); } catch (Exception e) { Logger.LogException(e); throw; } }
public JObject CreateDocument(IBaseObject doc) { var serialized = ObjectSerializer.Serialize(doc); if (doc.Id != null) { return(CreateDocument(doc.Id, serialized)); } return(CreateDocument(serialized)); }
private string GetStringFor(Type t, object obj) { Func <object, string> printer; if (_dictionary.TryGetValue(t, out printer)) { return(printer(obj)); } return(_serializer.Serialize(obj)); }
public bool AddOrUpdate(Guid key, object value) { lock (sync) { memory.Position = 0; serializer.Serialize(value, writer); file.Write(key, memory.GetBuffer(), 0, (int)memory.Position); return(true); } }
/// <summary> /// Serializes a (Key,Value) pair. /// </summary> /// <param name="Key">Key</param> /// <param name="Value">Value</param> /// <param name="Serializer">Serializer.</param> /// <returns>Serialized record.</returns> public byte[] Serialize(string Key, object Value, IObjectSerializer Serializer) { BinarySerializer Writer = new BinarySerializer(this.collectionName, this.encoding); Writer.WriteBit(true); Writer.Write(Key); Serializer.Serialize(Writer, true, false, Value); return(Writer.GetSerialization()); }
private async Task ExecuteAddMessageCommandAsync(DbConnection connection, MessageRecord messageRecord, CancellationToken cancellationToken) { using (var command = connection.CreateCommand()) { command.CommandText = queryProvider.GetInsertMessageScript(); AddParameter(command, "@Type", messageRecord.Type); AddParameter(command, "@ContentId", messageRecord.Id.ToString()); AddParameter(command, "@ContentType", messageRecord.ContentType); AddParameter(command, "@Content", serializer.Serialize(messageRecord.Content)); AddParameter(command, "@Data", messageRecord.Data != null ? serializer.Serialize(messageRecord.Data) : null); AddParameter(command, "@ErrorDetails", messageRecord.Error != null ? serializer.Serialize(messageRecord.Error) : null); AddParameter(command, "@ErrorMessage", messageRecord.ErrorMessage); AddParameter(command, "@ErrorType", messageRecord.ErrorType); AddParameter(command, "@CreatedAt", messageRecord.CreatedAt); AddParameter(command, "@ExecutionDuration", messageRecord.ExecutionDuration); AddParameter(command, "@Status", (byte)messageRecord.Status); await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); } }
/// <summary> /// Writes an object to a stream. /// </summary> /// <param name="o">Object</param> /// <param name="writer">Stream writer</param> /// <returns></returns> public static async Task SerializeToStreamAsync(this IObjectSerializer serializer, object o, DataWriter writer) { var data = serializer.Serialize(o); var bytes = Encoding.UTF8.GetBytes(data); writer.WriteUInt32((uint)bytes.Length); writer.WriteBytes(bytes); await writer.StoreAsync(); }
private void WriteBlobInfo(string blobId, BlobInfo blobInfo) { TryCreateDirectory(blobId); var infoFilePath = GetBlobInfoFilePath(blobId); using (var infoFile = OpenWriteFileStream(infoFilePath)) { _objectSerializer.Serialize(infoFile, blobInfo); } }
/// <summary> /// Serializes a (Key,Value) pair. /// </summary> /// <param name="Key">Key</param> /// <param name="Value">Value</param> /// <param name="Serializer">Serializer.</param> /// <returns>Serialized record.</returns> private async Task <byte[]> SerializeLocked(string Key, object Value, IObjectSerializer Serializer) { BinarySerializer Writer = new BinarySerializer(this.collectionName, this.encoding); Writer.WriteBit(true); Writer.Write(Key); await Serializer.Serialize(Writer, true, true, Value); return(Writer.GetSerialization()); }
private static void SaveLastObject(FilesProvider Provider, object LastObjectAdded) { if (LastObjectAdded != null) { IObjectSerializer Serializer = Provider.GetObjectSerializer(LastObjectAdded.GetType()); BinarySerializer Writer = new BinarySerializer(CollectionName, Encoding.UTF8); Serializer.Serialize(Writer, false, false, LastObjectAdded); byte[] Bin = Writer.GetSerialization(); System.IO.File.WriteAllBytes(ObjFileName, Bin); } }
public XmlDataStoreRepository() { dataStoreRepositoryPath = ConfigurationItem<string>.ReadSetting("XmlDataStoreRepositoryPath").GetValue(); serializer = new XmlObjectSerializer(); if (!File.Exists(dataStoreRepositoryPath)) { dataStores = new XmlDataStoreCollection(); File.WriteAllText(dataStoreRepositoryPath, serializer.Serialize(dataStores)); return; } dataStores = serializer.Deserialize<XmlDataStoreCollection>(File.ReadAllText(dataStoreRepositoryPath)); }
public SecureXmlDataStoreRepository() { key = ConfigurationItem<string>.ReadSetting("SecureXmlDataStoreRepositoryKey").GetValue(); dataStoreRepositoryPath = ConfigurationItem<string>.ReadSetting("SecureXmlDataStoreRepositoryPath").GetValue(); serializer = new XmlObjectSerializer(); if (!File.Exists(dataStoreRepositoryPath)) { dataStores = new XmlDataStoreCollection(); File.WriteAllText(dataStoreRepositoryPath, serializer.Serialize(dataStores)); return; } dataStores = serializer.Deserialize<XmlDataStoreCollection>(File.ReadAllText(dataStoreRepositoryPath)); PersistStore(); // force encryption for any insecure connection strings }