Ejemplo n.º 1
0
        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));
        }
Ejemplo n.º 2
0
        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));
        }
Ejemplo n.º 3
0
 public TData Load <TData>(string fileName) =>
 _serializationProvider
 .Deserialize <TData>(_fileProvider.Read(GetFilePath(fileName)));
        public IActionResult Refresh(string data)
        {
            if (string.IsNullOrWhiteSpace(data))
            {
                return(BadRequest());
            }

            var decryptedModel = _captchaProtectionProvider.Decrypt(data);

            if (decryptedModel == null)
            {
                return(BadRequest());
            }

            var model = _serializationProvider.Deserialize <DNTCaptchaTagHelperHtmlAttributes>(decryptedModel);

            if (model == null)
            {
                return(BadRequest());
            }

            invalidateToken(model);

            var tagHelper = HttpContext.RequestServices.GetRequiredService <DNTCaptchaTagHelper>();

            tagHelper.BackColor              = model.BackColor;
            tagHelper.FontName               = model.FontName;
            tagHelper.FontSize               = model.FontSize;
            tagHelper.ForeColor              = model.ForeColor;
            tagHelper.Language               = model.Language;
            tagHelper.Max                    = model.Max;
            tagHelper.Min                    = model.Min;
            tagHelper.Placeholder            = model.Placeholder;
            tagHelper.TextBoxClass           = model.TextBoxClass;
            tagHelper.TextBoxTemplate        = model.TextBoxTemplate;
            tagHelper.ValidationErrorMessage = model.ValidationErrorMessage;
            tagHelper.ValidationMessageClass = model.ValidationMessageClass;
            tagHelper.RefreshButtonClass     = model.RefreshButtonClass;
            tagHelper.DisplayMode            = model.DisplayMode;
            tagHelper.UseRelativeUrls        = model.UseRelativeUrls;
            tagHelper.UseNoise               = model.UseNoise;

            var tagHelperContext = new TagHelperContext(
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary <object, object> {
                { typeof(IUrlHelper), this.Url }
            },
                uniqueId: Guid.NewGuid().ToString("N"));

            var tagHelperOutput = new TagHelperOutput(
                tagName: "div",
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (useCachedResult, encoder) =>
            {
                var tagHelperContent = new DefaultTagHelperContent();
                tagHelperContent.SetContent(string.Empty);
                return(Task.FromResult <TagHelperContent>(tagHelperContent));
            });

            tagHelper.ViewContext = ViewContext ?? new ViewContext(
                new ActionContext(this.HttpContext, HttpContext.GetRouteData(), ControllerContext.ActionDescriptor),
                new FakeView(),
                new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
            {
                Model = null
            },
                new TempDataDictionary(this.HttpContext, _tempDataProvider),
                TextWriter.Null,
                new HtmlHelperOptions());

            tagHelper.Process(tagHelperContext, tagHelperOutput);

            var attrs = new StringBuilder();

            foreach (var attr in tagHelperOutput.Attributes)
            {
                attrs.Append(' ').Append(attr.Name).Append("='").Append(attr.Value).Append('\'');
            }

            var content = $"<div {attrs}>{tagHelperOutput.Content.GetContent()}</div>";

            return(Content(content));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Retrieve an item from the cache
        /// </summary>
        /// <typeparam name="T">Object type to return</typeparam>
        /// <param name="key">Key</param>
        /// <returns>Object of type T associated with the key</returns>
        public T Get <T>(string key)
        {
            // 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;

            int keyHashSlot = -1; // -1 is used as a sentinel value used to determine if the key's hash slot has already been computed

            // attempt to retreive value from the in-process cache

            var inProcessCacheEntry = _inProcessCache.Get(key) as LocalCacheEntry <T>;

            if (inProcessCacheEntry != null)
            {
                // found the entry in the in-process cache, now
                // need to check if the entry may be stale and we
                // need to re-read from Redis

                keyHashSlot = inProcessCacheEntry.KeyHashSlot;

                // Check the timestamp of the cache entry versus the _lastUpdated array
                // If the timestamp of the cache entry is greater than what's in _lastUpdated,
                // then we can just return the value from the in-process cache

                // Could use and Interlocked operation here, but lock is a more obvious in intent

                lock (_lastUpdated)
                {
                    if (_lastUpdated[keyHashSlot] < inProcessCacheEntry.Timestamp)
                    {
                        return((T)inProcessCacheEntry.Data);
                    }
                }
            }

            // if we've made it to here, the key is either not in the in-process cache or
            // the in-process cache entry is stale.  In either case we need to hit Redis to
            // get the correct value, and the key's remaining TTL in Redis

            T value = default(T);

            string luaScript = @"
        local result={}
        result[1] = redis.call('GET', KEYS[1])
        result[2] = redis.call('TTL', KEYS[1])
        return result;
      ";

            RedisValue[] results = (RedisValue[])_redisDb.ScriptEvaluate(luaScript, new RedisKey[] { key });

            if (!results[0].IsNull)
            {
                var serializedData = (byte[])results[0];

                if (serializedData.Length > 0)
                {
                    // Deserialize the bytes returned from Redis

                    using (MemoryStream ms = new MemoryStream(serializedData))
                    {
                        value = _serializationProvider.Deserialize <T>(ms);
                    }

                    // Don't want to have to recalculate the hashslot twice, so test if it's already
                    // been computed

                    if (keyHashSlot == -1)
                    {
                        keyHashSlot = HashSlotCalculator.CalculateHashSlot(key);
                    }

                    // Update the in-proces cache with the value retrieved from Redis

                    _inProcessCache.Set(key, new LocalCacheEntry <T>((ushort)keyHashSlot, timestamp, value), DateTimeOffset.UtcNow.AddSeconds((double)results[1]));
                }
            }

            return((T)inProcessCacheEntry.Data);
        }
 /// <summary>
 /// It will decrypt a Base64UrlEncode encrypted JSON string and then deserialize it as an object.
 /// </summary>
 public T DecryptObject <T>(string data)
 {
     return(_serializationProvider.Deserialize <T>(Decrypt(data)));
 }
 public T Deserialize <T>(byte[] data) =>
 _baseProvider.Deserialize <T>(_dataTransform.Reverse(data));
Ejemplo n.º 8
0
 public T GetData <T>(string key) =>
 _serializationProvider.Deserialize <T>(GetBytes(key));
Ejemplo n.º 9
0
        public TData Load <TData>(string fileName)
        {
            var output = _fileProvider.Read(GetFilePath(fileName));

            return(_serializationProvider.Deserialize <TData>(output));
        }