/// <summary>
        /// This class manages a string dictionary in a persisted file.
        /// </summary>
        /// <param name="FileName">File name of index file.</param>
        /// <param name="BlobFileName">Name of file in which BLOBs are stored.</param>
        /// <param name="CollectionName">Collection Name.</param>
        /// <param name="Provider">Files provider.</param>
        /// <param name="RetainInMemory">Retain the dictionary in memory.</param>
        public StringDictionary(string FileName, string BlobFileName, string CollectionName, FilesProvider Provider, bool RetainInMemory)
        {
            this.provider            = Provider;
            this.collectionName      = CollectionName;
            this.encoding            = this.provider.Encoding;
            this.timeoutMilliseconds = this.provider.TimeoutMilliseconds;
            this.genericSerializer   = new GenericObjectSerializer(this.provider);
            this.keyValueSerializer  = new KeyValueSerializer(this.provider, this.genericSerializer);

            this.recordHandler = new StringDictionaryRecords(this.collectionName, this.encoding,
                                                             (this.provider.BlockSize - ObjectBTreeFile.BlockHeaderSize) / 2 - 4, this.genericSerializer, this.provider);

            this.dictionaryFile = new ObjectBTreeFile(FileName, this.collectionName, BlobFileName,
                                                      this.provider.BlockSize, this.provider.BlobBlockSize, this.provider, this.encoding, this.timeoutMilliseconds,
#if NETSTANDARD1_5
                                                      this.provider.Encrypted, Provider.Debug, this.recordHandler);
#else
                                                      Provider.Debug, this.recordHandler);
#endif
            if (RetainInMemory)
            {
                this.inMemory = new Dictionary <string, object>();
            }
            else
            {
                this.inMemory = null;
            }
        }
        public void KeyNamingStyleTest()
        {
            var model = new { x = new { y = 1 } };

            var value = KeyValueSerializer.Serialize("root", model, null).First();

            Assert.Equal("y", value.Key);

            value = KeyValueSerializer.Serialize("root", model, new KeyValueSerializerOptions
            {
                KeyNamingStyle = KeyNamingStyle.FullName
            }).First();
            Assert.Equal("x.y", value.Key);


            value = KeyValueSerializer.Serialize("root", model, new KeyValueSerializerOptions
            {
                KeyNamingStyle = KeyNamingStyle.FullName,
                KeyDelimiter   = "|"
            }).First();
            Assert.Equal("x|y", value.Key);


            value = KeyValueSerializer.Serialize("root", model, new KeyValueSerializerOptions
            {
                KeyNamingStyle = KeyNamingStyle.FullNameWithRoot,
                KeyDelimiter   = "-"
            }).First();
            Assert.Equal("root-x-y", value.Key);
        }
Exemplo n.º 3
0
        public void TestSerializeKeyValuePair()
        {
            ISerializer <KeyValuePair <int, Guid> > ser = new KeyValueSerializer <int, Guid>(PrimitiveSerializer.Int32, PrimitiveSerializer.Guid);
            Dictionary <int, Guid> values = new Dictionary <int, Guid>
            {
                { -1, Guid.NewGuid() },
                { 0, Guid.NewGuid() },
                { 1, Guid.NewGuid() },
                { int.MaxValue, Guid.NewGuid() },
            };

            foreach (KeyValuePair <int, Guid> value in values)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    ser.WriteTo(value, ms);
                    // add random bytes, every value should know it's length and not rely on EOF.
                    byte[] bytes = new byte[256 - ms.Position];
                    _random.NextBytes(bytes);
                    ms.Write(bytes, 0, bytes.Length);
                    // seek begin and read.
                    ms.Position = 0;
                    Assert.AreEqual(value, ser.ReadFrom(ms));
                }
            }
        }
Exemplo n.º 4
0
        public static void Deserialize <T>(string param, ref T attribute) where T : IAnimationEventAttribute
        {
            KeyValueSerializer serializer = new KeyValueSerializer();

            serializer.Deserialize(param);

            attribute.OnSerialize(serializer);
        }
