System.Collections.Generic.ICollection.Add(System.Collections.Generic.KeyValuePair)

Here are the examples of the csharp api System.Collections.Generic.ICollection.Add(System.Collections.Generic.KeyValuePair) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1562 Examples 7

19 Source : EntityMapperProvider.cs
with Apache License 2.0
from 1448376744

public Func<IDataRecord, dynamic> GetSerializer()
        {
            return (reader) =>
            {
                dynamic obj = new System.Dynamic.ExpandoObject();
                var row = (IDictionary<string, object>)obj;
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    var name = reader.GetName(i);
                    row.Add(name, reader.GetValue(i));
                }
                return row;
            };
        }

19 Source : MapFormatterHelper.cs
with MIT License
from 1996v

public static void FillGenericIDictionaryData<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> pairs, ICollection<KeyValuePair<TKey, TValue>> collection)
        {
            foreach (KeyValuePair<TKey, TValue> item in pairs)
            {
                collection.Add(item);
            }
        }

19 Source : JsonData.cs
with MIT License
from 404Lcc

void IDictionary.Add (object key, object value)
        {
            JsonData data = ToJsonData (value);

            EnsureDictionary ().Add (key, data);

            KeyValuePair<string, JsonData> entry =
                new KeyValuePair<string, JsonData> ((string) key, data);
            object_list.Add (entry);

            json = null;
        }

19 Source : MpInfoContainer.cs
with MIT License
from 52ABP

public static IDictionary<string, MpInfoBag> GetAll(UserKeyType userId, TenantKeyType tenantId)
        {
            var registerList = Cache.Get<List<KeyInfo<UserKeyType, TenantKeyType>>>(REGIEST_LIST)
                .Where(info => info.UserId.Equals(userId) && info.TenantId.Equals(tenantId))
                .Select(info => info.Key)
                .ToList();
            IDictionary<string, MpInfoBag> dic = new Dictionary<string, MpInfoBag>();
            foreach (var key in registerList)
            {
                dic.Add(key, TryGereplacedem(key));
            }
            return dic;
        }

19 Source : Module.cs
with MIT License
from ABTSoftware

private void InitializeExamplesAndPages(IEnumerable<ExampleDefinition> exampleDefinitions)
        {
            AppPage appPage;
            HashSet<string> categories = new HashSet<string>();
            foreach (var definition in exampleDefinitions)
            {
                appPage = new ExampleAppPage(definition.replacedle ,definition.ViewModel, definition.View);
                ChartingPages.Add(appPage.PageId, appPage);

                var example = new Example(appPage, definition) {SelectCommand = NavigateToExample};

                _examples.Add(appPage.PageId, example);
                categories.Add(example.TopLevelCategory);
            }

            _allCategories = new ReadOnlyCollection<string>(categories.ToList());
            _groupsByCategory = new Dictionary<string, ReadOnlyCollection<string>>();
            foreach (var category in _allCategories)
            {
                var groups = _examples.Where(ex => ex.Value.TopLevelCategory == category).Select(y => y.Value.Group).Distinct().ToList();
                _groupsByCategory.Add(category, new ReadOnlyCollection<string>(groups));
            }

            appPage = new HomeAppPage();
            ChartingPages.Add(appPage.PageId, appPage);

            appPage = new EverythingAppPage();
            ChartingPages.Add(appPage.PageId, appPage);

            appPage = new ExamplesHostAppPage();
            ChartingPages.Add(appPage.PageId, appPage);
        }

19 Source : UriExtensions.cs
with MIT License
from actions

public static void AddMultiple<T>(this IList<KeyValuePair<String, String>> collection, String key, IEnumerable<T> values, Func<T, String> convert)
        {
            ArgumentUtility.CheckForNull(collection, "collection");
            ArgumentUtility.CheckStringForNullOrEmpty(key, "name");

            if (convert == null) convert = (val) => val.ToString();

            if (values != null && values.Any())
            {
                StringBuilder newValue = new StringBuilder();
                KeyValuePair<String, String> matchingKvp = collection.FirstOrDefault(kvp => kvp.Key.Equals(key));
                if (matchingKvp.Key == key)
                {
                    collection.Remove(matchingKvp);
                    newValue.Append(matchingKvp.Value);
                }

                foreach (var value in values)
                {
                    if (newValue.Length > 0)
                    {
                        newValue.Append(",");
                    }
                    newValue.Append(convert(value));
                }

                collection.Add(new KeyValuePair<String, String>(key, newValue.ToString()));
            }
        }

19 Source : ReferenceLinks.cs
with MIT License
from actions

void IXmlSerializable.ReadXml(XmlReader reader)
        {
            XmlSerializer keySerializer = new XmlSerializer(typeof(string));
            XmlSerializer valueSerializer = new XmlSerializer(typeof(List<ReferenceLink>));

            bool wasEmpty = reader.IsEmptyElement;
            reader.Read();

            if (wasEmpty)
            {
                return;
            }

            while (reader.NodeType != XmlNodeType.EndElement)
            {
                reader.ReadStartElement("item");

                reader.ReadStartElement("key");
                var key = (string)keySerializer.Deserialize(reader);
                reader.ReadEndElement();

                reader.ReadStartElement("value");
                var value = (List<ReferenceLink>)valueSerializer.Deserialize(reader);
                reader.ReadEndElement();

                if (value.Count == 1)
                {
                    referenceLinks.Add(key, value[0]);
                }
                else if (value.Count > 1)
                {
                    referenceLinks.Add(key, value);
                }

                reader.ReadEndElement();
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }

19 Source : FlagsEnum.cs
with MIT License
from actions

public static object ParseKnownFlags(Type enumType, string stringValue)
        {
            ArgumentUtility.CheckForNull(enumType, nameof(enumType));
            if (!enumType.IsEnum)
            {
                throw new ArgumentException(PipelinesWebApiResources.FlagEnumTypeRequired());
            }

            // Check for the flags attribute in debug. Skip this reflection in release.
            Debug.replacedert(enumType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any(), "FlagsEnum only intended for enums with the Flags attribute.");

            // The exception types below are based on Enum.TryParseEnum (http://index/?query=TryParseEnum&rightProject=mscorlib&file=system%5Cenum.cs&rightSymbol=bhaeh2vnegwo)
            if (stringValue == null)
            {
                throw new ArgumentNullException(stringValue);
            }

            if (String.IsNullOrWhiteSpace(stringValue))
            {
                throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
            }

            if (UInt64.TryParse(stringValue, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out ulong ulongValue))
            {
                return Enum.Parse(enumType, stringValue);
            }

            var enumNames = Enum.GetNames(enumType).ToHashSet(name => name, StringComparer.OrdinalIgnoreCase);
            var enumMemberMappings = new Lazy<IDictionary<string, string>>(() =>
            {
                IDictionary<string, string> mappings = null;
                foreach (var field in enumType.GetFields())
                {
                    if (field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() is EnumMemberAttribute enumMemberAttribute)
                    {
                        if (mappings == null)
                        {
                            mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                        }
                        mappings.Add(enumMemberAttribute.Value, field.GetValue(null).ToString());
                    }
                }

                return mappings;
            });

            var values = stringValue.Split(s_enumSeparatorCharArray);

            var matches = new List<string>();
            for (int i = 0; i < values.Length; i++)
            {
                string value = values[i].Trim();

                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
                }

                if (enumNames.Contains(value))
                {
                    matches.Add(value);
                }
                else if (enumMemberMappings.Value != null && enumMemberMappings.Value.TryGetValue(value, out string matchingValue))
                {
                    matches.Add(matchingValue);
                }
            }

            if (!matches.Any())
            {
                return Enum.Parse(enumType, "0");
            }

            string matchesString = String.Join(", ", matches);
            return Enum.Parse(enumType, matchesString, ignoreCase: true);
        }

