private TagBuilder getCaptchaImageTagBuilder(string encryptedText) { ViewContext.CheckArgumentNull(nameof(ViewContext)); var values = new CaptchaImageParams { Text = encryptedText, RndDate = DateTime.Now.Ticks.ToString(), ForeColor = ForeColor, BackColor = BackColor, FontSize = FontSize, FontName = FontName }; var serializedValues = _serializationProvider.Serialize(values); var encryptSerializedValues = _captchaProtectionProvider.Encrypt(serializedValues); var actionUrl = _urlHelper.Action( action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty), values: new { data = encryptSerializedValues, area = "" }, protocol: ViewContext.HttpContext.Request.Scheme); var captchaImage = new TagBuilder("img"); var dntCaptchaImg = "dntCaptchaImg"; captchaImage.TagRenderMode = TagRenderMode.SelfClosing; captchaImage.Attributes.Add("id", dntCaptchaImg); captchaImage.Attributes.Add("name", dntCaptchaImg); captchaImage.Attributes.Add("alt", "captcha"); captchaImage.Attributes.Add("src", actionUrl); captchaImage.Attributes.Add("style", "margin-bottom: 4px;"); return(captchaImage); }
public async Task <bool> SetAsync <T>(RedisClient client, T value, string key, DateTime expires, IEnumerable <string> tags) { if (value == null) { return(false); } var cacheItem = Create(value, key, expires, tags); var serialized = _serializer.Serialize(cacheItem); int expirySeconds = GetExpirySeconds(expires); await client.SetAsync(key, serialized, expirySeconds); return(true); }
/// <summary> /// Caches an item. If a serialization provider has been configured that will be used to serialize the value /// rather than relying on AppFanbric's default implementation. If the region the item is to be cached in doesn't /// exists, ite will be created. /// </summary> /// <param name="key">The key for the item to be cached.</param> /// <param name="value">The item to be cached.</param> /// <param name="createMissingRegion">A flag to determine whether or not the cache region should be created if it /// doesn't exist.</param> private void Put(object key, object value, bool createMissingRegion) { if (key == null) { throw new ArgumentNullException("key", "null key not allowed"); } if (value == null) { throw new ArgumentNullException("value", "null value not allowed"); } try { if (_serializationProvider != null) { value = _serializationProvider.Serialize(value); } Cache.Put(key.ToString(), value, AppFabricRegionName); } catch (DataCacheException ex) { if (ex.ErrorCode == DataCacheErrorCode.RegionDoesNotExist && createMissingRegion) { CreateAppFabricRegion(b => Put(key, value, false)); } else if (!IsSafeToIgnore(ex) && ex.ErrorCode != DataCacheErrorCode.ObjectLocked) { throw new CacheException(ex); } } }
private string getCaptchaImageUrl(DNTCaptchaTagHelperHtmlAttributes captchaAttributes, string encryptedText) { var values = new CaptchaImageParams { Text = encryptedText, RndDate = DateTime.Now.Ticks.ToString(), ForeColor = captchaAttributes.ForeColor, BackColor = captchaAttributes.BackColor, FontSize = captchaAttributes.FontSize, FontName = captchaAttributes.FontName }; var encryptSerializedValues = _captchaProtectionProvider.Encrypt(_serializationProvider.Serialize(values)); var actionUrl = captchaAttributes.UseRelativeUrls ? _urlHelper.Action(action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty), values: new { data = encryptSerializedValues, area = "" }) : _urlHelper.Action(action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty), values: new { data = encryptSerializedValues, area = "" }, protocol: _httpContextAccessor.HttpContext.Request.Scheme); if (string.IsNullOrWhiteSpace(actionUrl)) { throw new NullReferenceException("It's not possible to determine the URL of the `DNTCaptchaImageController.Show` method. Please register the `services.AddControllers()` and `endpoints.MapControllerRoute(...)`."); } return(actionUrl); }
public void Send(string name, object message, Action <MessageSendError> sendError) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException("argument is empty string", "name"); } if (message == null) { throw new ArgumentNullException("message"); } using (var memStream = new MemoryStream()) { var data = _serializator.Serialize(message); var nameBytes = Encoding.ASCII.GetBytes(name); var fullLength = 4 + nameBytes.Length + 4 + data.Length; memStream.Write(BitConverter.GetBytes(fullLength), 0, 4); memStream.Write(BitConverter.GetBytes(nameBytes.Length), 0, 4); memStream.Write(nameBytes, 0, nameBytes.Length); memStream.Write(BitConverter.GetBytes(data.Length), 0, 4); memStream.Write(data, 0, data.Length); _stream.Write(memStream.ToArray(), 0, (int)memStream.Length); } }
public void Put(object key, object value) { //validate the params if (key == null) { throw new ArgumentNullException("key"); } if (value == null) { throw new ArgumentNullException("value"); } //get the full key for the cache key string cacheKey = GetCacheKey(key); try { _webCache.Put(cacheKey, _serializationProvider.Serialize(value), RegionName); } catch (DataCacheException ex) { if (ex.ErrorCode == DataCacheErrorCode.RegionDoesNotExist) { CreateAppFabricRegion(b => Put(key, value)); } else if (!IsSafeToIgnore(ex) && ex.ErrorCode != DataCacheErrorCode.ObjectLocked) { throw new CacheException(ex); } } }
/// <summary> /// Sets an item into the cache under the given key with the associated tags /// </summary> /// <param name="client">The <see cref="RedisClient" /> to use to communicate with Redis</param> /// <param name="key">The key to set the item under</param> /// <param name="value">The value to store</param> /// <param name="expiry">When to expire the cached item</param> /// <param name="tags">The tags to assign to the cached value</param> /// <typeparam name="T">The type of the item being stored</typeparam> public Task <bool> Set <T>(RedisClient client, string key, T value, DateTime?expiry = null, params string[]?tags) where T : notnull { var cacheItem = _cacheItemFactory.Create(key, value, expiry, tags); var serialized = _serializer.Serialize(cacheItem); return(client.ThrowIfNull(nameof(client)).Set(key, serialized, expiry)); }
public ArraySegment <byte> Serialize <TIn>(TIn input) { if (_encryptionProvider != null && _compressionProvider != null) { return(SerializeCompressEncrypt(input)); } else if (_encryptionProvider != null) { return(SerializeEncrypt(input)); } else if (_compressionProvider != null) { return(SerializeEncrypt(input)); } return(_serializationProvider.Serialize(input)); }
private TagBuilder getCaptchaImageTagBuilder(ViewContext viewContext, string encryptedText) { if (_urlHelper == null) { throw new InvalidOperationException("Failed to find the IUrlHelper of ViewContext.HttpContext."); } var values = new CaptchaImageParams { Text = encryptedText, RndDate = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture), ForeColor = ForeColor, BackColor = BackColor, FontSize = FontSize, FontName = FontName }; var serializedValues = _serializationProvider.Serialize(values); var encryptSerializedValues = _captchaProtectionProvider.Encrypt(serializedValues); var actionUrl = UseRelativeUrls ? _urlHelper.Action( action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty, StringComparison.Ordinal), values: new { data = encryptSerializedValues, area = "" }) : _urlHelper.Action( action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty, StringComparison.Ordinal), values: new { data = encryptSerializedValues, area = "" }, protocol: viewContext.HttpContext.Request.Scheme); if (string.IsNullOrWhiteSpace(actionUrl)) { throw new InvalidOperationException("It's not possible to determine the URL of the `DNTCaptchaImageController.Show` method. Please register the `services.AddControllers()` and `endpoints.MapControllerRoute(...)`."); } var captchaImage = new TagBuilder("img"); var dntCaptchaImg = $"{_captchaOptions.CaptchaClass}Img"; captchaImage.TagRenderMode = TagRenderMode.SelfClosing; captchaImage.Attributes.Add("id", dntCaptchaImg); captchaImage.Attributes.Add("name", dntCaptchaImg); captchaImage.Attributes.Add("alt", "captcha"); captchaImage.Attributes.Add("src", actionUrl); captchaImage.Attributes.Add("style", "margin-bottom: 4px;"); return(captchaImage); }
public void Send <T>(T message, string queue) { var liteBusMessage = new LiteBusMessage { OriginatingEndpoint = Assembly.GetCallingAssembly().GetName().Name, DestinationEndpoint = queue, TimeSent = DateTime.Now, ObjectType = typeof(T).ToString(), ObjectAssembly = typeof(T).Assembly.ToString(), Message = _serializer.Serialize(message) }; using (var q = new MessageQueue(_qPathProvider.GetPath(queue))) { q.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) }); q.Send(_serializer.Serialize(liteBusMessage)); } }
protected BrokeredMessage Serialize(T entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } return(_provider.Serialize(entity)); }
public void SerializationProvider_Serialize() { var result = _serializationProvider.Serialize(Data); Assert.AreEqual(Data.ToJson().ToBytes(), result); var resultJson = result.FromBytes(); Assert.AreEqual(Data.ToJson(), resultJson); }
private TagBuilder getCaptchaImageTagBuilder(string encryptedText) { ViewContext.CheckArgumentNull(nameof(ViewContext)); var values = new CaptchaImageParams { Text = encryptedText, RndDate = DateTime.Now.Ticks.ToString(), ForeColor = ForeColor, BackColor = BackColor, FontSize = FontSize, FontName = FontName, UseNoise = UseNoise }; var serializedValues = _serializationProvider.Serialize(values); var encryptSerializedValues = _captchaProtectionProvider.Encrypt(serializedValues); var actionUrl = UseRelativeUrls ? _urlHelper.Action( action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty), values: new { data = encryptSerializedValues, area = "" }) : _urlHelper.Action( action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty), values: new { data = encryptSerializedValues, area = "" }, protocol: ViewContext.HttpContext.Request.Scheme); if (string.IsNullOrWhiteSpace(actionUrl)) { throw new NullReferenceException("It's not possible to determine the URL of the `DNTCaptchaImageController.Show` method. Please register the `services.AddControllers()` and `endpoints.MapControllerRoute(...)`."); } var captchaImage = new TagBuilder("img"); var dntCaptchaImg = "dntCaptchaImg"; captchaImage.TagRenderMode = TagRenderMode.SelfClosing; captchaImage.Attributes.Add("id", dntCaptchaImg); captchaImage.Attributes.Add("name", dntCaptchaImg); captchaImage.Attributes.Add("alt", "captcha"); captchaImage.Attributes.Add("src", actionUrl); captchaImage.Attributes.Add("style", "margin-bottom: 4px;"); return(captchaImage); }
/// <summary> /// Add/update an entry in the cache /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">Key used to locate value in the cache</param> /// <param name="value"></param> /// <param name="ttl"></param> public void Set <T>(string key, T value, TimeSpan ttl) { // parameter validation if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (ttl.TotalSeconds < 1) { throw new ArgumentNullException(nameof(ttl)); } // Get the current timestamp before we do anything else. Decrement it by one so any sync messages processed during // this method call will force an immediate expiration of the key's hash slot var timestamp = Stopwatch.GetTimestamp() - 1; var keyHashSlot = HashSlotCalculator.CalculateHashSlot(key); byte[] serializedData = null; // Serialize the data and write to Redis using (MemoryStream ms = new MemoryStream()) { _serializationProvider.Serialize <T>(ms, value); serializedData = ms.ToArray(); } // Execute the Redis SET and PUBLISH operations in one round trip using Lua // (Could use StackExchange.Redis batch here, instead) string luaScript = @" redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[2]) redis.call('PUBLISH', ARGV[3], ARGV[4]) "; var scriptArgs = new RedisValue[4]; scriptArgs[0] = serializedData; scriptArgs[1] = ttl.TotalSeconds; scriptArgs[2] = SYNC_CHANNEL_NAME; scriptArgs[3] = DataSyncMessage.Create(_instanceId, keyHashSlot).Serialize(); _redisDb.ScriptEvaluate(luaScript, new RedisKey[] { key }, scriptArgs); // Update the in-process cache _inProcessCache.Set(key, new LocalCacheEntry <T>(keyHashSlot, timestamp, value), DateTimeOffset.UtcNow.Add(ttl)); }
public void NewtonsoftJsonProvider_SerializeDeserialize() { var customObject = new MyCustomClass(); var data = _newtonsoftProvider.Serialize(customObject); Assert.NotNull(data); Assert.False(data.Length == 0); var deserializedObject = _newtonsoftProvider.Deserialize <MyCustomClass>(data); Assert.NotNull(deserializedObject); // Spot Check Assert.Equal(customObject.MyString, deserializedObject.MyString); Assert.Equal(customObject.EmbeddedClass.HappyByte, deserializedObject.EmbeddedClass.HappyByte); Assert.Equal(customObject.Data["TestKey"], Convert.ToInt32(deserializedObject.Data["TestKey"])); // deserialized int32 (as object) to int64 Assert.Equal(customObject.AbstractData["TestKey2"], deserializedObject.AbstractData["TestKey2"]); Assert.Equal(customObject.SubClass.Ints.ElementAt(3), deserializedObject.SubClass.Ints.ElementAt(3)); }
public void DefaultJsonProvider_SerializeDeserialize() { var customObject = new MyCustomClass(); var data = _defaultJsonProvider.Serialize(customObject); Assert.NotNull(data); Assert.False(data.Length == 0); var deserializedObject = _defaultJsonProvider.Deserialize <MyCustomClass>(data); Assert.NotNull(deserializedObject); // Spot Check Assert.Equal(customObject.MyString, deserializedObject.MyString); Assert.Equal(customObject.EmbeddedClass.HappyByte, deserializedObject.EmbeddedClass.HappyByte); //Assert.Equal(customObject.Data["TestKey"], deserializedObject.Data["TestKey"]); // Not Supported Yet //Assert.Equal(customObject.AbstractData["TestKey2"], deserializedObject.AbstractData["TestKey2"]); // Not Supported Yet Assert.Equal(customObject.SubClass.Ints.ElementAt(3), deserializedObject.SubClass.Ints.ElementAt(3)); }
public void SerializationProvider_SerializeDeserialize(ISerializationProvider serializationProvider) { void Test <T>(T data) { var serialized = serializationProvider.Serialize(data); var deserialized = serializationProvider.Deserialize <T>(serialized); Assert.AreEqual(data, deserialized); } Test(GenericDataVector); Test(GenericDataStruct); }
/// <summary> /// Acquires a channel from the channel pool, then publishes message based on the letter/envelope parameters. /// <para>Only throws exception when failing to acquire channel or when creating a receipt after the ReceiptBuffer is closed.</para> /// </summary> /// <param name="letter"></param> /// <param name="createReceipt"></param> /// <param name="withHeaders"></param> public async Task PublishAsync(Letter letter, bool createReceipt, bool withHeaders = true) { var error = false; var chanHost = await _channelPool .GetChannelAsync() .ConfigureAwait(false); try { chanHost.GetChannel().BasicPublish( letter.Envelope.Exchange, letter.Envelope.RoutingKey, letter.Envelope.RoutingOptions?.Mandatory ?? false, BuildProperties(letter, chanHost, withHeaders), _serializationProvider.Serialize(letter)); } catch (Exception ex) { _logger.LogDebug( LogMessages.Publishers.PublishLetterFailed, $"{letter.Envelope.Exchange}->{letter.Envelope.RoutingKey}", letter.LetterId, ex.Message); error = true; } finally { if (createReceipt) { await CreateReceiptAsync(letter, error) .ConfigureAwait(false); } await _channelPool .ReturnChannelAsync(chanHost, error); } }
public static void Setup() { Enumerable.Repeat <byte>(0xFF, 1000).ToArray().CopyTo(_data, 0); Enumerable.Repeat <byte>(0xAA, 1000).ToArray().CopyTo(_data, 1000); Enumerable.Repeat <byte>(0x1A, 1000).ToArray().CopyTo(_data, 2000); Enumerable.Repeat <byte>(0xAF, 1000).ToArray().CopyTo(_data, 3000); Enumerable.Repeat <byte>(0x01, 1000).ToArray().CopyTo(_data, 4000); MyClass.ByteData = _data; _serializationProvider = new Utf8JsonProvider(); _gzipProvider = new GzipProvider(); _deflateProvider = new DeflateProvider(); _serializedData = _serializationProvider.Serialize(MyClass).ToArray(); }
public void Utf8JsonProvider_SerializeDeserialize() { var customObject = new MyCustomClass(); var memoryStream = new MemoryStream(); _newtonsoftProvider.Serialize(memoryStream, customObject); _utf8JsonProvider.Serialize(memoryStream, customObject); Assert.NotNull(memoryStream); Assert.False(memoryStream.Length == 0); var deserializedObject = _utf8JsonProvider.Deserialize <MyCustomClass>(memoryStream); Assert.NotNull(deserializedObject); // Spot Check Assert.Equal(customObject.MyString, deserializedObject.MyString); Assert.Equal(customObject.EmbeddedClass.HappyByte, deserializedObject.EmbeddedClass.HappyByte); Assert.Equal(customObject.Data["TestKey"], Convert.ToInt32(deserializedObject.Data["TestKey"])); // deserialized int32 (as object) to double Assert.Equal(customObject.AbstractData["TestKey2"], deserializedObject.AbstractData["TestKey2"]); Assert.Equal(customObject.SubClass.Ints.ElementAt(3), deserializedObject.SubClass.Ints.ElementAt(3)); }
private string getCaptchaImageUrl(DNTCaptchaTagHelperHtmlAttributes captchaAttributes, string encryptedText) { var values = new CaptchaImageParams { Text = encryptedText, RndDate = DateTime.Now.Ticks.ToString(), ForeColor = captchaAttributes.ForeColor, BackColor = captchaAttributes.BackColor, FontSize = captchaAttributes.FontSize, FontName = captchaAttributes.FontName }; var encryptSerializedValues = _captchaProtectionProvider.Encrypt(_serializationProvider.Serialize(values)); var actionUrl = Url.Action(action: nameof(DNTCaptchaImageController.Show), controller: nameof(DNTCaptchaImageController).Replace("Controller", string.Empty), values: new { data = encryptSerializedValues, area = "" }, protocol: HttpContext.Request.Scheme); return(actionUrl); }
public void Save <TData>(TData data, string fileName) => _fileProvider.Write(_serializationProvider.Serialize(data), GetFilePath(fileName));
public void MessagePackProvider_SerializeDeserialize() { var customObject = new MyCustomClass(); Assert.Throws <MessagePack.MessagePackSerializationException>(() => _messagePackProvider.Serialize(customObject)); }
public void Save <TData>(TData data, string fileName) { var output = _serializationProvider.Serialize(data); _fileProvider.Write(output, GetFilePath(fileName)); }
public void SetData <T>(string key, T data) => SetBytes(key, _serializationProvider.Serialize(data));
public byte[] Serialize <T>(T data) => _dataTransform.Apply(_baseProvider.Serialize(data));
public byte[] GetBodyToPublish(ISerializationProvider serializationProvider) => serializationProvider.Serialize(this);
public void Send(string name, object message, Action <MessageSendError> sendError) { _receiver.Receive(name, _serializator.Serialize(message), null); }
public void OnItemSaved(object sender, EventArgs args) { var item = Sitecore.Events.Event.ExtractParameter <Item>(args, 0); _serializationProvider.Serialize(new SerializableItem(item)); }
/// <summary> /// It will serialize an object as a JSON string and then encrypt it as a Base64UrlEncode string. /// </summary> public string EncryptObject(object data, string key) { return(Encrypt(_serializationProvider.Serialize(data), key)); }