Exemplo n.º 5
0
 /// <summary>
 /// 键值对表单内容
 /// </summary>
 /// <param name="value">模型对象值</param>
 /// <param name="options">序列化选项</param>
 public FormContent(object?value, KeyValueSerializerOptions?options)
 {
     if (value != null)
     {
         var keyValues = KeyValueSerializer.Serialize(nameof(value), value, options);
         this.AddFormField(keyValues);
     }
     this.Headers.ContentType = new MediaTypeHeaderValue(MediaType);
 }
 public void Setup()
 {
     serializer   = new KeyValueSerializer <TestType>(new NullLogger <KeyValueSerializer <TestType> >());
     data         = new TestType();
     data.Status1 = BasicTypes.Char;
     data.Data    = "TestId";
     data.Value   = 1;
     data.Another = 2;
     data.Date    = new DateTime(2012, 02, 23);
 }
        public void TestOrderedKeyValuePairsOverloads()
        {
            IEnumerable <KeyValuePair <int, int> > e = new KeyValuePair <int, int> [0];
            OrderedKeyValuePairs <int, int>        ordered;

            ordered = new OrderedKeyValuePairs <int, int>(e);
            Assert.IsTrue(ordered.Comparer is KeyValueComparer <int, int>);
            Assert.IsTrue(ReferenceEquals(Comparer <int> .Default, ((KeyValueComparer <int, int>)ordered.Comparer).Comparer));
            Assert.AreEqual(DuplicateHandling.None, ordered.DuplicateHandling);
            Assert.AreEqual(0x10000, ordered.InMemoryLimit);
            Assert.AreEqual(null, ordered.Serializer);

            ordered = new OrderedKeyValuePairs <int, int>(new ReverseOrder <int>(Comparer <int> .Default), e);
            Assert.IsTrue(ordered.Comparer is KeyValueComparer <int, int>);
            Assert.IsTrue(((KeyValueComparer <int, int>)ordered.Comparer).Comparer is ReverseOrder <int>);
            Assert.AreEqual(DuplicateHandling.None, ordered.DuplicateHandling);
            Assert.AreEqual(0x10000, ordered.InMemoryLimit);
            Assert.AreEqual(null, ordered.Serializer);

            KeyValueSerializer <int, int> ser = new KeyValueSerializer <int, int>(PrimitiveSerializer.Int32, PrimitiveSerializer.Int32);

            ordered = new OrderedKeyValuePairs <int, int>(new ReverseOrder <int>(Comparer <int> .Default), e, ser);
            Assert.IsTrue(ordered.Comparer is KeyValueComparer <int, int>);
            Assert.IsTrue(((KeyValueComparer <int, int>)ordered.Comparer).Comparer is ReverseOrder <int>);
            Assert.AreEqual(DuplicateHandling.None, ordered.DuplicateHandling);
            Assert.AreEqual(0x10000, ordered.InMemoryLimit);
            Assert.AreEqual(ser, ordered.Serializer);

            ordered = new OrderedKeyValuePairs <int, int>(new ReverseOrder <int>(Comparer <int> .Default), e, ser, 42);
            Assert.IsTrue(ordered.Comparer is KeyValueComparer <int, int>);
            Assert.IsTrue(((KeyValueComparer <int, int>)ordered.Comparer).Comparer is ReverseOrder <int>);
            Assert.AreEqual(DuplicateHandling.None, ordered.DuplicateHandling);
            Assert.AreEqual(42, ordered.InMemoryLimit);
            Assert.AreEqual(ser, ordered.Serializer);

            ordered = new OrderedKeyValuePairs <int, int>(new ReverseOrder <int>(Comparer <int> .Default), e, PrimitiveSerializer.Int32, PrimitiveSerializer.Int32);
            Assert.IsTrue(ordered.Comparer is KeyValueComparer <int, int>);
            Assert.IsTrue(((KeyValueComparer <int, int>)ordered.Comparer).Comparer is ReverseOrder <int>);
            Assert.AreEqual(DuplicateHandling.None, ordered.DuplicateHandling);
            Assert.AreEqual(0x10000, ordered.InMemoryLimit);
            Assert.IsNotNull(ordered.Serializer);

            ordered = new OrderedKeyValuePairs <int, int>(new ReverseOrder <int>(Comparer <int> .Default), e, PrimitiveSerializer.Int32, PrimitiveSerializer.Int32, 42);
            Assert.IsTrue(ordered.Comparer is KeyValueComparer <int, int>);
            Assert.IsTrue(((KeyValueComparer <int, int>)ordered.Comparer).Comparer is ReverseOrder <int>);
            Assert.AreEqual(DuplicateHandling.None, ordered.DuplicateHandling);
            Assert.AreEqual(42, ordered.InMemoryLimit);
            Assert.IsNotNull(ordered.Serializer);
        }