19 Source : PropertiesCollection.cs
with MIT License
from actions

void ICollection<KeyValuePair<String, Object>>.Add(KeyValuePair<String, Object> keyValuePair)
        {
            if (this.ValidateNewValues)
            {
                PropertyValidation.ValidatePropertyName(keyValuePair.Key);
                PropertyValidation.ValidatePropertyValue(keyValuePair.Key, keyValuePair.Value);
            }

            ((ICollection<KeyValuePair<String, Object>>)m_innerDictionary).Add(keyValuePair);
        }

19 Source : DmnDefinitionFactory.cs
with MIT License
from adamecr

protected void ProcessInputDataSource(DmnModel source, IDictionary<string, DmnVariableDefinition> inputDataById)
        {
            if (source == null) throw Logger.Fatal<ArgumentNullException>($"{nameof(source)} is null");
            if (inputDataById == null) throw Logger.Fatal<ArgumentNullException>($"{nameof(inputDataById)} is null");
            if (source.InputData == null || source.InputData.Count == 0) return;//it's not common, but OK to have no input data

            //TODO    ?Input name in form varName:varType for (complex) input types
            //TODO ?Required input parameters check for null??
            foreach (var sourceInput in source.InputData)
            {
                if (string.IsNullOrWhiteSpace(sourceInput.Id)) throw Logger.Fatal<DmnParserException>($"Missing input id");

                var inputName = !string.IsNullOrWhiteSpace(sourceInput.Name) ? sourceInput.Name : sourceInput.Id;
                var variableName = NormalizeVariableName(inputName);
                if (InputData.ContainsKey(variableName))
                    throw Logger.Fatal<DmnParserException>($"Duplicate input data name {variableName} (from {inputName})");

                var variable = new DmnVariableDefinition(variableName) { IsInputParameter = true, HasValueSetter = true };
                variable.ValueSetters.Add($"Input: {inputName}");
                InputData.Add(variableName, variable);
                Variables.Add(variableName, variable);
                inputDataById.Add(sourceInput.Id, variable);
            }
        }

19 Source : DmnDefinitionFactory.cs
with MIT License
from adamecr

protected IDmnDecision ProcessDecision(
             Decision sourceDecision, IReadOnlyCollection<Decision> allDecisions,
             IDictionary<string, IDmnDecision> decisionsById, IDictionary<string, DmnVariableDefinition> inputDataById)
        {

            if (sourceDecision == null) throw Logger.Fatal<ArgumentNullException>($"{nameof(sourceDecision)} is null");
            if (decisionsById == null) throw Logger.Fatal<ArgumentNullException>($"{nameof(decisionsById)} is null");
            if (inputDataById == null) throw Logger.Fatal<ArgumentNullException>($"{nameof(inputDataById)} is null");

            if (string.IsNullOrWhiteSpace(sourceDecision.Id)) throw Logger.Fatal<DmnParserException>($"Missing decision id");
            if (decisionsById.ContainsKey(sourceDecision.Id)) return decisionsById[sourceDecision.Id]; //already processed

            var decisionName = !string.IsNullOrWhiteSpace(sourceDecision.Name) ? sourceDecision.Name : sourceDecision.Id;
            if (Decisions.ContainsKey(decisionName)) throw Logger.Fatal<DmnParserException>($"Duplicate decision name {decisionName}");

            var requiredInputs = new List<DmnVariableDefinition>();
            var requiredDecisions = new List<IDmnDecision>();
            //check dependencies
            if (sourceDecision.InformationRequirements != null)
            {
                foreach (var dependsOnDecisionRef in sourceDecision.InformationRequirements.Where(i => i.RequirementType == InformationRequirementType.Decision))
                {
                    var refId = dependsOnDecisionRef.Ref;
                    if (string.IsNullOrWhiteSpace(refId)) throw Logger.Fatal<DmnParserException>($"Missing required decision reference for {decisionName}");

                    if (decisionsById.TryGetValue(refId, out var requiredDecision))
                    {
                        //decision already processed, just add "new" inputs
                        AddNewRequiredInputs(requiredDecision.RequiredInputs, requiredInputs);
                        requiredDecisions.Add(requiredDecision);
                        continue;
                    }

                    var sourceDependsOnDecision = allDecisions.FirstOrDefault(d => d.Id == refId);
                    if (sourceDependsOnDecision == null) throw Logger.Fatal<DmnParserException>($"Decision with reference {refId} for {decisionName} not found");

                    var dependsOnDecision = ProcessDecision(sourceDependsOnDecision, allDecisions, decisionsById, inputDataById); //process needed decision first
                    AddNewRequiredInputs(dependsOnDecision.RequiredInputs, requiredInputs);
                    requiredDecisions.Add(dependsOnDecision);
                }
            }

            //validate input references
            if (sourceDecision.InformationRequirements != null)
            {
                var newInputs = new List<DmnVariableDefinition>();
                foreach (var informationRequirement in sourceDecision.InformationRequirements.Where(d => d.RequirementType == InformationRequirementType.Input))
                {
                    var refId = informationRequirement.Ref;
                    if (string.IsNullOrWhiteSpace(refId)) throw Logger.Fatal<DmnParserException>($"Missing required input reference for {decisionName}");
                    if (!inputDataById.ContainsKey(refId)) throw Logger.Fatal<DmnParserException>($"Input with reference {refId} for {decisionName} not found");
                    newInputs.Add(inputDataById[refId]);
                }
                AddNewRequiredInputs(newInputs, requiredInputs);
            }

            //Decision factory
            IDmnDecision decision;
            if (sourceDecision.DecisionTable == null)
            {
                //expression
                decision = CreateExpressionDecision(sourceDecision, decisionName, requiredInputs, requiredDecisions);
            }
            else
            {
                //decision table
                decision = CreateDecisionTable(sourceDecision.DecisionTable, decisionName, requiredInputs, requiredDecisions);
            }

            Decisions.Add(decisionName, decision);
            decisionsById.Add(sourceDecision.Id, decision);
            return decision;
        }

