/// <summary>
        /// Test dictionary insert/replace/delete.
        /// </summary>
        /// <typeparam name="TKey">Key type of the dictionary.</typeparam>
        /// <typeparam name="TValue">Value type of the dictionary.</typeparam>
        /// <param name="dictionary">The dictionary to test.</param>
        /// <param name="key">Key that is present in the dictionary.</param>
        /// <param name="value">Value associated with the key in the dictionary.</param>
        private static void TestBasicOperations <TKey, TValue>(PersistentDictionary <TKey, TValue> dictionary, TKey key, TValue value)
            where TKey : IComparable <TKey>
        {
            var kvp = new KeyValuePair <TKey, TValue>(key, value);

            // Add a record
            dictionary.Add(key, value);

            // Test PersistentDictionary.Add error handling
            try
            {
                dictionary.Add(key, value);
                Assert.Fail("Expected ArgumentException from Add");
            }
            catch (ArgumentException)
            {
                // Expected
            }

            // Overwrite a value
            dictionary[key] = value;

            // Retrieve a value
            Assert.AreEqual(value, dictionary[key], "Retrieve with [] failed");
            TValue t;

            Assert.IsTrue(dictionary.TryGetValue(key, out t), "TryGetValue({0}) failed", key);
            Assert.AreEqual(value, t, "TryGetValue({0}) returned the wrong value", key);

            // Clear and re-insert
            dictionary.Clear();
            Assert.AreEqual(0, dictionary.Count, "Dictionary is empty. Count is wrong");
            dictionary[key] = value;
            Assert.AreEqual(1, dictionary.Count, "Item was just inserted. Count is wrong");

            // Get the keys and values
            Assert.AreEqual(dictionary.Keys.First(), key, "Keys collection");
            Assert.AreEqual(dictionary.Values.First(), value, "Values collection");

            // Test PersistentDictionary.Contains (true)
            Assert.IsTrue(dictionary.ContainsKey(key), "Dictionary should have contained key {0}", key);
            Assert.IsTrue(dictionary.ContainsValue(value), "Dictionary should have contained value {0}", value);
            Assert.IsTrue(dictionary.Contains(kvp), "Dictionary should have contained <{0},{1}>", key, value);

            // Test PersistentDictionary.Remove
            Assert.IsTrue(dictionary.Remove(key), "Key {0} should exist, but removal failed", key);
            Assert.IsFalse(dictionary.Remove(key), "Key {0} doesn't exist, but removal succeeded", key);

            dictionary.Add(kvp);
            Assert.IsTrue(dictionary.Remove(kvp), "KeyValuePair <{0},{1}> should exist, but removal failed", kvp.Key, kvp.Value);
            Assert.IsFalse(dictionary.Remove(kvp), "KeyValuePair <{0},{1}> doesn't exist, but removal succeeded", kvp.Key, kvp.Value);

            // Test PersistentDictionary.Contains (false)
            Assert.IsFalse(dictionary.ContainsKey(key), "Dictionary should have contained key {0}", key);
            Assert.IsFalse(dictionary.ContainsValue(value), "Dictionary should have contained value {0}", value);
            Assert.IsFalse(dictionary.Contains(kvp), "Dictionary should have contained <{0},{1}>", key, value);
        }
Пример #2
0
 public void TestDictionary()
 {
     var a = new PersistentDictionary<string, int>();
     a.Add("one", 1);
     a.Store();
     a.Add("two", 2);
     a.Undo();
     Assert.True(a.Count == 1);
     Assert.True(a["one"] == 1);
     a.Redo();
     Assert.True(a.Count == 2);
     Assert.True(a["one"] == 1);
     Assert.True(a["two"] == 2);
 }
Пример #3
0
        //protected void InitializeConfiguration(IConfig config)
        //{

        //    var hostKey = config[BlobContainerLocalConfig.ContainerHost];
        //    _containerName = config[BlobContainerLocalConfig.ContainerName];


        //    _host = hostKey;

        //    _container = _containerName;
        //    _access = (EntityAccess)Enum.Parse(typeof(EntityAccess),
        //                                        config.Get(BlobContainerLocalConfig.OptionalAccess,
        //                                                   EntityAccess.Private.ToString()));
        //}

        protected void InternalSaveObject <TData>(string objId, TData obj)
        {
            try
            {
                if (mutex.Wait(TimeSpan.FromSeconds(DefaultTime)))
                {
                    var data = JsonConvert.SerializeObject(obj);
                    if (_persistentDictionary.ContainsKey(objId))
                    {
                        _persistentDictionary[objId] = data;
                    }
                    else
                    {
                        _persistentDictionary.Add(objId, data);
                    }

                    _persistentDictionary.Flush();
                    mutex.Release();
                }
            }
            catch (Exception ex)
            {
                throw new BlobAccessException(ex);
            }
        }