Exemplo n.º 8
0
        public static void Serialize(out string param, IAnimationEventAttribute attribute)
        {
            if (attribute != null)
            {
                KeyValueSerializer serializer = new KeyValueSerializer();

                attribute.OnSerialize(serializer);

                param = serializer.SerializedText;
            }
            else
            {
                param = null;
            }
        }
        public void SerializeTest()
        {
            var obj1 = new FormatModel {
                Age = 18, Name = "lao九"
            };

            var options = new HttpApiOptions().KeyValueSerializeOptions;

            var kvs = KeyValueSerializer.Serialize("pName", obj1, options)
                      .ToDictionary(item => item.Key, item => item.Value, StringComparer.OrdinalIgnoreCase);

            Assert.True(kvs.Count == 2);
            Assert.True(kvs["Name"] == "lao九");
            Assert.True(kvs["Age"] == "18");


            kvs = KeyValueSerializer.Serialize("pName", 30, null)
                  .ToDictionary(item => item.Key, item => item.Value);

            Assert.True(kvs.Count == 1);
            Assert.True(kvs["pName"] == "30");

            var bools = KeyValueSerializer.Serialize("bool", true, null);

            Assert.Equal("true", bools[0].Value);

            var strings = KeyValueSerializer.Serialize("strings", "string", null);

            Assert.Equal("string", strings[0].Value);


            var dic = new System.Collections.Concurrent.ConcurrentDictionary <string, object>();

            dic.TryAdd("Key", "Value");

            var kvs2 = KeyValueSerializer.Serialize("dic", dic, options);

            Assert.True(kvs2.First().Key == "key");


            Assert.True(KeyValueSerializer.Serialize("null", null, null).Any());
        }
Exemplo n.º 10
0
        public async Task OnRequestAsyncTest()
        {
            var apiAction = new DefaultApiActionDescriptor(typeof(IMyApi).GetMethod("PostAsync"));
            var context   = new TestRequestContext(apiAction, new
            {
                name     = "laojiu",
                birthDay = DateTime.Parse("2010-10-10")
            });

            context.HttpContext.RequestMessage.RequestUri = new Uri("http://www.webapi.com/");
            context.HttpContext.RequestMessage.Method     = HttpMethod.Post;

            var attr = new PathQueryAttribute();
            await attr.OnRequestAsync(new ApiParameterContext(context, 0));

            var birthday = KeyValueSerializer.Serialize("time", DateTime.Parse("2010-10-10"), null)[0].Value;
            var target   = new Uri("http://www.webapi.com?name=laojiu&birthDay=" + Uri.EscapeDataString(birthday));

            Assert.True(context.HttpContext.RequestMessage.RequestUri == target);
        }
        public void ArrayIndexFormatTest()
        {
            var model = new { x = new { y = new[] { 1, 2 } } };

            var kv = KeyValueSerializer.Serialize("root", model, new KeyValueSerializerOptions
            {
                KeyNamingStyle = KeyNamingStyle.FullName
            }).First();

            Assert.Equal("x.y[0]", kv.Key);
            Assert.Equal("1", kv.Value);

            kv = KeyValueSerializer.Serialize("root", model, new KeyValueSerializerOptions
            {
                KeyNamingStyle = KeyNamingStyle.FullName,
                KeyArrayIndex  = (i) => $"({i})"
            }).First();
            Assert.Equal("x.y(0)", kv.Key);
            Assert.Equal("1", kv.Value);
        }
Exemplo n.º 12
0
        /// <summary>
        /// This class manages a string dictionary in a persisted file.
        /// </summary>
        /// <param name="CollectionName">Collection Name.</param>
        /// <param name="Provider">Files provider.</param>
        /// <param name="RetainInMemory">Retain the dictionary in memory.</param>
        private StringDictionary(string CollectionName, FilesProvider Provider, bool RetainInMemory)
        {
            this.provider            = Provider;
            this.collectionName      = CollectionName;
            this.encoding            = this.provider.Encoding;
            this.timeoutMilliseconds = this.provider.TimeoutMilliseconds;
            this.genericSerializer   = new GenericObjectSerializer(this.provider);
            this.keyValueSerializer  = new KeyValueSerializer(this.provider, this.genericSerializer);

            this.recordHandler = new StringDictionaryRecords(this.collectionName, this.encoding, this.genericSerializer, this.provider);

            if (RetainInMemory)
            {
                this.inMemory = new Dictionary <string, object>();
            }
            else
            {
                this.inMemory = null;
            }
        }