19 Source : Avatar.razor.cs
with MIT License
from ADefWebserver

public async ValueTask CreateScene()
        {
            var canvas = await Canvas.GetElementById(
                "game-window"
            );
            var engine = await Engine.NewEngine(
                canvas,
                true
            );
            var scene = await Scene.NewScene(
                engine
            );
            var light0 = await PointLight.NewPointLight(
                "Omni",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                ),
                scene
            );
            var light1 = await HemisphericLight.NewHemisphericLight(
                "HemisphericLight",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                ),
                scene
            );

            var Player = await SceneLoader.ImportMesh(
                null,
                "replacedets/",
                "Player.glb",
                scene,
               new ActionCallback<AbstractMesh[], IParticleSystem[], Skeleton[], AnimationGroup[], TransformNode[], Geometry[], Light[]>(async (arg1, arg2, arg3, arg4, arg5, arg6, arg7) =>
               {
                    foreach (var animation in arg4)
                    {
                        await animation.stop();
                        _animationMap.Add(await animation.get_name(), animation);
                    }
                    if (_animationMap.Count > 0)
                    {
                        _runningAnimation = _animationMap.First().Value;
                        await _runningAnimation.start(true);
                    }
                })
            );            

            var camera = await ArcRotateCamera.NewArcRotateCamera(
                "ArcRotateCamera",
                (decimal)(System.Math.PI / 2),
                (decimal)(System.Math.PI / 4),
                3,
                await Vector3.NewVector3(0, 1, 0),
                scene
            );

            await camera.set_lowerRadiusLimit(2);
            await camera.set_upperRadiusLimit(10);
            await camera.set_wheelDeltaPercentage(0.01m);

            await scene.set_activeCamera(camera);

            await scene.set_activeCamera(camera);

            await camera.attachControl(
                false
            );

            await engine.runRenderLoop(new ActionCallback(
                            () => Task.Run(() => scene.render(true, false))
                        ));

            _engine = engine;
        }

19 Source : SharkControl.razor.cs
with MIT License
from ADefWebserver

public async ValueTask CreateScene()
        {            
            var canvas = await Canvas.GetElementById(
                "game-window"
            );
            var engine = await Engine.NewEngine(
                canvas,
                true
            );

            var scene = await Scene.NewScene(
                engine
            );
            var light0 = await PointLight.NewPointLight(
                "Omni",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                ),
                scene
            );
            var light1 = await HemisphericLight.NewHemisphericLight(
                "HemisphericLight",
                await Vector3.NewVector3(
                    0,
                    100,
                    8
                ),
                scene
            );

            var Player = await SceneLoader.ImportMesh(
                null,
                "replacedets/",
                "Shark.glb",
                scene,
                new ActionCallback<AbstractMesh[], IParticleSystem[], Skeleton[], AnimationGroup[], TransformNode[], Geometry[], Light[]>(async (arg1, arg2, arg3, arg4, arg5, arg6, arg7) =>
                {
                    foreach (var animation in arg4)
                    {
                        await animation.stop();
                        _animationMap.Add(await animation.get_name(), animation);
                    }

                    if (_animationMap.Count > 0)
                    {
                        _runningAnimation = _animationMap.First().Value;
                        await _runningAnimation.start(true);
                    }
                })
            );

            var camera = await ArcRotateCamera.NewArcRotateCamera(
                "ArcRotateCamera",
                (decimal)(System.Math.PI / 2),
                (decimal)(System.Math.PI / 4),
                0,
                await Vector3.NewVector3(0, 1, 0),
                scene
            );

            // This positions the camera
            await camera.setPosition(await Vector3.NewVector3(30, 10, -30));

            await camera.set_lowerRadiusLimit(2);
            await camera.set_upperRadiusLimit(100);
            await camera.set_wheelDeltaPercentage(0.01m);

            await scene.set_activeCamera(camera);

            await camera.attachControl(                
                false
            );

            await engine.runRenderLoop(new ActionCallback(
                            () => Task.Run(() => scene.render(true, false))
                        ));

            _engine = engine;
        }

19 Source : EmbeddedResourceAssemblyAttribute.cs
with MIT License
from Adoxio

private static void AddResource(EmbeddedResourceNode node, IDictionary<string, EmbeddedResourceNode> lookup, IEnumerable<string> path, string resourceName)
		{
			if (path.Any())
			{
				var name = path.First();

				var child = node.Children.SingleOrDefault(n => n.Name == name);
				
				if (child == null)
				{
					var isFile = path.Count() == 1;
					var resource = isFile ? resourceName : GetResourceName(node, name);

					child = new EmbeddedResourceNode(name, !isFile, isFile, GetVirtualPath(node, name), resource);

					node.Children.Add(child);
					lookup.Add(resource, child);
				}

				AddResource(child, lookup, path.Skip(1), resourceName);
			}
		}

19 Source : Track.cs
with MIT License
from Aeroluna

public void AddPathProperty(string name, PropertyType propertyType)
        {
            if (PathProperties.ContainsKey(name))
            {
                Plugin.Logger.Log($"Duplicate path property {name}, skipping...", IPA.Logging.Logger.Level.Trace);
            }
            else
            {
                PathProperties.Add(name, new PathProperty(propertyType));
            }
        }

19 Source : UnityContainerAttributeExtensions.cs
with Apache License 2.0
from agoda-com