Пример #4
0
 public void Put(string key, object value)
 {
     if (_persistentDictionary != null && !_disposing)
     {
         _persistentDictionary.Add(key, value.ToJson());
     }
 }
Пример #5
0
 private void addLogEntry(logEntry_t logEntry)
 {
     using (PersistentDictionary <DateTime, logEntry_t> dictionary = new PersistentDictionary <DateTime, logEntry_t>(logpath))
     {
         dictionary.Add(DateTime.Now, logEntry);
     }
     this.Notify();
 }
Пример #6
0
 public void addConfigEntry(string key, string configEntryValue)
 {
     using (PersistentDictionary <string, string> dictionary = new PersistentDictionary <string, string>(getConfigLogPath()))
     {
         if (!dictionary.ContainsKey(key))
         {
             dictionary.Add(key, configEntryValue);
         }
     }
 }
Пример #7
0
        static void Benchmark()
        {
            var payload = new byte[4 * 1024];

            var dir = "temp";
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);

            Utility.Timeit("File system", 1, () =>
            {
                var random = new Random();
                for (var i = 0; i < 40000; ++i)
                {
                    var path = string.Format("{0}/{1}.txt", dir, random.Next(1000));
                    switch (random.Next(2))
                    {
                        case 0:
                            File.WriteAllBytes(path, payload);
                            break;
                        case 1:
                            if (File.Exists(path)) File.Delete(path);
                            break;
                        default:
                            throw new NotSupportedException();
                    }
                }
            });

            Utility.Timeit("PersistentDictionary", 1, () =>
            {
                if (File.Exists("1.txt"))
                    File.Delete("1.txt");

                var random = new Random();
                using (var dict = new PersistentDictionary("1.txt"))
                {
                    for (var i = 0; i < 40000; ++i)
                    {
                        var key = string.Format("{0}/{1}.txt", dir, random.Next(1000));
                        switch (random.Next(2))
                        {
                            case 0:
                                if (dict.ContainsKey(key)) dict[key] = payload;
                                else dict.Add(key, payload);
                                break;
                            case 1:
                                if (dict.ContainsKey(key)) dict.Remove(key);
                                break;
                            default:
                                throw new NotSupportedException();
                        }
                    }
                }
            });
        }
 public static void FillStore(string folder, PersistentDictionary <string, string> dic)
 {
     foreach (string rawFile in ListRawFiles(folder))
     {
         string source = PeptidAce.Utilities.vsCSV.GetFileName_NoExtension(rawFile);
         if (!dic.ContainsKey(source))
         {
             dic.Add(source, rawFile);
         }
     }
 }
Пример #9
0
        public void BuildStore(int minPepLength = 8, int maxPepLength = 14)
        {
            for (int size = maxPepLength; size >= minPepLength; size--)
            {
                Dictionary <int, StringBuilder> dicOfStr     = new Dictionary <int, StringBuilder>();
                Combinations <char>             combinations = new Combinations <char>(new List <char>(PeptidAce.AminoAcidMasses.VALID_AMINO_ACIDS), size, GenerateOption.WithRepetition);
                foreach (IList <char> str in combinations)
                {
                    string sequence = string.Concat(str);
                    double mass     = PeptidAce.AminoAcidPolymer.ComputeMonoisotopicMass(sequence);
                    double dIndex   = mass / Precision;
                    int    index    = (int)dIndex;
                    if (dicOfStr.ContainsKey(index))
                    {
                        dicOfStr[index].Append("," + sequence);
                    }
                    else
                    {
                        dicOfStr.Add(index, new StringBuilder(sequence));
                    }

                    if (index > dIndex)
                    {
                        index--;
                    }
                    else
                    {
                        index++;
                    }

                    if (dicOfStr.ContainsKey(index))
                    {
                        dicOfStr[index].Append("," + sequence);
                    }
                    else
                    {
                        dicOfStr.Add(index, new StringBuilder(sequence));
                    }
                }

                //Now that its all in memory, fill dictionnary
                foreach (KeyValuePair <int, StringBuilder> pair in dicOfStr)
                {
                    if (Dictionary.ContainsKey(pair.Key))
                    {
                        Dictionary[pair.Key] += pair.Value.ToString();
                    }
                    else
                    {
                        Dictionary.Add(pair.Key, pair.Value.ToString());
                    }
                }
            }
        }
