Ejemplo n.º 1
0
        public static JsonStyles FromString(string inlineStyles)
        {
            JsonStyles retVal = new JsonStyles();

            retVal.styles = DictionaryExtensions.FromDelimited(inlineStyles, ";", ":");
            return(retVal);
        }
Ejemplo n.º 2
0
 public void Deserilize(Stream stream)
 {
     this._selfProperties       = stream.ReadObject <Dictionary <object, object> >();
     this.LobbyCustomProperties = stream.ReadObject <Dictionary <object, object> >();
     //服务器传来的是包含置空的值,需要排除掉
     this.OtherCustomProperties = DictionaryExtensions.BytesDictToProp(stream.ReadObject <Dictionary <object, object> >(), false);
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets lexically related words for the current synset. Many of the relations in WordNet are lexical instead of semantic. Whereas
        /// the latter indicate relations between entire synsets (e.g., hypernym), the former indicate relations between specific
        /// words in synsets. This method retrieves all lexical relations and the words related thereby.
        /// </summary>
        /// <returns>Mapping from relations to mappings from words in the current synset to related words in the related synsets</returns>
        public Dictionary <WordNetEngine.SynSetRelation, Dictionary <string, Set <string> > > GetLexicallyRelatedWords()
        {
            Dictionary <WordNetEngine.SynSetRelation, Dictionary <string, Set <string> > > relatedWords = new Dictionary <WordNetEngine.SynSetRelation, Dictionary <string, Set <string> > >();

            foreach (WordNetEngine.SynSetRelation relation in _lexicalRelations.Keys)
            {
                DictionaryExtensions.EnsureContainsKey(relatedWords, relation, typeof(Dictionary <string, Set <string> >));               //ZK changed to static method

                foreach (SynSet relatedSynSet in _lexicalRelations[relation].Keys)
                {
                    // make sure related synset is initialized
                    if (!relatedSynSet.Instantiated)
                    {
                        relatedSynSet.Instantiate();
                    }

                    foreach (int sourceWordIndex in _lexicalRelations[relation][relatedSynSet].Keys)
                    {
                        string sourceWord = _words[sourceWordIndex - 1];

                        DictionaryExtensions.EnsureContainsKey(relatedWords[relation], sourceWord, typeof(Set <string>), false);                         //ZK changed to static method

                        foreach (int targetWordIndex in _lexicalRelations[relation][relatedSynSet][sourceWordIndex])
                        {
                            string targetWord = relatedSynSet.Words[targetWordIndex - 1];
                            relatedWords[relation][sourceWord].Add(targetWord);
                        }
                    }
                }
            }

            return(relatedWords);
        }
Ejemplo n.º 4
0
 public override void OnReceiveRpc(object session, Stream stream)
 {
     this.Name             = stream.ReadString();
     this.Password         = stream.ReadString();
     this.PlayerName       = stream.ReadString();
     this.PlayerProperties = DictionaryExtensions.BytesDictToProp(stream.ReadObject <Dictionary <object, object> >());
 }
Ejemplo n.º 5
0
 public void Serilize(Stream stream)
 {
     lock (this._selfProperties) {
         stream.WriteObject(this._selfProperties);
     }
     if (this.LobbyCustomProperties == null)
     {
         stream.WriteObject(null);
     }
     else
     {
         lock (this.LobbyCustomProperties) {
             stream.WriteObject(this.LobbyCustomProperties);
         }
     }
     if (this.OtherCustomProperties == null)
     {
         stream.WriteObject(null);
     }
     else
     {
         lock (this.OtherCustomProperties) {
             //自定义属性允许服务器无法序列化的类型,所以转为bytes后再传到服务器
             var bytesDict = DictionaryExtensions.PropToBytesDict(this.OtherCustomProperties);
             stream.WriteObject(bytesDict);
         }
     }
 }
Ejemplo n.º 6
0
        public void PopFailsWithNullThis()
        {
            var e = Assert.Throws <ArgumentNullException>(() =>
                                                          DictionaryExtensions.Pop <object, object>(null, new object()));

            Assert.Equal(e.ParamName, "dictionary");
        }
Ejemplo n.º 7
0
 public override void OnSendRpc(Stream stream)
 {
     stream.Write(this.Name);
     stream.Write(this.Password);
     stream.Write(this.PlayerName);
     stream.WriteObject(DictionaryExtensions.PropToBytesDict(this.PlayerProperties));
 }
        public static StreamSubscriptionMatch[] Match(IActorSystem system, StreamIdentity stream)
        {
            var specifications = DictionaryExtensions.Find(configuration, stream.Provider)
                                 ?? Enumerable.Empty <StreamSubscriptionSpecification>();

            return(Match(system, stream.Id, specifications));
        }
Ejemplo n.º 9
0
 internal void Deserilize(Stream stream)
 {
     this.Id               = stream.ReadInt();
     this.Name             = stream.ReadString();
     this.IsMaster         = stream.ReadBool();
     this.CustomProperties = DictionaryExtensions.BytesDictToProp(stream.ReadObject <Dictionary <object, object> >(), false);
 }
            public void Then_the_dictionary_that_is_created_should_be_case_sensitive()
            {
                var dict = DictionaryExtensions.AnonymousObjectToCaseSensitiveDictionary(new { Foo = "Bar" });

                Assert.That(dict.ContainsKey("Foo"));
                Assert.That(!dict.ContainsKey("foo"));
            }
            public void And_the_object_is_null_then_an_empty_dictionary_should_be_returned()
            {
                var dict = DictionaryExtensions.AnonymousObjectToCaseSensitiveDictionary(null);

                Assert.That(dict, Is.Not.Null);
                Assert.That(dict.Count, Is.EqualTo(0));
            }
Ejemplo n.º 12
0
        /// <summary>
        /// Compare an old and new version of a database
        /// </summary>
        /// <param name="oldDataBase">Old version</param>
        /// <param name="newDataBase">New version</param>
        /// <returns>A object stating changes to the database</returns>
        public static DatabaseMetaChange CompareVersions(DataBase oldDataBase, DataBase newDataBase)
        {
            // Get changes happened to the database
            var databaseMetaChange = DetectChanges(oldDataBase, newDataBase);

            // If the database is added or deleted, we don't care about the remaining tables and columns.
            if (databaseMetaChange.IsSet(DatabaseChanges.Addition | DatabaseChanges.Deletion))
            {
                return(databaseMetaChange);
            }

            // Proceed down towards the tables and record these.
            foreach (var pair in DictionaryExtensions.MergeKeys(oldDataBase.Tables, newDataBase.Tables).Values)
            {
                // Check if the new version is not null, then use that ID for the dictionary, if it is then use the old ID
                if (pair.New != null)
                {
                    databaseMetaChange.Tables[pair.New.ID] = Table.CompareVersions(pair.Old, pair.New);
                }
                else
                {
                    databaseMetaChange.Tables[pair.Old.ID] = Table.CompareVersions(pair.Old, pair.New);
                }
            }

            return(databaseMetaChange);
        }
Ejemplo n.º 13
0
        public IndexDefinitionCompareDifferences Compare(AutoIndexDefinition other)
        {
            if (other == null)
            {
                return(IndexDefinitionCompareDifferences.All);
            }

            if (ReferenceEquals(this, other))
            {
                return(IndexDefinitionCompareDifferences.None);
            }

            var result = IndexDefinitionCompareDifferences.None;

            if (string.Equals(Collection, other.Collection) == false || DictionaryExtensions.ContentEquals(MapFields, other.MapFields) == false)
            {
                result |= IndexDefinitionCompareDifferences.Maps;
            }

            if (DictionaryExtensions.ContentEquals(GroupByFields, other.GroupByFields) == false)
            {
                result |= IndexDefinitionCompareDifferences.Reduce;
            }

            if (Priority != other.Priority)
            {
                result |= IndexDefinitionCompareDifferences.Priority;
            }

            return(result);
        }
        public void AddRange_OtherIsNotEmpty_ShouldAggregate()
        {
            // Arrange
            var target = new Dictionary <string, int>
            {
                { "one", 5 },
                { "two", 34 }
            };

            var other = new Dictionary <string, int>
            {
                { "two", 67 },
                { "three", 2 }
            };

            // Act
            DictionaryExtensions.AddRange(target, other, (lhs, rhs) => lhs + rhs);

            // Assert
            target.ShouldBeEquivalentTo(new Dictionary <string, int>
            {
                { "one", 5 },
                { "two", 34 + 67 },
                { "three", 2 }
            });
        }
Ejemplo n.º 15
0
        public void When_comparing_dictionaries_with_comparer()
        {
            IDictionary <int, string> left  = new Dictionary <int, string>();
            IDictionary <int, string> right = new Dictionary <int, string>();

            var comparer = StringComparer.OrdinalIgnoreCase;

            DictionaryExtensions.Equals(left, right, comparer).ShouldBeTrue();

            left.Add(1, "A");
            DictionaryExtensions.Equals(left, right, comparer).ShouldBeFalse();

            right.Add(1, "A");
            DictionaryExtensions.Equals(left, right, comparer).ShouldBeTrue();

            left[2] = "A";
            DictionaryExtensions.Equals(left, right, comparer).ShouldBeFalse();

            right[2] = "A";
            right[3] = "B";
            DictionaryExtensions.Equals(left, right, comparer).ShouldBeFalse();

            left[3] = "B";
            DictionaryExtensions.Equals(left, right, comparer).ShouldBeTrue();

            left[3] = "b";
            DictionaryExtensions.Equals(left, right, comparer).ShouldBeTrue();

            DictionaryExtensions.Equals(((IDictionary <int, string>)null), right, comparer).ShouldBeFalse();

            left = right;
            DictionaryExtensions.Equals(left, null, comparer).ShouldBeFalse();

            DictionaryExtensions.Equals(((IDictionary <int, string>)null), null, comparer).ShouldBeTrue();
        }
        public static EndpointDetails SendingEndpoint(IDictionary <string, string> headers)
        {
            var endpointDetails = new EndpointDetails();

            DictionaryExtensions.CheckIfKeyExists(Headers.OriginatingEndpoint, headers, s => endpointDetails.Name      = s);
            DictionaryExtensions.CheckIfKeyExists("NServiceBus.OriginatingMachine", headers, s => endpointDetails.Host = s);
            DictionaryExtensions.CheckIfKeyExists(Headers.OriginatingHostId, headers, s => endpointDetails.HostId      = Guid.Parse(s));

            if (!string.IsNullOrEmpty(endpointDetails.Name) && !string.IsNullOrEmpty(endpointDetails.Host))
            {
                return(endpointDetails);
            }

            var address = Address.Undefined;

            DictionaryExtensions.CheckIfKeyExists(Headers.OriginatingAddress, headers, s => address = Address.Parse(s));

            if (address != Address.Undefined)
            {
                endpointDetails.Name = address.Queue;
                endpointDetails.Host = address.Machine;
                return(endpointDetails);
            }

            return(null);
        }
Ejemplo n.º 17
0
        private ZoneDetailsProviderResult.CountersData GetCountersData(ZoneState zone, ControllerState state, Building building)
        {
            var heaterIds       = zone.Zone.Heaters.Select(x => x.HeaterId).ToHashSet();
            var heatersCounters = _counterRepository.Read(x => heaterIds.Contains(x.HeaterId) &&
                                                          !x.ResetDate.HasValue)
                                  .ToDictionary(x => x.HeaterId,
                                                x => x);

            var now = DateTime.UtcNow;

            var heaterIdToCountedSeconds = heaterIds.ToDictionary(x => x,
                                                                  x =>
            {
                var savedCounterValue   = DictionaryExtensions.GetValueOrDefault(heatersCounters, x)?.CountedSeconds ?? 0;
                var heaterState         = state.HeaterIdToState[x];
                var currentCounterValue = heaterState.OutputState ? (int)(now - heaterState.LastCounterStart).TotalSeconds : 0;

                return(savedCounterValue + currentCounterValue);
            });

            var usageUnitToHeaterToValue = building.Heaters
                                           .Where(x => heaterIds.Contains(x.HeaterId))
                                           .GroupBy(x => x.UsageUnit)
                                           .ToDictionary(x => x.Key,
                                                         x => x.ToDictionary(h => h.Name, h => h.UsagePerHour * (decimal)(heaterIdToCountedSeconds[h.HeaterId] / 3600f)));

            return(new ZoneDetailsProviderResult.CountersData
            {
                LastResetDate = heatersCounters.Any() ? heatersCounters.Values.Min(x => x.StartDate) : (DateTime?)null,
                UsageUnitToValue = usageUnitToHeaterToValue.ToDictionary(x => x.Key,
                                                                         x => x.Value.Sum(h => h.Value)),
                UsageUnitToHeaterNameToValue = usageUnitToHeaterToValue
            });
        }
Ejemplo n.º 18
0
        public void When_comparing_dictionaries()
        {
            IDictionary <string, int> left  = new Dictionary <string, int>();
            IDictionary <string, int> right = new Dictionary <string, int>();

            DictionaryExtensions.Equals(left, right).ShouldBeTrue();

            left.Add("A", 1);
            DictionaryExtensions.Equals(left, right).ShouldBeFalse();

            right.Add("A", 1);
            DictionaryExtensions.Equals(left, right).ShouldBeTrue();

            left["A"] = 2;
            DictionaryExtensions.Equals(left, right).ShouldBeFalse();

            right["A"] = 2;
            right["B"] = 3;
            DictionaryExtensions.Equals(left, right).ShouldBeFalse();

            left["B"] = 3;
            DictionaryExtensions.Equals(left, right).ShouldBeTrue();

            DictionaryExtensions.Equals(((IDictionary <string, int>)null), right).ShouldBeFalse();

            left = right;
            DictionaryExtensions.Equals(left, null).ShouldBeFalse();

            DictionaryExtensions.Equals(((IDictionary <string, int>)null), null).ShouldBeTrue();
        }
Ejemplo n.º 19
0
        public static EndpointDetails SendingEndpoint(IReadOnlyDictionary <string, string> headers)
        {
            var endpointDetails = new EndpointDetails();

            DictionaryExtensions.CheckIfKeyExists(Headers.OriginatingEndpoint, headers, s => endpointDetails.Name      = s);
            DictionaryExtensions.CheckIfKeyExists("NServiceBus.OriginatingMachine", headers, s => endpointDetails.Host = s);
            DictionaryExtensions.CheckIfKeyExists(Headers.OriginatingHostId, headers, s => endpointDetails.HostId      = Guid.Parse(s));

            if (!string.IsNullOrEmpty(endpointDetails.Name) && !string.IsNullOrEmpty(endpointDetails.Host))
            {
                return(endpointDetails);
            }

            string address = null;

            DictionaryExtensions.CheckIfKeyExists(Headers.OriginatingAddress, headers, s => address = s);

            if (address != null)
            {
                var queueAndMachinename = ExtractQueueAndMachineName(address);
                endpointDetails.Name = queueAndMachinename.Queue;
                endpointDetails.Host = queueAndMachinename.Machine;
                return(endpointDetails);
            }

            return(null);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Records event with parameters
        /// </summary>
        /// <param name="area">Telemetry area name such as 'Toolbox'.</param>
        /// <param name="eventName">Event name.</param>
        /// <param name="parameters">
        /// Either string/object dictionary or anonymous
        /// collection of string/object pairs.
        /// </param>
        /// <summary>
        public void ReportEvent(TelemetryArea area, string eventName, object parameters = null)
        {
            Check.ArgumentStringNullOrEmpty("eventName", eventName);

            string completeEventName = MakeEventName(area, eventName);

            if (parameters == null)
            {
                this.TelemetryRecorder.RecordEvent(completeEventName);
            }
            else if (parameters is string)
            {
                this.TelemetryRecorder.RecordEvent(completeEventName, parameters as string);
            }
            else
            {
                IDictionary <string, object> dict           = DictionaryExtensions.FromAnonymousObject(parameters);
                IDictionary <string, object> dictWithPrefix = new Dictionary <string, object>();

                foreach (KeyValuePair <string, object> kvp in dict)
                {
                    Check.ArgumentStringNullOrEmpty("parameterName", kvp.Key);
                    dictWithPrefix[this.PropertyNamePrefix + area.ToString() + "." + kvp.Key] = kvp.Value ?? string.Empty;
                }
                this.TelemetryRecorder.RecordEvent(completeEventName, dictWithPrefix);
            }
        }
Ejemplo n.º 21
0
        public void Returns_Dynamic_Object_From_ToDynamic_When_Source_Is_Provided()
        {
            // arrange
            var id          = Guid.NewGuid();
            var description = "description";
            var count       = 1;

#pragma warning disable SA1413  // No trailing commas on initializers, that is STUPID.
            var source = new Dictionary <string, object>()
            {
                { "Id", id },
                { "Description", description },
                { "Count", count }
            };
#pragma warning restore SA1413  // No trailing commas on initializers, that is STUPID.

            // act
            var result = DictionaryExtensions.ToDynamicObject(source);

            // assert
            Assert.IsInstanceOfType(result, typeof(ExpandoObject));
            Assert.AreEqual(source["Id"], result.id);
            Assert.AreEqual(source["Description"], result.description);
            Assert.AreEqual(source["Count"], result.count);
        }
Ejemplo n.º 22
0
 public void SetPoolProfileProperty(Guid workId, Guid poolId, string propertyName, object value)
 {
     if (!PoolProfileProperties.ContainsKey(propertyName))
     {
         return;
     }
     using (var database = CreateDatabase(workId)) {
         var  col   = database.GetCollection <PoolProfileData>();
         var  data  = col.FindById(poolId);
         bool exist = true;
         if (data == null)
         {
             exist = false;
             data  = PoolProfileData.CreateDefaultData(poolId);
         }
         PropertyInfo propertyInfo = PoolProfileProperties[propertyName];
         if (propertyInfo.PropertyType == typeof(Guid))
         {
             value = DictionaryExtensions.ConvertToGuid(value);
         }
         propertyInfo.SetValue(data, value, null);
         if (exist)
         {
             col.Update(data);
         }
         else
         {
             col.Insert(data);
         }
     }
 }
Ejemplo n.º 23
0
 public void SetMinerProfileProperty(Guid workId, string propertyName, object value)
 {
     if (!MinerProfileProperties.ContainsKey(propertyName))
     {
         return;
     }
     using (var database = CreateDatabase(workId)) {
         var  col   = database.GetCollection <MinerProfileData>();
         var  data  = col.FindAll().FirstOrDefault();
         bool exist = true;
         if (data == null)
         {
             exist = false;
             data  = MinerProfileData.CreateDefaultData();
         }
         PropertyInfo propertyInfo = MinerProfileProperties[propertyName];
         if (propertyInfo.PropertyType == typeof(Guid))
         {
             value = DictionaryExtensions.ConvertToGuid(value);
         }
         propertyInfo.SetValue(data, value, null);
         if (exist)
         {
             data.ModifiedOn = DateTime.Now;
             col.Update(data);
         }
         else
         {
             col.Insert(data);
         }
     }
 }
Ejemplo n.º 24
0
        public override IndexDefinitionCompareDifferences Compare(IndexDefinitionBase other)
        {
            var otherDefinition = other as AutoMapIndexDefinition;

            if (otherDefinition == null)
            {
                return(IndexDefinitionCompareDifferences.All);
            }

            if (ReferenceEquals(this, other))
            {
                return(IndexDefinitionCompareDifferences.None);
            }

            var result = IndexDefinitionCompareDifferences.None;

            if (Collections.SetEquals(otherDefinition.Collections) == false || DictionaryExtensions.ContentEquals(MapFields, otherDefinition.MapFields) == false)
            {
                result |= IndexDefinitionCompareDifferences.Maps;
            }

            if (LockMode != other.LockMode)
            {
                result |= IndexDefinitionCompareDifferences.LockMode;
            }

            if (Priority != other.Priority)
            {
                result |= IndexDefinitionCompareDifferences.Priority;
            }

            return(result);
        }
Ejemplo n.º 25
0
        public void UpdateClients(string propertyName, Dictionary <string, object> values)
        {
            InitOnece();
            PropertyInfo propertyInfo = typeof(ClientData).GetProperty(propertyName);

            if (propertyInfo != null)
            {
                if (propertyInfo.PropertyType == typeof(Guid))
                {
                    foreach (var kv in values)
                    {
                        values[kv.Key] = DictionaryExtensions.ConvertToGuid(kv.Value);
                    }
                }
                foreach (var kv in values)
                {
                    string objectId = kv.Key;
                    object value    = kv.Value;
                    if (_dicByObjectId.TryGetValue(objectId, out ClientData clientData))
                    {
                        propertyInfo.SetValue(clientData, value, null);
                        clientData.ModifiedOn = DateTime.Now;
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public void EditPatterns()
        {
            var patterns = DictionaryExtensions.DeserializeFromFile(@"patterns.xml");

            if (patterns == null)
            {
                Console.WriteLine("\nSorry, no patterns");
            }

            ShowPatterns(patterns);

            Console.WriteLine("\nPlease, input number pattern for edit");

            int[] patternNumbers = Enumerable.Range(1, patterns.Count).ToArray();
            int   number         = InputHelper.ValidateTwoDigitNumberInput(Console.ReadLine(), patternNumbers);
            var   pattern        = patterns.ToList()[number - 1];

            Console.WriteLine("\nPlease, input new value for pattern");
            Console.WriteLine("\n" + pattern.Key);

            char value = InputHelper.ValidateLetterOrDigitInput(Console.ReadKey());

            patterns[pattern.Key] = value;

            patterns.SerializeToFile(@"patterns.xml");

            Console.WriteLine("\n\nСhanges saved successfully");
        }
Ejemplo n.º 27
0
 public static bool ExtensionMethodsCalledForAllDiagnostics(IEnumerable <DiagnosticAnalyzer> analyzers) =>
 // In general this check is not very precise, because when the tests are run in parallel
 // we cannot determine which diagnostic was reported from which analyzer instance. In other
 // words, we cannot distinguish between diagnostics reported from different tests. That's
 // why we require each diagnostic to be reported through the extension methods at least once.
 analyzers.SelectMany(analyzer => analyzer.SupportedDiagnostics)
 .Select(d => DictionaryExtensions.GetValueOrDefault(counters, d.Id))
 .Any(count => count > 0);
Ejemplo n.º 28
0
        public void MergeReturnsNullIfSourceIsNull()
        {
            var candidate = DictionaryExtensions.Merge(null, new Dictionary <string, string> {
                { "key", "value" }
            });

            Assert.IsNull(candidate);
        }
Ejemplo n.º 29
0
 public static void Clear()
 {
     lock (metadataLock)
     {
         _instances.Clear();
         DictionaryExtensions.ClearCache();
     }
 }
Ejemplo n.º 30
0
        public void TestTryAdd()
        {
            var dictionary = new Dictionary <string, string>();

            Assert.True(DictionaryExtensions.TryAdd(dictionary, "a", "b"));
            Assert.Equal("b", dictionary["a"]);
            Assert.False(DictionaryExtensions.TryAdd(dictionary, "a", "c"));
        }