public async UniTask SaveAsync(Uri uri, T data, CancellationToken cancellationToken = default) { if (await asyncCRUDHandler.ExistsAsync(uri, cancellationToken)) { await asyncCRUDHandler.UpdateAsync(uri, dataSerializer.Serialize(data), cancellationToken); } else { await asyncCRUDHandler.CreateAsync(uri, dataSerializer.Serialize(data), cancellationToken); } }
public void Save(Uri uri, T data) { if (crudHandler.Exists(uri)) { crudHandler.Update(uri, dataSerializer.Serialize(data)); } else { crudHandler.Create(uri, dataSerializer.Serialize(data)); } }
/// <summary> /// 异步执行任务 /// </summary> /// <typeparam name="TMessage">真实的响应类型</typeparam> /// <param name="request"></param> /// <param name="mission"></param> public void AsyncExecuteMission <TMessage>(IMissionMessage request, Task <TMessage> mission) { if (_queue == null || _serializer == null) { throw new Exception("请先注入中间件及序列化器"); } Action <Task <TMessage> > a = async(t) => { try { TMessage message = await t; var msgBytes = _serializer.Serialize(message); var body = new byte[4 + msgBytes.Length]; var idBytes = BitConverter.GetBytes(request.MissionId); Array.Copy(idBytes, body, 4); Array.Copy(msgBytes, 0, body, 4, msgBytes.Length); await _queue.PublishAsync(request.ReplyQueue, body); } catch (Exception e) { _logger?.LogError(e, null); } }; mission.ContinueWith(a).ConfigureAwait(false); }
public static UFileManager Create(string fileName, IDataSerializer serializer, bool crcEnabled, int blockSize = 4096) { UFileManager manager = new UFileManager(); manager.dataSerializer = serializer; manager.mainHeader = new Header(); manager.mainHeader.CRCEnabled = crcEnabled; manager.mainHeader.Filled = true; manager.mainHeader.LastBlock = true; manager.blockSize = blockSize; manager.fileMap = new Dictionary <string, long>(); manager.stream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.Read); manager.fileMap.Add("$_BlockSize_$", manager.blockSize); manager.AvailableEndBlockSize = blockSize - Header.HeaderSize; manager.AvailableMidBlockSize = manager.AvailableEndBlockSize - sizeof(long); byte[] mapBytes = serializer.Serialize(manager.fileMap); manager.FillData("", mapBytes, 0); //manager.mainHeader.Length = mapBytes.Length; //manager.mainHeader.SetChecksum(mapBytes); //byte[] header = Header.ToBytes(manager.mainHeader); //manager.stream.Write(header, 0, header.Length); //manager.stream.Write(mapBytes, 0, mapBytes.Length); //manager.stream.Flush(); return(manager); }
public NameValueCollection Interact(IServerEndpoint serverEndpoint, NameValueCollection message) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverEndpoint.Url + ":" + serverEndpoint.Port); byte[] postBuffer; Stream postData = request.GetRequestStream(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); byte[] responseBuffer; string result; NameValueCollection nameValueCollection = new NameValueCollection(); request.Method = "POST"; foreach (KeyValuePair <string, string> collection in message) { postBuffer = serializer.Serialize(collection.Value); request.ContentLength = postBuffer.Length; postData.Write(postBuffer, 0, postBuffer.Length); responseBuffer = new byte[BufferSize]; responseStream.Read(responseBuffer, 0, responseBuffer.Length); result = serializer.Deserialize <string>(responseBuffer); nameValueCollection.Add(collection.Key, result); } postData.Close(); response.Close(); responseStream.Close(); return(nameValueCollection); }
public string Protect(AuthenticationTicket data) { var serialisedData = serializer.Serialize(data); var protectedData = dataProtector.Protect(serialisedData); var protectedText = encoder.Encode(protectedData); return(protectedText); }
public string Protect(TData data) { byte[] userData = _serializer.Serialize(data); byte[] protectedData = _protector.Protect(userData); string protectedText = _encoder.Encode(protectedData); return(protectedText); }
public async Task UpdateAsync(Consent consent) { string key = $"{consent.Subject}_{consent.ClientId}"; var data = _serializer.Serialize(consent); await _cache.RemoveAsync(key); await _cache.SetAsync(key, data, _dceo); }
/// <summary> /// 入队 /// </summary> /// <param name="exchangeName"></param> /// <param name="queueName"></param> /// <param name="dataObj"></param> /// <param name="persistent">数据是否持久化</param> /// <param name="durableQueue">队列是否持久化</param> /// <param name="exchangeType">默认为空,值为fanout是支持订阅发布模型</param> private bool BasicEnqueue(string exchangeName, string queueName, object dataObj, bool persistent = false, bool durableQueue = false, ExchangeType exchangeType = ExchangeType.Default) { try { using (IModel channel = Connection.CreateModel()) { if (exchangeType != ExchangeType.Default) { string strExchangeType = ExchangeTypeDataDict.ExchangeTypeDict[exchangeType]; channel.ExchangeDeclare(exchangeName, strExchangeType); } //if (exchangeType == ExchangeType.Fanout) //{ // exchangeName = "publish"; //} if (durableQueue) { channel.QueueDeclare(queueName, true, false, false, null); } IBasicProperties properties = propertiesEmpty; if (persistent) { properties = channel.CreateBasicProperties(); properties.Persistent = true; } byte[] data = serializer.Serialize(dataObj); dataObj = null; channel.BasicPublish(exchangeName, queueName, properties, data); return(true); } } catch (Exception ex) { if (!Monitor.IsEntered(objLock)) { if (_connection != null) { try { _connection.Close(100); _connection.Dispose(); } catch { } } _connection = null; } RecordException(ex, dataObj); dataObj = null; return(false); //throw; } }
public byte[] SaveEnvelopeData(ImmutableEnvelope envelope) { // string contract, Guid messageId, Uri sender, var itemContracts = new MessageContract[envelope.Items.Length]; using (var content = new MemoryStream()) { int position = 0; for (int i = 0; i < envelope.Items.Length; i++) { var item = envelope.Items[i]; string name; if (!_dataSerializer.TryGetContractNameByType(item.MappedType, out name)) { var error = string.Format("Failed to find contract name to serialize '{0}'.", item.MappedType); throw new InvalidOperationException(error); } // normal serializers have a nasty habbit of closing the stream after they are done // we can suppress that or use a wrapper now instead using (var itemStream = new MemoryStream()) { _dataSerializer.Serialize(item.Content, item.MappedType, itemStream); var bytes = itemStream.ToArray(); content.Write(bytes, 0, bytes.Length); } int size = (int)content.Position - position; var attribContracts = EnvelopeConvert.ItemAttributesToContract(item.GetAllAttributes()); itemContracts[i] = new MessageContract(name, size, position, attribContracts); position += size; } var envelopeAttribs = EnvelopeConvert.EnvelopeAttributesToContract(envelope.GetAllAttributes()); var contract = new EnvelopeContract(envelope.EnvelopeId, envelopeAttribs, itemContracts, envelope.DeliverOnUtc, envelope.CreatedOnUtc); using (var stream = new MemoryStream()) { // skip header stream.Seek(EnvelopeHeaderContract.FixedSize, SeekOrigin.Begin); // save envelope attributes _envelopeSerializer.SerializeEnvelope(stream, contract); var envelopeBytes = stream.Position - EnvelopeHeaderContract.FixedSize; // copy data content.WriteTo(stream); // write the header stream.Seek(0, SeekOrigin.Begin); var header = new EnvelopeHeaderContract(EnvelopeHeaderContract.Schema2DataFormat, envelopeBytes, 0); header.WriteToStream(stream); return(stream.ToArray()); } } }
public (byte[], int) BuildStepOne(string key, string abonentId, string keyServiceId, string authorityId, string[] abonentAttributes) { _encryptor.SetKey(key); var nonce = CryptoHelper.GetNonce(); var payload = new KeyDistributionRequestPayload() { AbonentId = abonentId, KeyServiceId = keyServiceId, AttributeAuthorityId = authorityId, Attributes = abonentAttributes, Nonce = nonce }; var serializedPayload = _serializer.Serialize <KeyDistributionRequestPayload>(payload); var encryptedPayload = _encryptor.Encrypt(serializedPayload); var stepData = new KeyDistrubutionStepOne() { AbonentId = abonentId, AttributeAuthorityId = authorityId, Attributes = abonentAttributes, Payload = encryptedPayload }; var serializedData = _serializer.Serialize <KeyDistrubutionStepOne>(stepData); return(serializedData, nonce); }
private RedisValue GetValue(T instance) { if (!RedisValueExtractor.TryParsePrimitive(instance, out RedisValue redisValue)) { return(serializer.Serialize(instance)); } return(redisValue); }
public async Task Create(string path, PhotoDirectoryConfig config) { var configFilename = _fileSystem.Path.Combine(path, PhotoFolderConsts.ConfigFileName); var serializedConfig = _serializer.Serialize(config); await _fileSystem.File.WriteAllTextAsync(configFilename, serializedConfig); _fileSystem.File.SetAttributes(configFilename, FileAttributes.Hidden); }
/// <summary> /// 序列化 /// </summary> /// <param name="obj"></param> /// <returns></returns> private static string Serializer(object obj) { if (obj is string) { return((string)obj); } if (serializer is Raven.Serializer.IStringDataSerializer strSerializer) { return(strSerializer.SerializeToString(obj)); } else { var data = serializer.Serialize(obj); Encoding encoding = Encoding.UTF8; var res = encoding.GetString(data); return(res); } }
public string Protect(AuthenticationTicket data) { var userData = _serializer.Serialize(data); var protectedData = rsa.Encrypt(userData); var s1 = Base64UrlTextEncoder.Encode(protectedData); return(s1); }
public async Task Serialize_GivenStreamAndIdInfo_SavesCsvToValidIdFile() { var filestream = new FileStream("ValidCsv.txt", FileMode.Create); await _dataSerializer.Serialize(filestream, _idInfos); var actualValue = "8709046424188,1987/09/04,Non-SA Citizen,Male\r\n" + "8605065397083,1986/05/06,SA Citizen,Male\r\n"; Assert.That(actualValue, Is.EqualTo(_dataSerializer.CsvData)); }
public string Protect(AuthenticationTicket data, string purpose) { byte[] plaintext = _serializer.Serialize(data); IDataProtector dataProtector = _protector; if (!string.IsNullOrEmpty(purpose)) { dataProtector = dataProtector.CreateProtector(purpose); } return(Base64UrlTextEncoder.Encode(dataProtector.Protect(plaintext))); }
public T Save <T>(T data) { var message = new NameValueCollection { { "command", "save" }, { "data", Convert.ToBase64String(dataSerializer.Serialize(data)) } }; NameValueCollection result = Send(message); return(dataSerializer.Deserialize <T>(Convert.FromBase64String(result["data"]))); }
private string Serialized(object data) { if (data == null) { return(null); } if (data.GetType().IsPrimitive) { data = data.ToString(); } return(_dataSerializer.Serialize(data)); }
public string Protect(AuthenticationProperties data, string purpose) { var key = Guid.NewGuid().ToString(); var cacheKey = $"{CacheKeyPrefix}{key}"; var serialized = _serializer.Serialize(data); // Rather than encrypt the full AuthenticationProperties // cache the data and encrypt the key that points to the data _cache.Set(cacheKey, serialized); return(key); }
public IActionResult ShippingOptions(string shippingMethodSystemName) { if (!CanCheckout(out Cart cart)) { return(R.Fail.Result); } if (cart.BillingAddressId == 0 || cart.ShippingAddressId == 0) { return(R.Fail.With("error", T("The address details were not provided")).Result); } //validate shipping method var shippingHandler = PluginHelper.GetShipmentHandler(shippingMethodSystemName); if (shippingHandler == null || !shippingHandler.IsMethodAvailable(cart)) { return(R.Fail.With("error", T("Shipping method unavailable")).Result); } var shippingOptionModels = GetShipmentOptionModels(shippingHandler, cart); cart.ShippingOptionsSerialized = _dataSerializer.Serialize(shippingOptionModels); //select the first option as default one var selectedOptions = shippingOptionModels.Select(x => x.ShippingOptions.FirstOrDefault()).ToList(); cart.SelectedShippingOption = _dataSerializer.Serialize(ToShippingOptions(selectedOptions)); _cartService.Update(cart); return(R.Success.With("shippingOptions", shippingOptionModels).Result); }
protected IOperations ExecuteSave <TData>(IEnumerable <TData> data, IDataSerializer <TData> serializer, bool commit, bool optimize) { _httpHelper.Post(UpdateUri, serializer.Serialize(data, FormatType.JSON), "application/json", Encoding.UTF8); if (commit) { Commit(); } if (optimize) { Optimize(); } return(this); }
public string Protect(AuthenticationProperties data, string purpose) { var key = Guid.NewGuid().ToString(); var cacheKey = $"{CacheKeyPrefix}{key}"; var serialized = _serializer.Serialize(data); // Rather than encrypt the full AuthenticationProperties // cache the data and encrypt the key that points to the data _cache.Set(cacheKey, serialized, new DistributedCacheEntryOptions { SlidingExpiration = TimeSpan.FromHours(1) }); return(key); }
private string GetStringValue(object value, IDataSerializer serializer) { if (value == null) { return(null); } if (value is string str) { return(str); } return(serializer.Serialize(value)); }
public Task PublishAsync <T>(string channel, T message) { try { var ch = GetChannel(); var body = _serializer.Serialize(message); ch.BasicPublish("", channel, null, body); } catch (Exception e) { Console.WriteLine(DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + e.Message); } return(Task.FromResult(0)); }
protected override void ProcessRequest(HttpListenerContext context) { var request = context.Request; switch (request.QueryString["operation"]) { case ServiceOperations.GetAll: var records = GetAllRecords(); var bytes = _dataSerializer.Serialize(records); var output = context.Response.OutputStream; output.Write(bytes, 0, bytes.Length); output.Close(); break; } }
/// <inheritdoc /> public string Protect(TData data, string?purpose) { var userData = _serializer.Serialize(data); var protector = _protector; if (!string.IsNullOrEmpty(purpose)) { protector = protector.CreateProtector(purpose); } var protectedData = protector.Protect(userData); return(Base64UrlTextEncoder.Encode(protectedData)); }
/// <summary>Converts a <c>CloudEntity</c> toward a <c>FatEntity</c>.</summary> public static FatEntity Convert <T>(CloudEntity <T> cloudEntity, IDataSerializer serializer) { var fatEntity = new FatEntity { PartitionKey = cloudEntity.PartitionKey, RowKey = cloudEntity.RowKey, Timestamp = cloudEntity.Timestamp }; using (var stream = new MemoryStream()) { serializer.Serialize(cloudEntity.Value, stream, typeof(T)); fatEntity.SetData(stream.ToArray()); return(fatEntity); } }
private async Task <string> SendProxyRequest(string url, string method, object parameters) { using (var webClient = new WebClient()) { try { byte[] resBytes; if (method == "GET") { if (parameters != null) { //add parameters if (!url.Contains('?')) { url += "?"; } url += parameters.ToString(); } resBytes = await webClient.DownloadDataTaskAsync(url); } else { if (parameters is NameValueCollection collection) { resBytes = await webClient.UploadValuesTaskAsync(url, method, collection); } else { var data = ""; if (parameters != null) { data = _dataSerializer.Serialize(parameters); } webClient.Headers[HttpRequestHeader.ContentType] = "application/json"; return(await webClient.UploadStringTaskAsync(url, method, data)); } } var result = System.Text.Encoding.UTF8.GetString(resBytes); return(result); } catch (Exception e) { return(null); } } }
public Task RenewAsync(string key, AuthenticationTicket ticket) { var options = new DistributedCacheEntryOptions(); var expiresUtc = ticket.Properties.ExpiresUtc; if (expiresUtc.HasValue) { options.SetAbsoluteExpiration(expiresUtc.Value); } if (ticket.Properties.AllowRefresh.GetValueOrDefault(false)) { options.SetSlidingExpiration(TimeSpan.FromMinutes(30)); // TODO: configurable. } return(_cache.SetAsync(key, _ticketSerializer.Serialize(ticket), options)); }
public void Save(FileInfo file, IDataSerializer serializer) { File.WriteAllBytes(file.FullName, serializer.Serialize(this)); }