Пример #10
0
 public void changeConfig(string name, string value)
 {
     using (PersistentDictionary <string, string> dictionary = new PersistentDictionary <string, string>(getConfigLogPath()))
     {
         if (dictionary.ContainsKey(name))
         {
             dictionary.Remove(name);
             dictionary.Add(name, value);
         }
     }
 }
Пример #11
0
        public virtual PersistentDictionary <string, StoreSetting> LoadDictionaryForStore()
        {
            PersistentCollection <StoreSetting>         settingCollection = StoreSettingDataSource.LoadForStore();
            PersistentDictionary <string, StoreSetting> settingDictionary = new PersistentDictionary <string, StoreSetting>();

            foreach (StoreSetting setting in settingCollection)
            {
                settingDictionary.Add(setting.FieldName, setting);
            }
            return(settingDictionary);
        }
Пример #12
0
        public void Start(CancellationTokenSource cancelationTokenSource)
        {
            //асинхронен хендлър - Consume<T>(IQueue queue, Func<IMessage<T>, MessageReceivedInfo, Task> onMessage)
            //Consume(queue, (body, properties, info) => Task.Factory.StartNew(() =>
            //{
            //var message = Encoding.UTF8.GetString(body);
            //Console.WriteLine("Got message: '{0}'", message);
            //}));
            //bus.Advanced.Consume(

            //синхронен хендлър - Consume<T>(IQueue queue, Action<IMessage<T>, MessageReceivedInfo> on Message)
            bus.Advanced.Consume <EasyNetQ.SystemMessages.Error>(queue, (message, info) =>
            {
                try
                {
                    using (var processedErrorMessages = new PersistentDictionary <string, int>(instancePersistenceFolder))
                    {
                        var key        = message.Body.BasicProperties.CorrelationId;
                        int retryCount = 1;
                        if (processedErrorMessages.ContainsKey(key))
                        {
                            retryCount = processedErrorMessages[key];
                            processedErrorMessages[key] = ++retryCount;
                        }
                        else
                        {
                            processedErrorMessages.Add(key, retryCount);
                        }


                        var msgBody = message.Body;

                        var className = getClassNameFromExchange(msgBody.Exchange);

                        log.InfoFormat(
                            "Processing ErrorQueue Message. DateTime = {0}, RetryCount = {1}, Message = {2}",
                            msgBody.DateTime,
                            retryCount,
                            msgBody.Message);

                        applyStrategies(className, retryCount, msgBody);
                    }
                }
                catch (Exception ex)
                {
                    if (!cancelationTokenSource.IsCancellationRequested)
                    {
                        log.ErrorFormat("ERROR Consuming message from ErrorQueue! {0}", ex);
                    }
                }
            });
        }
Пример #13
0
        private void Store(long index, string text)
        {
            if (index < 0)
            {
                throw new InvalidOperationException("Event index must be >= 0!");
            }
            if (_directory.ContainsKey(index))
            {
                throw new InvalidOperationException($"Event with index {index} has already been stored and cannot be overwritten!");
            }

            _directory.Add(index, text);
        }
Пример #14
0
        private void AddRow(int id)
        {
            if (dict.ContainsKey(id))
            {
                return;
            }

            var cust = new Customer();

            cust.Name         = customerNames[rnd.Next(0, customerNames.Length)];
            cust.TotalRevenue = id;

            dict.Add(id, cust);
        }
        /// <summary>
        /// Run a set of tests against a dictionary.
        /// </summary>
        /// <typeparam name="TKey">Key type of the dictionary.</typeparam>
        /// <typeparam name="TValue">Value type of the dictionary.</typeparam>
        /// <param name="dictionary">The dictionary to test.</param>
        /// <param name="key">Key value to use.</param>
        /// <param name="value">Data value to use.</param>
        private static void RunDictionaryTests <TKey, TValue>(PersistentDictionary <TKey, TValue> dictionary, TKey key, TValue value)
            where TKey : IComparable <TKey>
        {
            Assert.IsFalse(dictionary.IsReadOnly, "Dictionary is read-only");
            Assert.AreEqual(DictionaryPath, dictionary.Database);

            TestBasicOperations(dictionary, key, value);

            // Add the value
            var kvp = new KeyValuePair <TKey, TValue>(key, value);

            dictionary.Add(kvp);

            dictionary.Flush();

            TestDictionaryLinq(dictionary, key, value);
            TestDictionaryKeysLinq(dictionary, key);
            TestDictionaryEnumeration(dictionary, key, value);
            TestDictionaryCopyTo(dictionary, key, value);
        }