private static void RegisterForCollection<TLifestyleManager>(RegistrationContext reg)
            where TLifestyleManager : LifetimeManager, new()
        {
            reg.Key = Guid.NewGuid().ToString();

            // As well as registering the collection items individually, Unity also requires us to explicitly register
            // the IEnumerable<T> to make them injectable as a collection. Do this now if we haven't already done so.
            var enumerableInterface = typeof(IEnumerable<>).MakeGenericType(reg.FromType);
            if (!_container.IsRegistered(enumerableInterface))
            {
                _container.RegisterType(enumerableInterface, new TLifestyleManager(), new InjectionFactory(c =>
                {
                    // To keep the runtime happy, we need to return a strongly typed enumerable. The only way I can see
                    // to do this with the runtime types we have available is by calling Array.CreateInstance with our
                    // target type and copying into it.
                    var untypedObjects = _collectionItemsForType[reg.FromType]
                        .OrderBy(item => item.Order)
                        .Select(item => c.Resolve(reg.FromType, item.Key))
                        .ToArray();
                    var typedObjects = Array.CreateInstance(reg.FromType, untypedObjects.Length);
                    Array.Copy(untypedObjects, typedObjects, untypedObjects.Length);
                    return typedObjects;
                }));

                _collectionItemsForType.Add(reg.FromType, new List<ResolutionItem>());
            }

            // Ensure Order is unique for collection.
            if (reg.Collection.Order != 0)
            {
                var registeredOrders = _collectionItemsForType[reg.FromType]
                    .Where(item => item.Order != 0)
                    .OrderBy(item => item.Order)
                    .ToList();
                if (registeredOrders.Any(item => item.Order == reg.Collection.Order))
                {
                    var msg =
                        $"{reg.ToType.FullName}: an item has already been registered with {nameof(ContainerRegistrationAttribute.Order)} " +
                        $"= {reg.Collection.Order} for collection of {reg.FromType.FullName}. A collection's " +
                        $"{nameof(ContainerRegistrationAttribute.Order)} property must be either unspecified, 0, or otherwise unique. " +
                        $"The following {nameof(ContainerRegistrationAttribute.Order)}s were previously registered: " +
                        $"{{ {string.Join(", ", registeredOrders.Select(item => item.Order))} }}.";
                    throw new RegistrationFailedException(msg);
                }
            }

            // Ensure the lifetime of the new item matches those of the existing.
            var lifetimeManager = new TLifestyleManager();
            var mismatchedItem = _collectionItemsForType[reg.FromType]
                .FirstOrDefault(item => item.LifetimeManager.GetType() != typeof(TLifestyleManager));
            if (mismatchedItem != null && mismatchedItem.LifetimeManager != default(TLifestyleManager))
            {
                var msg = $"{reg.ToType.FullName}: registered with invalid lifetime {lifetimeManager.GetType().Name}. " +
                          $"All items in a collection must be registered with the same lifetime. Lifetime is fixed once " +
                          $"the first item is registered, in this case {mismatchedItem.LifetimeManager.GetType().Name}.";
                throw new RegistrationFailedException(msg);
            }

            _collectionItemsForType[reg.FromType].Add(ResolutionItem.Create(reg.Key, reg.Collection.Order, lifetimeManager));

            // Now go wash your eyes out.
        }

19 Source : UnityContainerAttributeExtensions.cs
with Apache License 2.0
from agoda-com

private static void EnsureKeyUnique(RegistrationContext reg)
        {
            if (!_keysForTypes.TryGetValue(reg.FromType, out var keys))
            {
                _keysForTypes.Add(reg.FromType, new HashSet<string>(new[] { reg.Key }));
            }
            else if (keys.Contains(reg.Key))
            {
                var msg = $"{reg.ToType.FullName}: {nameof(ContainerRegistrationAttribute.Key)} \"{reg.Key}\" has " +
                          $"already been registered for {reg.FromType.FullName}. Keys must be unique.";
                throw new RegistrationFailedException(msg);
            }
        }

19 Source : StartupExtension.cs
with Apache License 2.0
from agoda-com

private static void AddToKeyedRegistrationList(RegistrationContext reg, IDictionary<Type, List<KeyTypePair>> keysForTypes, ServiceLifetime serviceLifetime)
        {
            if (!keysForTypes.TryGetValue(reg.FromType, out var keys))
            {
                keysForTypes.Add(reg.FromType, new List<KeyTypePair> { new KeyTypePair(reg.Key, reg.ToType, serviceLifetime) });
            }
            else if (keys.Any(x => x.Key == reg.Key))
            {
                var msg = $"{reg.ToType.FullName}: {nameof(ContainerRegistrationAttribute.Key)} \"{reg.Key}\" has " +
                          $"already been registered for {reg.FromType.FullName}. Keys must be unique.";
                throw new RegistrationFailedException(msg);
            }
            else
            {
                keysForTypes[reg.FromType].Add(new KeyTypePair(reg.Key, reg.ToType, serviceLifetime));
            }
        }

19 Source : UserOnlyStore.cs
with Apache License 2.0
from Aguafrommars

private Claim CreateClaim(UserClaim userClaim)
        {
            var claim = new Claim(userClaim.ClaimType, userClaim.ClaimValue, null, userClaim.Issuer);
            claim.Properties.Add(nameof(UserClaim.OriginalType), userClaim.OriginalType);
            return claim;
        }

19 Source : DynamicResult.cs
with MIT License
from ahm3tcelik

public static IEnumerable<dynamic> DynamicListFromSql(this DbContext db, string Sql, Dictionary<string, object> Params)
        {
            using (var cmd = db.Database.Connection.CreateCommand())
            {
                cmd.CommandText = Sql;
                if (cmd.Connection.State != ConnectionState.Open) { cmd.Connection.Open(); }

                foreach (KeyValuePair<string, object> p in Params)
                {
                    DbParameter dbParameter = cmd.CreateParameter();
                    dbParameter.ParameterName = p.Key;
                    dbParameter.Value = p.Value;
                    cmd.Parameters.Add(dbParameter);
                }

                using (var dataReader = cmd.ExecuteReader())
                {
                    while (dataReader.Read())
                    {
                        var row = new ExpandoObject() as IDictionary<string, object>;
                        for (var fieldCount = 0; fieldCount < dataReader.FieldCount; fieldCount++)
                        {
                            row.Add(dataReader.GetName(fieldCount), dataReader[fieldCount]);
                        }
                        yield return row;
                    }
                }
            }
        }

19 Source : MainWindow_Dat.cs
with GNU Affero General Public License v3.0
from aianlinb