Exemplo n.º 13
0
        public async Task OnRequestAsyncTest()
        {
            var apiAction = new DefaultApiActionDescriptor(typeof(IMyApi).GetMethod("PostAsync"));
            var context   = new TestRequestContext(apiAction, new
            {
                name     = "老 九",
                birthDay = DateTime.Parse("2010-10-10")
            });

            context.HttpContext.RequestMessage.RequestUri = new Uri("http://www.mywebapi.com");
            context.HttpContext.RequestMessage.Method     = HttpMethod.Post;

            var attr = new FormContentAttribute();
            await attr.OnRequestAsync(new ApiParameterContext(context, 0));

            var body = await context.HttpContext.RequestMessage.Content.ReadAsStringAsync();

            var time   = KeyValueSerializer.Serialize("time", DateTime.Parse("2010-10-10"), null);
            var target = $"name={HttpUtility.UrlEncode("老 九", Encoding.UTF8)}&birthDay={HttpUtility.UrlEncode(time[0].Value, Encoding.UTF8)}";

            Assert.True(body.ToUpper() == target.ToUpper());
        }
Exemplo n.º 14
0
        /// <summary>
        /// Rewrite the entire BTree as a transaction to include the provided items.  This method is Thread safe.
        /// If the input is already sorted, use BulkInsertOptions overload to specify InputIsSorted = true.
        /// </summary>
        public int BulkInsert(IEnumerable <KeyValuePair <TKey, TValue> > items, BulkInsertOptions bulkOptions)
        {
            NodePin oldRoot = null;

            if (bulkOptions.InputIsSorted == false)
            {
                KeyValueSerializer <TKey, TValue> kvserializer = new KeyValueSerializer <TKey, TValue>(_options.KeySerializer, _options.ValueSerializer);
                items = new OrderedKeyValuePairs <TKey, TValue>(_options.KeyComparer, items, kvserializer)
                {
                    DuplicateHandling = bulkOptions.DuplicateHandling
                };
            }

            List <IStorageHandle> handles = new List <IStorageHandle>();

            try
            {
                int counter = 0;
                using (RootLock root = LockRoot(LockType.Insert, "Merge", false))
                {
                    if (root.Pin.Ptr.Count != 1)
                    {
                        throw new InvalidDataException();
                    }

                    NodeHandle oldRootHandle = root.Pin.Ptr[0].ChildNode;
                    oldRoot = _storage.Lock(root.Pin, oldRootHandle);

                    if (oldRoot.Ptr.Count == 0 || bulkOptions.ReplaceContents)
                    {
                        // Currently empty, so just enforce duplicate keys...
                        items = OrderedKeyValuePairs <TKey, TValue>
                                .WithDuplicateHandling(items,
                                                       new KeyValueComparer <TKey, TValue>(_options.KeyComparer),
                                                       bulkOptions.DuplicateHandling);
                    }
                    else
                    {
                        // Merging with existing data and enforce duplicate keys...
                        items = OrderedKeyValuePairs <TKey, TValue>
                                .Merge(_options.KeyComparer, bulkOptions.DuplicateHandling, EnumerateNodeContents(oldRoot), items);
                    }

                    Node newtree = BulkWrite(handles, ref counter, items);
                    if (newtree == null) // null when enumeration was empty
                    {
                        return(0);
                    }

                    using (NodeTransaction trans = _storage.BeginTransaction())
                    {
                        Node rootNode = trans.BeginUpdate(root.Pin);
                        rootNode.ReplaceChild(0, oldRootHandle, new NodeHandle(newtree.StorageHandle));
                        trans.Commit();
                    }

                    _count = counter;
                }

                //point of no return...
                handles.Clear();
                DeleteTree(oldRoot);
                oldRoot = null;

                if (bulkOptions.CommitOnCompletion)
                {
                    //Since transaction logs do not deal with bulk-insert, we need to commit our current state
                    Commit();
                }
                return(counter);
            }
            catch
            {
                if (oldRoot != null)
                {
                    oldRoot.Dispose();
                }

                foreach (IStorageHandle sh in handles)
                {
                    try { _storage.Storage.Destroy(sh); }
                    catch (ThreadAbortException) { throw; }
                    catch { continue; }
                }
                throw;
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// 序列化参数值为键值对
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static IList <KeyValue> SerializeToKeyValues(this ApiParameterContext context)
        {
            var options = context.HttpContext.HttpApiOptions.KeyValueSerializeOptions;

            return(KeyValueSerializer.Serialize(context.ParameterName, context.ParameterValue, options));
        }
Exemplo n.º 16
0
 public void OnSerialize(KeyValueSerializer serializer)
 {
     serializer.Serialize("EventName", ref animationGameEvent);
     serializer.Serialize("Argument", ref Argument);
     //	serializer.Serialize("ENABLEATTACK_EVENTNUM", ref enableAttackEventNum);
 }