Пример #16
0
        static void Test()
        {
            using (var dict = new PersistentDictionary("1.txt"))
            {
                string line;
                while ((line = Console.ReadLine()) != null)
                {
                    try
                    {
                        var tokens = line.Split();
                        switch (tokens[0].ToLower())
                        {
                            case "add":
                                dict.Add(tokens[1], Encoding.UTF8.GetBytes(tokens[2]));
                                break;
                            case "update":
                                dict[tokens[1]] = Encoding.UTF8.GetBytes(tokens[2]);
                                break;
                            case "remove":
                                dict.Remove(tokens[1]);
                                break;
                            case "dump":
                                {
                                    foreach (var kv in dict.OrderBy(kv => kv.Key))
                                        Console.WriteLine("\t{0}: {1}", kv.Key, Encoding.UTF8.GetString(kv.Value));
                                }
                                break;
                            default:
                                throw new NotSupportedException();
                        }

                        Console.WriteLine("Done.");
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
        }
 public void Put <T>(string key, T value)
 {
     _persistentDictionary.Add(key, value.ToJson());
     _persistentDictionary.Flush();
 }
        private void ProcessingThread()
        {
            // Start AcquireFrame/ReleaseFrame loop
            while (senseManager.AcquireFrame(true) >= pxcmStatus.PXCM_STATUS_NO_ERROR)
            {
                // Acquire the color image data
                PXCMCapture.Sample  sample = senseManager.QuerySample();
                Bitmap              colorBitmap;
                PXCMImage.ImageData colorData;
                int            topScore   = 0;
                FaceExpression expression = FaceExpression.None;

                sample.color.AcquireAccess(PXCMImage.Access.ACCESS_READ, PXCMImage.PixelFormat.PIXEL_FORMAT_RGB24, out colorData);
                colorBitmap = colorData.ToBitmap(0, sample.color.info.width, sample.color.info.height);

                try
                {
                    IBarcodeReader reader = new BarcodeReader();
                    // load a bitmap
                    //var barcodeBitmap = (Bitmap)Bitmap.LoadFrom("C:\\sample-barcode-image.png");
                    // detect and decode the barcode inside the bitmap
                    var result = reader.Decode(colorBitmap);
                    // do something with the result
                    if (result != null)
                    {
                        MessageBox.Show(result.BarcodeFormat.ToString());
                        MessageBox.Show(result.Text);
                    }
                }
                catch (Exception ex)
                {
                }

                // Get face data
                if (faceData != null)
                {
                    faceData.Update();
                    numFacesDetected = faceData.QueryNumberOfDetectedFaces();

                    if (numFacesDetected > 0)
                    {
                        // Get the first face detected (index 0)
                        PXCMFaceData.Face face = faceData.QueryFaceByIndex(0);

                        // Retrieve face location data
                        PXCMFaceData.DetectionData faceDetectionData = face.QueryDetection();
                        if (faceDetectionData != null)
                        {
                            PXCMRectI32 faceRectangle;
                            faceDetectionData.QueryBoundingRect(out faceRectangle);
                            if ((faceRectangle.h > 90) || (faceRectangle.w > 90))
                            {
                                faceRectangleHeight = faceRectangle.h * 3 / 2;
                                faceRectangleWidth  = faceRectangle.w * 3 / 2;
                            }
                            else if (((faceRectangle.h < 90) || (faceRectangle.w < 90)) && ((faceRectangle.h > 70) || (faceRectangle.w > 70)))
                            {
                                faceRectangleHeight = faceRectangle.h * 2;
                                faceRectangleWidth  = faceRectangle.w * 2;
                            }
                            else
                            {
                                faceRectangleHeight = faceRectangle.h * 5 / 2;
                                faceRectangleWidth  = faceRectangle.w * 5 / 2;
                            }
                            faceRectangleX = faceRectangle.x;
                            faceRectangleY = faceRectangle.y;
                        }

                        // Retrieve pose estimation data
                        PXCMFaceData.PoseData facePoseData = face.QueryPose();
                        if (facePoseData != null)
                        {
                            PXCMFaceData.PoseEulerAngles headAngles;
                            facePoseData.QueryPoseAngles(out headAngles);
                            headRoll  = headAngles.roll;
                            headPitch = headAngles.pitch;
                            headYaw   = headAngles.yaw;
                        }

                        // Retrieve expression data
                        PXCMFaceData.ExpressionsData expressionData = face.QueryExpressions();

                        if (expressionData != null)
                        {
                            PXCMFaceData.ExpressionsData.FaceExpressionResult score;

                            expressionData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_KISS, out score);
                            expressionScore[Convert.ToInt32(FaceExpression.Kiss)] = score.intensity;

                            expressionData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_MOUTH_OPEN, out score);
                            expressionScore[Convert.ToInt32(FaceExpression.Open)] = score.intensity;

                            expressionData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_SMILE, out score);
                            expressionScore[Convert.ToInt32(FaceExpression.Smile)] = score.intensity;

                            expressionData.QueryExpression(PXCMFaceData.ExpressionsData.FaceExpression.EXPRESSION_TONGUE_OUT, out score);


                            expressionScore[Convert.ToInt32(FaceExpression.Tongue)] = score.intensity;

                            // Determine the highest scoring expression
                            for (int i = 1; i < TotalExpressions; i++)
                            {
                                if (expressionScore[i] > topScore)
                                {
                                    expression = (FaceExpression)i;
                                }
                            }
                        }

                        // Process face recognition data
                        if (face != null)
                        {
                            // Retrieve the recognition data instance
                            recognitionData = face.QueryRecognition();

                            // Set the user ID and process register/unregister logic
                            if (recognitionData.IsRegistered())
                            {
                                userId = Convert.ToString(recognitionData.QueryUserID());

                                if (doUnregister)
                                {
                                    recognitionData.UnregisterUser();
                                    SaveDatabaseToFile();
                                    doUnregister = false;
                                    if (_persistentDict.ContainsKey(userId) == true)
                                    {
                                        _persistentDict.Remove(userId);
                                    }
                                }
                            }
                            else
                            {
                                if (doRegister)
                                {
                                    int uId = recognitionData.RegisterUser();
                                    SaveDatabaseToFile();

                                    if (newUserName != "")
                                    {
                                        if (_persistentDict.ContainsKey(uId.ToString()) == false)
                                        {
                                            _persistentDict.Add(uId.ToString(), newUserName);
                                            _persistentDict.Flush();
                                            newUserName = "";
                                        }
                                    }

                                    // Capture a jpg image of registered user
                                    colorBitmap.Save("image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);

                                    doRegister = false;
                                }
                                else
                                {
                                    userId = "New User";
                                }
                            }
                        }
                    }
                    else
                    {
                        userId = "No users in view";
                    }
                }

                //hand = senseManager.QueryHand();

                //if (hand != null)
                //{

                //    // Retrieve the most recent processed data
                //    handData = hand.CreateOutput();
                //    handData.Update();

                //    // Get number of tracked hands
                //    nhands = handData.QueryNumberOfHands();

                //    if (nhands > 0)
                //    {
                //        // Retrieve hand identifier
                //        handData.QueryHandId(PXCMHandData.AccessOrderType.ACCESS_ORDER_BY_TIME, 0, out handId);

                //        // Retrieve hand data
                //        handData.QueryHandDataById(handId, out ihand);

                //        PXCMHandData.BodySideType bodySideType = ihand.QueryBodySide();
                //        if (bodySideType == PXCMHandData.BodySideType.BODY_SIDE_LEFT)
                //        {
                //            leftHand = true;
                //        }
                //        else if (bodySideType == PXCMHandData.BodySideType.BODY_SIDE_RIGHT)
                //        {
                //            leftHand = false;
                //        }



                //        // Retrieve all hand joint data
                //        for (int i = 0; i < nhands; i++)
                //        {
                //            for (int j = 0; j < 0x20; j++)
                //            {
                //                PXCMHandData.JointData jointData;
                //                ihand.QueryTrackedJoint((PXCMHandData.JointType)j, out jointData);
                //                nodes[i][j] = jointData;
                //            }
                //        }

                //        // Get world coordinates for tip of middle finger on the first hand in camera range
                //        handTipX = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.x;
                //        handTipY = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.y;
                //        handTipZ = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionWorld.z;


                //        swipehandTipX = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionImage.x;
                //        swipehandTipY = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionImage.y;
                //        swipehandTipZ = nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].positionImage.z;

                //        //Console.Out.WriteLine("Before x={0}", swipehandTipX);
                //        //Console.Out.WriteLine("Before speed={0}", nodes[0][Convert.ToInt32(PXCMHandData.JointType.JOINT_MIDDLE_TIP)].speed.x);

                //        // Retrieve gesture data
                //        if (handData.IsGestureFired("spreadfingers", out gestureData)) { gesture = Gesture.FingerSpread; }
                //        else if (handData.IsGestureFired("two_fingers_pinch_open", out gestureData)) { gesture = Gesture.Pinch; }
                //        else if (handData.IsGestureFired("wave", out gestureData)) { gesture = Gesture.Wave; }
                //        else if (handData.IsGestureFired("swipe_left", out gestureData)) { gesture = Gesture.SwipeLeft; }
                //        else if (handData.IsGestureFired("swipe_right", out gestureData)) { gesture = Gesture.SwipeRight; }
                //        else if (handData.IsGestureFired("fist", out gestureData)) { gesture = Gesture.Fist; }
                //        else if (handData.IsGestureFired("thumb_up", out gestureData)) { gesture = Gesture.Thumb; }

                //    }
                //    else
                //    {
                //        gesture = Gesture.Undefined;
                //    }

                //    //UpdateUI();
                //    if (handData != null) handData.Dispose();
                //}

                // Display the color stream and other UI elements
                //UpdateUI(colorBitmap, expression, gesture);


                UpdateUI(colorBitmap, expression);

                // Release resources
                colorBitmap.Dispose();
                sample.color.ReleaseAccess(colorData);
                sample.color.Dispose();

                // Release the frame
                senseManager.ReleaseFrame();
            }
        }
Пример #19
0
 public void Add(int cep, string statusProcessamento)
 {
     CheckCacheOpened();
     pairs.Add(cep, statusProcessamento);
     pairs.Flush();
 }
Пример #20
0
        public void Collections()
        {
            Common.Reset();
            using (Database database = Database.Get(Common.DatabaseName))
            {
                database.Add("Doc", "<Doc/>");
                Element elem = database.GetDocument("Doc").Root;
                Assert.IsNotNull(elem);

                // Add content
                List <int> numbers = new List <int>();
                using (new Updates())
                {
                    for (int c = 0; c < 10; c++)
                    {
                        elem.Append(String.Format("<A x='{0}'><B y='{1}'>{2}</B><C>{3}</C></A>",
                                                  c, c * 2, c * 3, c * 4));
                        numbers.Add(c);
                    }
                }

                // Create and attach a dictionary
                PersistentDictionary <int, string> dictionary = new PersistentDictionary <int, string>(
                    new PersistentKvpCollectionAttribute()
                {
                    Query            = ".", ItemQuery = "./A",
                    KeyAttributeName = "x", ValueElementName = "C"
                });
                dictionary.Attach(elem);
                CollectionAssert.AreEqual(numbers, dictionary.Keys);
                CollectionAssert.AreEqual(numbers.Select(n => (n * 4).ToString()), dictionary.Values);

                // Create and attach a list
                PersistentList <int> list = new PersistentList <int>(
                    new PersistentCollectionAttribute()
                {
                    Query = ".", ItemQuery = "./A/B"
                });
                list.Attach(elem);
                CollectionAssert.AreEqual(numbers.Select(n => n * 3), list);

                // Change the database (remove every other)
                for (int c = 9; c >= 0; c -= 2)
                {
                    elem.Child(c).Remove();
                    numbers.RemoveAt(c);
                }
                Manager.Default.FetchAll();
                CollectionAssert.AreEqual(numbers, dictionary.Keys);
                CollectionAssert.AreEqual(numbers.Select(n => (n * 4).ToString()), dictionary.Values);
                CollectionAssert.AreEqual(numbers.Select(n => n * 3), list);

                // Change the dictionary and attempt to store
                dictionary.Add(20, (20 * 4).ToString());
                Assert.Throws(Is.InstanceOf <Exception>(), dictionary.Store);

                // Refetch and verify
                dictionary.Fetch();
                CollectionAssert.AreEqual(numbers, dictionary.Keys);
                CollectionAssert.AreEqual(numbers.Select(n => (n * 4).ToString()), dictionary.Values);
            }
        }
Пример #21
0
 public void TestPersistentStructureDictionary()
 {
     var a = new PersistentDictionary<string, Persistent<int>>();
     a.Add("one", new Persistent<int>(1));
     a.Store();
     a["one"].Value = 2;
     a.Undo();
     Assert.True(a["one"].Value == 1);
     a.Redo();
     Assert.True(a["one"].Value == 2);
 }