private void ShowDatFile(DatContainer dat) {
			toMark.Clear();
			DatTable.Tag = dat;
			DatTable.Columns.Clear();
			DatTable.ItemsSource = null;
			var eos = new List<ExpandoObject>(dat.FieldDefinitions.Count);
			for (var i = 0; i < dat.FieldDatas.Count; i++) {
				var eo = new ExpandoObject() as IDictionary<string, object>;
				eo.Add("Row", i);
				var names = dat.FieldDefinitions.Select(t => t.Key).GetEnumerator();
				var values = dat.FieldDatas[i];
				if (values != null)
					foreach (var value in values) {
						names.MoveNext();
						eo.Add(names.Current, value);
					}
				names.Dispose();
				eos.Add((ExpandoObject)eo);
			}

			DatTable.Columns.Add(new DataGridTextColumn {
				Header = "Row",
				Binding = new Binding("Row") { Mode = BindingMode.OneTime },
				Width = dataGridLength,
				IsReadOnly = true
			});

			foreach (var (col, type) in dat.FieldDefinitions)
				DatTable.Columns.Add(new DataGridTextColumn {
					Header = col,
					Binding = new Binding(col + ".StringValue") { TargetNullValue = "{null}", Mode = BindingMode.TwoWay },
					Width = dataGridLength,
					IsReadOnly = type == "array" // Field of this type must be empty array
				});

			DatTable.ItemsSource = new ObservableCollection<ExpandoObject>(eos);

			var lastEndOffset = 8L;
			var row = 0;
			var pointedList = new ObservableCollection<IReferenceData>(dat.ReferenceDatas.Values);
			foreach (var rd in pointedList) {
				if (rd.Offset != lastEndOffset)
					toMark.Add(row);
				lastEndOffset = rd.EndOffset;
				++row;
			}
			
			DatReferenceDataTable.Columns.Clear();
			DatReferenceDataTable.ItemsSource = null;
			DatReferenceDataTable.Columns.Add(new DataGridTextColumn {
				Header = "Offset",
				Binding = new Binding("Offset") { Mode = BindingMode.OneWay },
				Width = dataGridLength,
				IsReadOnly = true
			});
			DatReferenceDataTable.Columns.Add(new DataGridTextColumn {
				Header = "Length",
				Binding = new Binding("Length") { Mode = BindingMode.OneWay },
				Width = dataGridLength,
				IsReadOnly = true
			});
			DatReferenceDataTable.Columns.Add(new DataGridTextColumn {
				Header = "EndOffset",
				Binding = new Binding("EndOffset") { Mode = BindingMode.OneWay },
				Width = dataGridLength,
				IsReadOnly = true
			});
			DatReferenceDataTable.Columns.Add(new DataGridTextColumn {
				Header = "Value",
				Binding = new Binding("StringValue") { TargetNullValue = "{null}", Mode = BindingMode.TwoWay },
				Width = dataGridLength
			});

			DatReferenceDataTable.ItemsSource = pointedList;

			if (dat.Exception != null)
				MessageBox.Show(this, dat.Exception.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error);
		}

19 Source : GGPKContainer.cs
with GNU Affero General Public License v3.0
from aianlinb

public static void RecursiveFileList(RecordTreeNode record, string path, ICollection<KeyValuePair<IFileRecord, string>> list, bool export, string regex = null)
        {
            if (record is IFileRecord fr)
            {
                if ((export || File.Exists(path)) && (regex == null || Regex.IsMatch(record.GetPath(), regex)))
                    list.Add(new(fr, path));
            }
            else
                foreach (var f in record.Children)
                    RecursiveFileList(f, path + "\\" + f.Name, list, export, regex);
        }

19 Source : GGPKContainer.cs
with GNU Affero General Public License v3.0
from aianlinb

public virtual void GetFileList(string ROOTPath, ICollection<KeyValuePair<IFileRecord, string>> list, string searchPattern = "*", string regex = null) {
            var files = Directory.GetFiles(ROOTPath, searchPattern, SearchOption.AllDirectories);
            foreach (var f in files) {
                var path = f[(ROOTPath.Length + 1)..];
                if ((regex == null || Regex.IsMatch(path, regex)) && FindRecord(path) is IFileRecord ifr)
                    list.Add(new(ifr, f));
			}
        }

19 Source : GGPKContainer.cs
with GNU Affero General Public License v3.0
from aianlinb

public virtual void GetFileListFromZip(IEnumerable<ZipArchiveEntry> ZipEntries, ICollection<KeyValuePair<IFileRecord, ZipArchiveEntry>> list, string regex = null) {
            var first = ZipEntries.FirstOrDefault();
            if (first == null)
                return;

            RecordTreeNode parent;
            if (first.FullName.StartsWith("ROOT/"))
                parent = rootDirectory;
            else if (first.FullName.StartsWith("Bundles2/"))
                parent = (RecordTreeNode)FakeBundles2 ?? OriginalBundles2;
            else
                throw new("The root directory in zip must be ROOT or Bundles2");

            var rootNameOffset = parent.Name.Length + 1;
            foreach (var zae in ZipEntries) {
                if (zae.FullName.EndsWith('/'))
                    continue;
                var path = zae.FullName[rootNameOffset..];
                if (regex == null || Regex.IsMatch(path, regex)) {
                    if (FindRecord(path, parent) is not IFileRecord ifr)
                        throw new Exception("Not found in GGPK: " + zae.FullName);
                    list.Add(new(ifr, zae));
                }
			}
        }

19 Source : JsonSchemaBuilder.cs
with MIT License
from akaskela

private void Push(JsonSchema value)
        {
            _currentSchema = value;
            _stack.Add(value);
            _resolver.LoadedSchemas.Add(value);
            _doreplacedentSchemas.Add(value.Location, value);
        }

19 Source : JsonSchemaBuilder.cs
with MIT License
from akaskela

private IDictionary<string, JsonSchema> ProcessProperties(JToken token)
        {
            IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();

            if (token.Type != JTokenType.Object)
            {
                throw JsonException.Create(token, token.Path, "Expected Object token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));
            }

            foreach (JProperty propertyToken in token)
            {
                if (properties.ContainsKey(propertyToken.Name))
                {
                    throw new JsonException("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyToken.Name));
                }

                properties.Add(propertyToken.Name, BuildSchema(propertyToken.Value));
            }

            return properties;
        }

19 Source : DictionaryWrapper.cs
with MIT License
from akaskela

public void Add(KeyValuePair<TKey, TValue> item)
        {
            if (_dictionary != null)
            {
                ((IList)_dictionary).Add(item);
            }
#if !(NET40 || NET35 || NET20 || PORTABLE40)
            else if (_readOnlyDictionary != null)
            {
                throw new NotSupportedException();
            }
#endif
            else if (_genericDictionary != null)
            {
                _genericDictionary.Add(item);
            }
        }

19 Source : ChainManager.cs
with MIT License
from alexanderdna

private static bool validateTransactions(Block block, IList<Transaction> transactions,
            TransactionDb localTxMap, IDictionary<string, Transaction> receivedTxMap,
            HashSet<TxOutPointer> spentTxOutputs)
        {
            for (int i = 0, c = transactions.Count; i < c; ++i)
            {
                var tx = transactions[i];
                bool isValidTx = validateTransaction(block, i, tx, localTxMap, receivedTxMap, spentTxOutputs);
                if (isValidTx)
                {
                    receivedTxMap.Add(tx.Id, tx);
                }
                else
                {
                    return false;
                }
            }

            return true;
        }

19 Source : ExperimentDataExportController.cs
with MIT License
from AlexanderFroemmgen

[HttpGet("{id}/data.json")]
        public IActionResult GetResultData(int id)
        {
            var data =
                _context.Experiments
                    .Include(s => s.Parameters).ThenInclude(p => p.Values)
                    .Include(s => s.ExperimentInstances).ThenInclude(i => i.ParameterValues)
                    .Include(s => s.ExperimentInstances).ThenInclude(i => i.Records)
                    .Single(s => s.Id == id);

            if (data == null)
            {
                return NotFound();
            }
            
            var metadata = new
            {
                Parameters = data.Parameters.MapTo<ParameterDto>(_mapper)
            };
            
            var dataArray = new List<IDictionary<string, object>>();

            foreach (var simInstance in data.ExperimentInstances)
            {
                var simInstanceDataObject = new ExpandoObject() as IDictionary<string, object>;

                foreach (var paramInstance in simInstance.ParameterValues.Select(a => a.ParameterValue))
                {
                    var paramValue = ParseUtils.ParseToClosestPossibleValueType(paramInstance.Value);

                    simInstanceDataObject.Add(paramInstance.Parameter.Name, paramValue);
                }

                var recordArray = new JArray();
                foreach (var record in simInstance.Records)
                {
                    var recordValue = ParseUtils.ParseToClosestPossibleValueType(record.Value);

                    recordArray.Add(JObject.FromObject(new { record.Key, record.Offset, Value = recordValue }));
                }
                simInstanceDataObject.Add("records", recordArray);

                dataArray.Add(simInstanceDataObject);
            }

            return Json(new
            {
                Metadata = metadata,
                Data = dataArray
            });
        }

19 Source : ChainManager.cs
with MIT License
from alexanderdna

private static bool validateBlock(Block block, Block prevBlock,
            TransactionDb localTxMap, IDictionary<string, Transaction> receivedTxMap,
            HashSet<TxOutPointer> spentTxOutputs)
        {
            if (block.Index != prevBlock.Index + 1)
                return false;

            // Block should not be too far in the future
            if (block.Timestamp > TimeUtils.MsSinceEpochToUtcNow() + Config.BlockTimestampMaxFutureOffset)
                return false;

            // Block should not be too close in time to previous block
            if (block.Timestamp - prevBlock.Timestamp < Config.CalculateBlockTimestampMinDistance(block.Index))
                return false;

            if (block.Transactions == null)
                return false;

            for (int i = 0, c = block.Transactions.Count; i < c; ++i)
            {
                var tx = block.Transactions[i];
                bool isValidTx = validateTransaction(block, i, tx, localTxMap, receivedTxMap, spentTxOutputs);
                if (isValidTx)
                {
                    receivedTxMap.Add(tx.Id, tx);
                }
                else
                {
                    return false;
                }
            }

            if (block.MerkleHash != Block.ComputeMerkleHash(block))
                return false;

            if (block.PreviousBlockHash != prevBlock.Hash)
                return false;

            int expectedDifficulty = Pow.CalculateDifficulty(block.Index);
            using (var stream = new MemoryStream())
            {
                using var streamWriter = new StreamWriter(stream, Encoding.UTF8, bufferSize: 1024, leaveOpen: true);
                block.PrepareForPowHash(streamWriter);
                HexUtils.AppendHexFromInt(streamWriter, block.Nonce);
                streamWriter.Flush();
                var hash = Pow.Hash(stream);
                if (!Pow.IsValidHash(hash, expectedDifficulty))
                    return false;
            }

            return true;
        }

19 Source : InitializationFile.cs
with MIT License
from AlexanderPro

private Dictionary<string, IDictionary<string, string>> Load(string fileName, Encoding fileEncoding)
        {
            var content = new Dictionary<string, IDictionary<string, string>>();
            using (var file = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            using (var reader = new StreamReader(file, _fileEncoding))
            {
                string line = null;
                string section = null;
                while ((line = reader.ReadLine()) != null)
                {
                    if (line.Length == 0) continue;
                    if (line.StartsWith(";")) continue;
                    if (line.Length > 2 && line[0] == '[' && line[line.Length - 1] == ']')
                    {
                        section = line.Substring(1, line.Length - 2);
                        if (content.ContainsKey(section)) continue;
                        content[section] = new Dictionary<string, string>();
                    }
                    else
                    {
                        if (section == null) continue;
                        var pair = line.Split('=');
                        if (pair.Length < 2) continue;
                        var keyValue = new KeyValuePair<string, string>(pair[0], pair[1]);
                        if (content[section].Contains(keyValue)) continue;
                        content[section].Add(keyValue);
                    }
                }
            }
            return content;
        }

19 Source : Settings.cs
with GNU General Public License v3.0
from alexgracianoarj

private void Settings_SettingsLoaded(object sender, SettingsLoadedEventArgs e)
		{
			if (CSharpImportList == null)
				CSharpImportList = new StringCollection();
			if (JavaImportList == null)
				JavaImportList = new StringCollection();

			ImportList.Clear();
			ImportList.Add(CSharp.CSharpLanguage.Instance, CSharpImportList);
			ImportList.Add(Java.JavaLanguage.Instance, JavaImportList);

			if (string.IsNullOrEmpty(DestinationPath))
			{
				string myDoreplacedents = Environment.GetFolderPath(Environment.SpecialFolder.MyDoreplacedents);
				DestinationPath = Path.Combine(myDoreplacedents, "NClreplaced Generated Projects");
			}
		}

19 Source : MainForm.cs
with MIT License
from AlexGyver

private void PlotSelectionChanged(object sender, EventArgs e)
        {
            List<ISensor> selected = new List<ISensor>();
            IDictionary<ISensor, Color> colors = new Dictionary<ISensor, Color>();
            int colorIndex = 0;

            foreach (TreeNodeAdv node in treeView.AllNodes)
            {
                if (node.Tag is SensorNode sensorNode)
                {
                    if (sensorNode.Plot)
                    {
                        colors.Add(sensorNode.Sensor,
                          plotColorPalette[colorIndex % plotColorPalette.Length]);
                        selected.Add(sensorNode.Sensor);
                    }
                    colorIndex++;
                }
            }

            sensorPlotColors = colors;
            plotPanel.SetSensors(selected, colors);
        }

19 Source : DataConnectionConfiguration.cs
with GNU General Public License v3.0
from alexgracianoarj

public void LoadConfiguration(DataConnectionDialog dialog, SqlType serverType)
		{
            
            this.dataSources = new Dictionary<string, DataSource>();
            this.dataProviders = new Dictionary<string, DataProvider>();

		    switch (serverType)
		    {
		        case SqlType.Oracle:
                    dialog.DataSources.Add(DataSource.OracleDataSource);
                    dialog.UnspecifiedDataSource.Providers.Add(DataProvider.OracleDataProvider);
                    this.dataSources.Add(DataSource.OracleDataSource.Name, DataSource.OracleDataSource);
                    this.dataProviders.Add(DataProvider.OracleDataProvider.Name, DataProvider.OracleDataProvider);
		            break;
		        case SqlType.SqlServer:
                    dialog.DataSources.Add(DataSource.SqlDataSource);
                    this.dataSources.Add(DataSource.SqlDataSource.Name, DataSource.SqlDataSource);
                    this.dataProviders.Add(DataProvider.SqlDataProvider.Name, DataProvider.SqlDataProvider);
		            break;
		        default:
                    dialog.UnspecifiedDataSource.Providers.Add(DataProvider.OleDBDataProvider);
                    this.dataProviders.Add(DataProvider.OleDBDataProvider.Name, DataProvider.OleDBDataProvider);
			        dialog.DataSources.Add(dialog.UnspecifiedDataSource);
                    this.dataSources.Add(dialog.UnspecifiedDataSource.DisplayName, dialog.UnspecifiedDataSource);
		            break;
		    }

			DataSource ds = null;
			string dsName = this.GetSelectedSource();
			if (!String.IsNullOrEmpty(dsName) && this.dataSources.TryGetValue(dsName, out ds))
			{
				dialog.SelectedDataSource = ds;
			}

			DataProvider dp = null;
			string dpName = this.GetSelectedProvider();
			if (!String.IsNullOrEmpty(dpName) && this.dataProviders.TryGetValue(dpName, out dp))
			{
				dialog.SelectedDataProvider = dp;
			}
		}

19 Source : MainForm.cs
with MIT License
from AlexGyver

private void PlotSelectionChanged(object sender, EventArgs e) {
      List<ISensor> selected = new List<ISensor>();
      IDictionary<ISensor, Color> colors = new Dictionary<ISensor, Color>();
      int colorIndex = 0;
      foreach (TreeNodeAdv node in treeView.AllNodes) {
        SensorNode sensorNode = node.Tag as SensorNode;
        if (sensorNode != null) {
          if (sensorNode.Plot) {
            colors.Add(sensorNode.Sensor,
              plotColorPalette[colorIndex % plotColorPalette.Length]);
            selected.Add(sensorNode.Sensor);
          }
          colorIndex++;
        }
      }
      sensorPlotColors = colors;
      plotPanel.SetSensors(selected, colors);
    }

19 Source : KrakenApiClient.cs
with Apache License 2.0
from AlexWan

private void SynchronizeSubscriptions(SubscriptionStatus currentStatus)
        {
            if (currentStatus.ChannelId == null || !currentStatus.ChannelId.HasValue)
            {
                //logger.LogWarning("SubscriptionStatus has no channelID");
                // no channelID --> error?
                return;
            }

            // handle unsubscribe
            var channelIdValue = currentStatus.ChannelId.Value;
            if (currentStatus.Status == "unsubscribed")
            {
                if (!Subscriptions.ContainsKey(channelIdValue)) return;

                Subscriptions.Remove(channelIdValue);
                //logger.LogDebug("Subscription for {channelID} successfully removed", channelIdValue);
                return;
            }

            // handle subscription
            var value = channelIdValue;
            if (Subscriptions.ContainsKey(value))
            {
                Subscriptions[value] = currentStatus;
            }
            else
            {
                Subscriptions.Add(value, currentStatus);
            }
        }

19 Source : IndexKeysBuilder.cs
with MIT License
from aliyun

public IndexKeysBuilder AddLong(String key, Boolean? docValue = null, String alias = null)
        {
            var longKeyInfo = new IndexLongKeyInfo
            {
                DocValue = docValue,
                Alias = alias
            };

            this.keys.Add(key, longKeyInfo);

            return this;
        }

19 Source : AckMessageRequestMarshaller.cs
with MIT License
from aliyunmq

private static void PopulateSpecialParameters(AckMessageRequest request, IDictionary<string, string> paramters)
        {
            paramters.Add(Constants.PARAMETER_CONSUMER, request.Consumer);
            if (request.IsSetInstance())
            {
                paramters.Add(Constants.PARAMETER_NS, request.IntanceId);
            }
            if (request.IsSetTransaction())
            {
                paramters.Add(Constants.PARAMETER_TRANSACTION, request.Trasaction);
            }
        }

19 Source : ConsumeMessageRequestMarshaller.cs
with MIT License
from aliyunmq

private static void PopulateSpecialParameters(ConsumeMessageRequest request, IDictionary<string, string> paramters)
        {
            paramters.Add(Constants.PARAMETER_CONSUMER, request.Consumer);
            if (request.IsSetInstance()) 
            {
                paramters.Add(Constants.PARAMETER_NS, request.IntanceId);
            }
            if (request.IsSetWaitSeconds() && request.WaitSeconds > 0 && request.WaitSeconds < 31)
            {
                paramters.Add(Constants.PARAMETER_WAIT_SECONDS, request.WaitSeconds.ToString());
            }
            paramters.Add(Constants.PARAMETER_BATCH_SIZE, request.BatchSize.ToString());
            if (request.IsSetMessageTag()) 
            {
                paramters.Add(Constants.PARAMETER_CONSUME_TAG, request.MessageTag);
            }
            if (request.IsSetTransaction())
            {
                paramters.Add(Constants.PARAMETER_TRANSACTION, request.Trasaction);
            }
        }

19 Source : PublishMessageRequestMarshaller.cs
with MIT License
from aliyunmq

private static void PopulateSpecialParameters(PublishMessageRequest request, IDictionary<string, string> paramters)
        {
            if (request.IsSetInstance()) {
                paramters.Add(Constants.PARAMETER_NS, request.IntanceId);
            }
        }

19 Source : Marshaller.cs
with MIT License
from aliyunmq

private void AddRequiredHeaders(IRequestContext requestContext)
        {
            IDictionary<string, string> headers = requestContext.Request.Headers;
            headers[Constants.UserAgentHeader] = requestContext.ClientConfig.UserAgent;
            if (requestContext.Request.ContentStream != null)
                headers[Constants.ContentLengthHeader] = requestContext.Request.ContentStream.Length.ToString(CultureInfo.InvariantCulture);
            headers[Constants.DateHeader] = AliyunSDKUtils.FormattedCurrentTimestampRFC822;
            headers[Constants.XMQVersionHeader] = requestContext.ClientConfig.ServiceVersion;
            if (!headers.ContainsKey(Constants.HostHeader))
            {
                Uri requestEndpoint = requestContext.Request.Endpoint;
                var hostHeader = requestEndpoint.Host;
                if (!requestEndpoint.IsDefaultPort)
                    hostHeader += ":" + requestEndpoint.Port;
                headers.Add(Constants.HostHeader, hostHeader);
            }
        }

19 Source : IndexKeysBuilder.cs
with MIT License
from aliyun

public IndexKeysBuilder AddDouble(String key, Boolean? docValue = null, String alias = null)
        {
            var doubleKeyInfo = new IndexDoubleKeyInfo
            {
                DocValue = docValue,
                Alias = alias
            };

            this.keys.Add(key, doubleKeyInfo);

            return this;
        }

19 Source : IndexKeysBuilder.cs
with MIT License
from aliyun

public IndexKeysBuilder AddJson(String key, IEnumerable<Char> token, Int32 maxDepth,
            Boolean? chn = null, Boolean? indexAll = null, Action<IndexKeysBuilder> jsonKeys = null)
        {
            if (!this.allowJson)
            {
                throw new InvalidOperationException("json index info is not support in current state.");
            }

            var frozenToken = token?.ToArray(); // Avoid recalculate the non-reentranceable IEnumerable.
            Ensure.NotEmpty(frozenToken, nameof(token));

            IDictionary<String, IndexKeyInfo> subKeys;
            if (jsonKeys != null)
            {
                var subBuilder = new IndexKeysBuilder(false);
                jsonKeys(subBuilder);
                subKeys = subBuilder.Build();
            } else
            {
                subKeys = null;
            }

            var jsonKeyInfo = new IndexJsonKeyInfo(frozenToken, maxDepth)
            {
                Chn = chn,
                IndexAll = indexAll,
                JsonKeys = subKeys
            };

            this.keys.Add(key, jsonKeyInfo);

            return this;
        }

19 Source : HttpRequestMessageBuilder.cs
with MIT License
from aliyun

public IRequestBuilder<HttpRequestMessage> Query(Object queryModel)
        {
            foreach (var kv in JObject.FromObject(queryModel, JsonSerializer.CreateDefault(JsonSerializerSettings)))
            {
                this.query.Add(kv.Key, kv.Value.Value<String>());
            }

            return this;
        }

19 Source : IndexKeysBuilder.cs
with MIT License
from aliyun

public IndexKeysBuilder AddText(String key, IEnumerable<Char> token, Boolean? caseSensitive = null, Boolean? chn = null)
        {
            var frozenToken = token?.ToArray(); // Avoid recalculate the non-reentranceable IEnumerable.
            Ensure.NotEmpty(frozenToken, nameof(token));

            var textKeyInfo = new IndexTextKeyInfo(frozenToken)
            {
                CaseSensitive = caseSensitive,
                Chn = chn
            };

            this.keys.Add(key, textKeyInfo);

            return this;
        }

19 Source : ExpandoObjectResolver.cs
with Apache License 2.0
from allenai

protected override object DeserializeMap(ref MessagePackReader reader, int length, MessagePackSerializerOptions options)
            {
                IMessagePackFormatter<string> keyFormatter = options.Resolver.GetFormatterWithVerify<string>();
                IMessagePackFormatter<object> objectFormatter = options.Resolver.GetFormatter<object>();
                IDictionary<string, object> dictionary = new ExpandoObject();
                for (int i = 0; i < length; i++)
                {
                    var key = keyFormatter.Deserialize(ref reader, options);
                    var value = objectFormatter.Deserialize(ref reader, options);
                    dictionary.Add(key, value);
                }

                return dictionary;
            }

19 Source : ClientUpdateQueryDataMapper.cs
with MIT License
from amolines

public ClientUpdateQuery Mapper(IEnvelope source)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>
            {
                { "@AggregateId", source.AggregateId},

            };
            if(source.Payload.ContainsKey("FirstName"))
                parameters.Add("@Name", source.Payload["FirstName"] );

            if (source.Payload.ContainsKey("LastName"))
                parameters.Add("@LastName", source.Payload["LastName"]);

            if (source.Payload.ContainsKey("Email"))
                parameters.Add("@Email", source.Payload["Email"]);



            return new ClientUpdateQuery(parameters);
        }

19 Source : IssueTrackerConfigDialog.cs
with Apache License 2.0
from AmpScm

private IssueRepositoryConfigurationPage GetConfigurationPageFor(IssueRepositoryConnector connector, ref bool needsCurrentSettings)
        {
            if (connector == null)
            {
                return null;
            }
            if (_connectorPageMap == null)
            {
                _connectorPageMap = new Dictionary<string, IssueRepositoryConfigurationPage>();
            }
            IssueRepositoryConfigurationPage configPage = null;
            if (_connectorPageMap.ContainsKey(connector.Name))
            {
                configPage = _connectorPageMap[connector.Name];
            }
            else
            {
                Exception exception = null;
                try
                {
                    // triggers connector package initialization
                    configPage = connector.ConfigurationPage;
                }
                catch (Exception exc)
                {
                    exception = exc;
                }
                if (configPage == null)
                {
                    // use a dummy configuration page in case where connector does not provide a configuration page or
                    // if an exception is thrown while initializing the connector.
                    configPage = exception == null ?
                        new DummyIssueRepositoryConfigurationPage(string.Format("'{0}' does not provide a configuration page.", connector.Name))
                        : new DummyIssueRepositoryConfigurationPage(exception);
                }
                _connectorPageMap.Add(connector.Name, configPage);
                needsCurrentSettings = true;
            }
            return configPage;
        }

19 Source : SmartListView.cs
with Apache License 2.0
from AmpScm

public IDictionary<string, int> GetColumnWidths()
        {
            IDictionary<string, int> widths = new Dictionary<string, int>(_allColumns.Count);

            foreach (SmartColumn item in _allColumns)
            {
                if (!string.IsNullOrEmpty(item.Name))
                {
                    widths.Add(item.Name, item.DefaultWidth == item.Width ? -1 : item.Width);
                }
            }

            return widths;
        }

19 Source : IssueTrackerConfigDialog.cs
with Apache License 2.0
from AmpScm

private void UpdatePageFor(IssueRepositoryConnector connector)
        {
            configPagePanel.Controls.Clear();

            bool needsCurrentSettings = false;
            _configPage = GetConfigurationPageFor(connector, ref needsCurrentSettings);

            if (_connectorPageControlMap == null)
            {
                _connectorPageControlMap = new Dictionary<string, Control>();
            }

            Control newControl = null;
            if (!_connectorPageControlMap.TryGetValue(connector.Name, out newControl))
            {
                newControl = GetControlFor(_configPage);
                newControl.Dock = DockStyle.Fill;
                _connectorPageControlMap.Add(connector.Name, newControl);
            }

            // setup config page
            if (_configPage != null)
            {
                _configPage.OnPageEvent += new EventHandler<ConfigPageEventArgs>(_configPage_OnPageEvent);
            }

            configPagePanel.Controls.Add(newControl);

            if (_configPage != null && needsCurrentSettings)
            {
                BeginInvoke((DoSomething)delegate()
                {
                    IssueRepositorySettings currentSettings = CurrentSolutionSettings;
                    if (currentSettings != null
                        && string.Equals(currentSettings.ConnectorName, connector.Name))
                    {
                        _configPage.Settings = currentSettings;
                    }
                });
            }
        }

See More Examples