System.Collections.Generic.IDictionary.ContainsKey(string)

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

2008 Examples 7

19 View Source File : QuickAndDirtyCache.cs
License : MIT License
Project Creator : 1iveowl

public async Task CacheObject<T>(T obj, string key)
        {
            if (_cacheDictionary.ContainsKey(key))
            {
                _cacheDictionary.Remove(key);
            }

            _cacheDictionary.Add(key, obj);

            await Task.CompletedTask;
        }

19 View Source File : ProjectReferences.cs
License : MIT License
Project Creator : 3F

public IEnumerable<Item> GetReferences(string guid)
        {
            if(String.IsNullOrWhiteSpace(guid) || !References.ContainsKey(guid)) {
                return new List<Item>();
            }
            return References[guid];
        }

19 View Source File : LProjectDependencies.cs
License : MIT License
Project Creator : 3F

public Projecreplacedem GetProjectBy(string guid)
        {
            if(String.IsNullOrWhiteSpace(guid) || !Projects.ContainsKey(guid)) {
                return default(Projecreplacedem);
            }
            return Projects[guid];
        }

19 View Source File : ProjectReferences.cs
License : MIT License
Project Creator : 3F

protected void InitReferences()
        {
            References = new Dictionary<string, List<Item>>();
            foreach(var project in XProjects)
            {
                var pguid = FormatGuid(project.ProjectGuid);

                if(!References.ContainsKey(pguid)) {
                    References[pguid] = new List<Item>();
                }
                project.GetProjectReferences().ForEach(i => References[pguid].Add(i));
            }
        }

19 View Source File : XProjectEnv.cs
License : MIT License
Project Creator : 3F

public Project GetOrLoadProject(Projecreplacedem pItem, IDictionary<string, string> properties)
        {
            if(String.IsNullOrWhiteSpace(pItem.pGuid)) {
                throw new ArgumentException($"GUID of project is empty or null ['{pItem.name}', '{pItem.fullPath}']");
            }

            if(!properties.ContainsKey(PropertyNames.CONFIG) || !properties.ContainsKey(PropertyNames.PLATFORM)) {
                throw new ArgumentException($"Properties does not contain {PropertyNames.CONFIG} or {PropertyNames.PLATFORM} key.");
            }

            foreach(var eProject in ValidProjects)
            {
                if(IsEqual(eProject, pItem, properties[PropertyNames.CONFIG], properties[PropertyNames.PLATFORM])) {
                    //LSender.Send(this, $"Found project from collection {pItem.pGuid}: {propCfg} == {eCfg}", Message.Level.Trace);
                    return eProject;
                }
            }

            LSender.Send(this, $"Load project {pItem.pGuid}:{properties[PropertyNames.CONFIG]}|{properties[PropertyNames.PLATFORM]} :: '{pItem.name}' ('{pItem.fullPath}')", Message.Level.Info);
            if(String.IsNullOrWhiteSpace(pItem.fullPath)) {
                throw new NotFoundException($"Path is empty to project ['{pItem.name}', '{pItem.pGuid}']");
            }

            return Load(pItem, properties);
        }

19 View Source File : XProjectEnv.cs
License : MIT License
Project Creator : 3F

public IDictionary<string, string> GetProjectProperties(Projecreplacedem pItem, IDictionary<string, string> slnProps)
        {
            if(!slnProps.ContainsKey(PropertyNames.CONFIG) || !slnProps.ContainsKey(PropertyNames.PLATFORM)) {
                throw new ArgumentException("Solution Configuration or Platform is not defined in used properties.");
            }

            var cfg = Sln.ProjectConfigs
                    .FirstOrDefault(c => 
                        c.PGuid == pItem.pGuid 
                        && c.Sln.IsEqualByRule
                        (
                            slnProps[PropertyNames.CONFIG], 
                            slnProps[PropertyNames.PLATFORM], 
                            true
                        )
                    );

            if(cfg?.Configuration == null || cfg.Platform == null)
            {
                LSender.Send(
                    this, 
                    String.Format(
                        "Project configuration is not found <- sln [{0}|{1}]",
                        slnProps[PropertyNames.CONFIG],
                        slnProps[PropertyNames.PLATFORM]
                    ), 
                    Message.Level.Warn
                );
                return slnProps;
            }

            string config   = cfg.ConfigurationByRule;
            string platform = cfg.PlatformByRule;
            LSender.Send(this, $"-> prj['{config}'; '{platform}']", Message.Level.Info);

            return new Dictionary<string, string>(slnProps) {
                [PropertyNames.CONFIG]      = config,
                [PropertyNames.PLATFORM]    = platform
            };
        }

19 View Source File : XProjectEnv.cs
License : MIT License
Project Creator : 3F

protected Project Load(Projecreplacedem pItem, IDictionary<string, string> properties)
        {
            if(rawXmlProjects != null && rawXmlProjects.ContainsKey(pItem.pGuid)) {
                return Load(rawXmlProjects[pItem.pGuid], properties);
            }
            return Load(pItem.fullPath, properties);
        }

19 View Source File : JsonMapper.cs
License : MIT License
Project Creator : 404Lcc

private static object ReadValue (Type inst_type, JsonReader reader)
        {
            reader.Read ();

            if (reader.Token == JsonToken.ArrayEnd)
                return null;

            //ILRuntime doesn't support nullable valuetype
            Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
            Type value_type = inst_type;

            if (reader.Token == JsonToken.Null) {
                if (inst_type.IsClreplaced || underlying_type != null) {
                    return null;
                }

                throw new JsonException (String.Format (
                            "Can't replacedign null to an instance of type {0}",
                            inst_type));
            }

            if (reader.Token == JsonToken.Double ||
                reader.Token == JsonToken.Int ||
                reader.Token == JsonToken.Long ||
                reader.Token == JsonToken.String ||
                reader.Token == JsonToken.Boolean) {

                Type json_type = reader.Value.GetType();
                var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;

                if (vt.IsreplacedignableFrom(json_type))
                    return reader.Value;
                if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
                {
                    if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
                        return reader.Value;
                }
                // If there's a custom importer that fits, use it
                if (custom_importers_table.ContainsKey (json_type) &&
                    custom_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        custom_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe there's a base importer that works
                if (base_importers_table.ContainsKey (json_type) &&
                    base_importers_table[json_type].ContainsKey (
                        vt)) {

                    ImporterFunc importer =
                        base_importers_table[json_type][vt];

                    return importer (reader.Value);
                }

                // Maybe it's an enum
                if (vt.IsEnum)
                    return Enum.ToObject (vt, reader.Value);

                // Try using an implicit conversion operator
                MethodInfo conv_op = GetConvOp (vt, json_type);

                if (conv_op != null)
                    return conv_op.Invoke (null,
                                           new object[] { reader.Value });

                // No luck
                throw new JsonException (String.Format (
                        "Can't replacedign value '{0}' (type {1}) to type {2}",
                        reader.Value, json_type, inst_type));
            }

            object instance = null;

            if (reader.Token == JsonToken.ArrayStart) {

                AddArrayMetadata (inst_type);
                ArrayMetadata t_data = array_metadata[inst_type];

                if (! t_data.IsArray && ! t_data.IsList)
                    throw new JsonException (String.Format (
                            "Type {0} can't act as an array",
                            inst_type));

                IList list;
                Type elem_type;

                if (! t_data.IsArray) {
                    list = (IList) Activator.CreateInstance (inst_type);
                    elem_type = t_data.ElementType;
                } else {
                    list = new ArrayList ();
                    elem_type = inst_type.GetElementType ();
                }

                while (true) {
                    object item = ReadValue (elem_type, reader);
                    if (item == null && reader.Token == JsonToken.ArrayEnd)
                        break;
                    var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
                    if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
                    {
                        item = (int) item;
                    }
                    else
                    {
                        item = rt.CheckCLRTypes(item);            
                    }
                    list.Add (item);         
                    
                }

                if (t_data.IsArray) {
                    int n = list.Count;
                    instance = Array.CreateInstance (elem_type, n);

                    for (int i = 0; i < n; i++)
                        ((Array) instance).SetValue (list[i], i);
                } else
                    instance = list;

            } else if (reader.Token == JsonToken.ObjectStart)
            {
                AddObjectMetadata(value_type);
                ObjectMetadata t_data = object_metadata[value_type];
                if (value_type is ILRuntime.Reflection.ILRuntimeType)
                    instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
                else
                    instance = Activator.CreateInstance(value_type);
                bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
                while (true)
                {
                    reader.Read();

                    if (reader.Token == JsonToken.ObjectEnd)
                        break;

                    string key = (string) reader.Value;

                    if (t_data.Properties.ContainsKey(key))
                    {
                        PropertyMetadata prop_data =
                            t_data.Properties[key];

                        if (prop_data.IsField)
                        {
                            ((FieldInfo) prop_data.Info).SetValue(
                                instance, ReadValue(prop_data.Type, reader));
                        }
                        else
                        {
                            PropertyInfo p_info =
                                (PropertyInfo) prop_data.Info;

                            if (p_info.CanWrite)
                                p_info.SetValue(
                                    instance,
                                    ReadValue(prop_data.Type, reader),
                                    null);
                            else
                                ReadValue(prop_data.Type, reader);
                        }

                    }
                    else
                    {
                        if (!t_data.IsDictionary)
                        {

                            if (!reader.SkipNonMembers)
                            {
                                throw new JsonException(String.Format(
                                    "The type {0} doesn't have the " +
                                    "property '{1}'",
                                    inst_type, key));
                            }
                            else
                            {
                                ReadSkip(reader);
                                continue;
                            }
                        }

                        var dict = ((IDictionary) instance);
                        var elem_type = t_data.ElementType;
                        object readValue = ReadValue(elem_type, reader);
                        var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
                            ? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
                            : t_data.ElementType;
                        //value 是枚举的情况没处理,毕竟少
                        if (isIntKey)
                        {
                            var dictValueType = value_type.GetGenericArguments()[1];
                            IConvertible convertible = dictValueType as IConvertible;
                            if (convertible == null)
                            {
                                //自定义类型扩展
                                if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
                                {
                                    var v = Convert.ChangeType(readValue.ToString(), dictValueType);
                                    dict.Add(Convert.ToInt32(key), v);
                                }
                                else
                                {
                                    readValue = rt.CheckCLRTypes(readValue);
                                    dict.Add(Convert.ToInt32(key), readValue);
                                    // throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
                                }
                            }
                            else
                            {
                                var v = Convert.ChangeType(readValue, dictValueType);
                                dict.Add(Convert.ToInt32(key), v);
                            }
                        }
                        else
                        {
                            readValue = rt.CheckCLRTypes(readValue);
                            dict.Add(key, readValue);
                        }
                    }

                }
            }

            return instance;
        }

19 View Source File : Shared.cs
License : MIT License
Project Creator : 7coil

public static string getString(string key)
        {
            if (Strings.ContainsKey(key))
            {
                return Strings[key];
            }
            else
            {
                return getString("unknown_key");
            }
        }

19 View Source File : ExampleSearchProvider.cs
License : MIT License
Project Creator : ABTSoftware

private IEnumerable<Guid> RankDoreplacedents(string[] terms, IEnumerable<Guid> examplePageIds, IDictionary<string, Posting> invertedIndex)
        {
            var queryVector = new double[terms.Length];
            var docVectors = new Dictionary<Guid, double[]>();
            var docScores = new Dictionary<Guid, double>();

            for (int i = 0; i < terms.Length; i++)
            {
                string term = terms[i];
                if (!invertedIndex.ContainsKey(term))
                {
                    continue;
                }

                var posting = invertedIndex[term];
                queryVector[i] = (posting.InvertedDoreplacedentFrequency);

                foreach (var termInfo in posting.TermInfos)
                {
                    var examplePageId = termInfo.ExamplePageId;
                    if (examplePageIds.Contains(examplePageId))
                    {
                        if (!docVectors.ContainsKey(examplePageId))
                        {
                            docVectors[examplePageId] = new double[terms.Length];
                        }
                        docVectors[examplePageId][i] = termInfo.TermFrequency;
                    }
                }
            }

            foreach (var docVector in docVectors)
            {
                var dotProduct = DotProduct(docVector.Value, queryVector);
                docScores.Add(docVector.Key, dotProduct);
            }

            return docScores.OrderByDescending(pair => pair.Value).Select(pair => pair.Key);
        }

19 View Source File : DataManager.cs
License : MIT License
Project Creator : ABTSoftware

public PriceSeries GetPriceData(string dataset)
        {
            if (_dataSets.ContainsKey(dataset))
            {
                return _dataSets[dataset];
            }

            // e.g. resource format: SciChart.Examples.ExternalDependencies.Resources.Data.EURUSD_Daily.csv 
            var csvResource = string.Format("{0}.{1}", ResourceDirectory, Path.ChangeExtension(dataset, "csv.gz"));

            var priceSeries = new PriceSeries();
            priceSeries.Symbol = dataset;

            var replacedembly = typeof(DataManager).replacedembly;
            // Debug.WriteLine(string.Join(", ", replacedembly.GetManifestResourceNames()));
            using (var stream = replacedembly.GetManifestResourceStream(csvResource))
            using (var gz = new GZipStream(stream, CompressionMode.Decompress))
            using (var streamReader = new StreamReader(gz))
            {
                string line = streamReader.ReadLine();
                while (line != null)
                {
                    var priceBar = new PriceBar();
                    // Line Format: 
                    // Date, Open, High, Low, Close, Volume 
                    // 2007.07.02 03:30, 1.35310, 1.35310, 1.35280, 1.35310, 12 
                    var tokens = line.Split(',');
                    priceBar.DateTime = DateTime.Parse(tokens[0], DateTimeFormatInfo.InvariantInfo);
                    priceBar.Open = double.Parse(tokens[1], NumberFormatInfo.InvariantInfo);
                    priceBar.High = double.Parse(tokens[2], NumberFormatInfo.InvariantInfo);
                    priceBar.Low = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo);
                    priceBar.Close = double.Parse(tokens[4], NumberFormatInfo.InvariantInfo);
                    priceBar.Volume = long.Parse(tokens[5], NumberFormatInfo.InvariantInfo);
                    priceSeries.Add(priceBar);

                    line = streamReader.ReadLine();
                }
            }

            _dataSets.Add(dataset, priceSeries);

            return priceSeries;
        }

19 View Source File : ProcessInvoker.cs
License : MIT License
Project Creator : actions

public async Task<int> ExecuteAsync(
            string workingDirectory,
            string fileName,
            string arguments,
            IDictionary<string, string> environment,
            bool requireExitCodeZero,
            Encoding outputEncoding,
            bool killProcessOnCancel,
            Channel<string> redirectStandardIn,
            bool inheritConsoleHandler,
            bool keepStandardInOpen,
            bool highPriorityProcess,
            CancellationToken cancellationToken)
        {
            ArgUtil.Null(_proc, nameof(_proc));
            ArgUtil.NotNullOrEmpty(fileName, nameof(fileName));

            Trace.Info("Starting process:");
            Trace.Info($"  File name: '{fileName}'");
            Trace.Info($"  Arguments: '{arguments}'");
            Trace.Info($"  Working directory: '{workingDirectory}'");
            Trace.Info($"  Require exit code zero: '{requireExitCodeZero}'");
            Trace.Info($"  Encoding web name: {outputEncoding?.WebName} ; code page: '{outputEncoding?.CodePage}'");
            Trace.Info($"  Force kill process on cancellation: '{killProcessOnCancel}'");
            Trace.Info($"  Redirected STDIN: '{redirectStandardIn != null}'");
            Trace.Info($"  Persist current code page: '{inheritConsoleHandler}'");
            Trace.Info($"  Keep redirected STDIN open: '{keepStandardInOpen}'");
            Trace.Info($"  High priority process: '{highPriorityProcess}'");

            _proc = new Process();
            _proc.StartInfo.FileName = fileName;
            _proc.StartInfo.Arguments = arguments;
            _proc.StartInfo.WorkingDirectory = workingDirectory;
            _proc.StartInfo.UseShellExecute = false;
            _proc.StartInfo.CreateNoWindow = !inheritConsoleHandler;
            _proc.StartInfo.RedirectStandardInput = true;
            _proc.StartInfo.RedirectStandardError = true;
            _proc.StartInfo.RedirectStandardOutput = true;

            // Ensure we process STDERR even the process exit event happen before we start read STDERR stream. 
            if (_proc.StartInfo.RedirectStandardError)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

            // Ensure we process STDOUT even the process exit event happen before we start read STDOUT stream.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                Interlocked.Increment(ref _asyncStreamReaderCount);
            }

#if OS_WINDOWS
            // If StandardErrorEncoding or StandardOutputEncoding is not specified the on the
            // ProcessStartInfo object, then .NET PInvokes to resolve the default console output
            // code page:
            //      [DllImport("api-ms-win-core-console-l1-1-0.dll", SetLastError = true)]
            //      public extern static uint GetConsoleOutputCP();
            StringUtil.EnsureRegisterEncodings();
#endif
            if (outputEncoding != null)
            {
                _proc.StartInfo.StandardErrorEncoding = outputEncoding;
                _proc.StartInfo.StandardOutputEncoding = outputEncoding;
            }

            // Copy the environment variables.
            if (environment != null && environment.Count > 0)
            {
                foreach (KeyValuePair<string, string> kvp in environment)
                {
                    _proc.StartInfo.Environment[kvp.Key] = kvp.Value;
                }
            }

            // Indicate GitHub Actions process.
            _proc.StartInfo.Environment["GITHUB_ACTIONS"] = "true";

            // Set CI=true when no one else already set it.
            // CI=true is common set in most CI provider in GitHub
            if (!_proc.StartInfo.Environment.ContainsKey("CI") &&
                Environment.GetEnvironmentVariable("CI") == null)
            {
                _proc.StartInfo.Environment["CI"] = "true";
            }

            // Hook up the events.
            _proc.EnableRaisingEvents = true;
            _proc.Exited += ProcessExitedHandler;

            // Start the process.
            _stopWatch = Stopwatch.StartNew();
            _proc.Start();

            // Decrease invoked process priority, in platform specifc way, relative to parent
            if (!highPriorityProcess)
            {
                DecreaseProcessPriority(_proc);
            }

            // Start the standard error notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardError)
            {
                StartReadStream(_proc.StandardError, _errorData);
            }

            // Start the standard output notifications, if appropriate.
            if (_proc.StartInfo.RedirectStandardOutput)
            {
                StartReadStream(_proc.StandardOutput, _outputData);
            }

            if (_proc.StartInfo.RedirectStandardInput)
            {
                if (redirectStandardIn != null)
                {
                    StartWriteStream(redirectStandardIn, _proc.StandardInput, keepStandardInOpen);
                }
                else
                {
                    // Close the input stream. This is done to prevent commands from blocking the build waiting for input from the user.
                    _proc.StandardInput.Close();
                }
            }

            var cancellationFinished = new TaskCompletionSource<bool>();
            using (var registration = cancellationToken.Register(async () =>
            {
                await CancelAndKillProcessTree(killProcessOnCancel);
                cancellationFinished.TrySetResult(true);
            }))
            {
                Trace.Info($"Process started with process id {_proc.Id}, waiting for process exit.");
                while (true)
                {
                    Task outputSignal = _outputProcessEvent.WaitAsync();
                    var signaled = await Task.WhenAny(outputSignal, _processExitedCompletionSource.Task);

                    if (signaled == outputSignal)
                    {
                        ProcessOutput();
                    }
                    else
                    {
                        _stopWatch.Stop();
                        break;
                    }
                }

                // Just in case there was some pending output when the process shut down go ahead and check the
                // data buffers one last time before returning
                ProcessOutput();

                if (cancellationToken.IsCancellationRequested)
                {
                    // Ensure cancellation also finish on the cancellationToken.Register thread.
                    await cancellationFinished.Task;
                    Trace.Info($"Process Cancellation finished.");
                }

                Trace.Info($"Finished process {_proc.Id} with exit code {_proc.ExitCode}, and elapsed time {_stopWatch.Elapsed}.");
            }

            cancellationToken.ThrowIfCancellationRequested();

            // Wait for process to finish.
            if (_proc.ExitCode != 0 && requireExitCodeZero)
            {
                throw new ProcessExitCodeException(exitCode: _proc.ExitCode, fileName: fileName, arguments: arguments);
            }

            return _proc.ExitCode;
        }

19 View Source File : VssHttpRequestSettings.cs
License : MIT License
Project Creator : actions

protected internal virtual Boolean ApplyTo(HttpRequestMessage request)
        {
            // Make sure we only apply the settings to the request once
            if (request.Properties.ContainsKey(PropertyName))
            {
                return false;
            }

            request.Properties.Add(PropertyName, this);

            if (this.AcceptLanguages != null && this.AcceptLanguages.Count > 0)
            {
                // An empty or null CultureInfo name will cause an ArgumentNullException in the
                // StringWithQualityHeaderValue constructor. CultureInfo.InvariantCulture is an example of
                // a CultureInfo that has an empty name.
                foreach (CultureInfo culture in this.AcceptLanguages.Where(a => !String.IsNullOrEmpty(a.Name)))
                {
                    request.Headers.AcceptLanguage.Add(new StringWithQualityHeaderValue(culture.Name));
                }
            }

            if (this.UserAgent != null)
            {
                foreach (var headerVal in this.UserAgent)
                {
                    if (!request.Headers.UserAgent.Contains(headerVal))
                    {
                        request.Headers.UserAgent.Add(headerVal);
                    }
                }
            }

            if (this.SuppressFedAuthRedirects)
            {
                request.Headers.Add(Internal.HttpHeaders.TfsFedAuthRedirect, "Suppress");
            }

            // Record the command, if we have it.  Otherwise, just record the session ID.
            if (!request.Headers.Contains(Internal.HttpHeaders.TfsSessionHeader))
            {
                if (!String.IsNullOrEmpty(this.OperationName))
                {
                    request.Headers.Add(Internal.HttpHeaders.TfsSessionHeader, String.Concat(this.SessionId.ToString("D"), ", ", this.OperationName));
                }
                else
                {
                    request.Headers.Add(Internal.HttpHeaders.TfsSessionHeader, this.SessionId.ToString("D"));
                }
            }

            if (!String.IsNullOrEmpty(this.AgentId))
            {
                request.Headers.Add(Internal.HttpHeaders.VssAgentHeader, this.AgentId);
            }

            // Content is being sent as chunked by default in dotnet5.4, which differs than the .net 4.5 behaviour.
            if (request.Content != null && !request.Content.Headers.ContentLength.HasValue && !request.Headers.TransferEncodingChunked.HasValue)
            {
                request.Content.Headers.ContentLength = request.Content.ReadAsByteArrayAsync().Result.Length;
            }

            return true;
        }

19 View Source File : ReferenceLinks.cs
License : MIT License
Project Creator : actions

[EditorBrowsable(EditorBrowsableState.Never)]
        public void AddLink(string name, string href, ISecuredObject securedObject)
        {
            if (referenceLinks.ContainsKey(name))
            {
                IList<ReferenceLink> links;
                if (referenceLinks[name] is ReferenceLink)
                {
                    // promote to a list of links
                    links = new List<ReferenceLink>();
                    links.Add((ReferenceLink)referenceLinks[name]);
                    referenceLinks[name] = links;
                }
                else
                {
                    links = (IList<ReferenceLink>)referenceLinks[name];
                }

                links.Add(new ReferenceLink(securedObject) { Href = href });
            }
            else
            {
                referenceLinks[name] = new ReferenceLink(securedObject) { Href = href };
            }
        }

19 View Source File : ResourceProperties.cs
License : MIT License
Project Creator : actions

public void UnionWith(
            ResourceProperties properties,
            Boolean overwrite = false)
        {
            if (properties?.m_items == null)
            {
                return;
            }

            foreach (var property in properties.m_items)
            {
                if (overwrite || !this.Items.ContainsKey(property.Key))
                {
                    this.Items[property.Key] = property.Value;
                }
            }
        }

19 View Source File : DacPropertyInfo.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static DacPropertyInfo Create(PXContext context, PropertyDeclarationSyntax node, IPropertySymbol property, int declarationOrder,
											 AttributeInformation attributesInformation, IDictionary<string, DacFieldInfo> dacFields,
											 DacPropertyInfo baseInfo = null)
		{
			context.ThrowOnNull(nameof(context));
			property.ThrowOnNull(nameof(property));
			attributesInformation.ThrowOnNull(nameof(attributesInformation));
			dacFields.ThrowOnNull(nameof(dacFields));

			bool isDacProperty = dacFields.ContainsKey(property.Name);
			var attributeInfos = GetAttributeInfos(property, attributesInformation);
			var effectivePropertyType = property.Type.GetUnderlyingTypeFromNullable(context) ?? property.Type;

			return baseInfo != null
				? new DacPropertyInfo(node, property, effectivePropertyType, declarationOrder, isDacProperty, attributeInfos, baseInfo)
				: new DacPropertyInfo(node, property, effectivePropertyType, declarationOrder, isDacProperty, attributeInfos);
		}

19 View Source File : GraphActionSymbolUtils.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static IEnumerable<(MethodDeclarationSyntax Node, IMethodSymbol Symbol)> GetRawActionHandlersFromGraphOrGraphExtension(
															this ITypeSymbol grapreplacedxtension, IDictionary<string, ActionInfo> actionsByName,
															PXContext pxContext, CancellationToken cancellation)
		{
			IEnumerable<IMethodSymbol> handlers = from method in grapreplacedxtension.GetMembers().OfType<IMethodSymbol>()
												  where method.IsValidActionHandler(pxContext) && actionsByName.ContainsKey(method.Name)
												  select method;

			foreach (IMethodSymbol handler in handlers)
			{
				cancellation.ThrowIfCancellationRequested();

				SyntaxReference reference = handler.DeclaringSyntaxReferences.FirstOrDefault();

				if (reference?.GetSyntax(cancellation) is MethodDeclarationSyntax declaration)
				{
					yield return (declaration, handler);
				}
			}
		}

19 View Source File : GraphViewSymbolUtils.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

private static IEnumerable<(MethodDeclarationSyntax Node, IMethodSymbol Symbol)> GetRawViewDelegatesFromGraphOrGraphExtension(
															this ITypeSymbol grapreplacedxtension, IDictionary<string, DataViewInfo> viewsByName,
															PXContext pxContext, CancellationToken cancellation)
		{
			IEnumerable<IMethodSymbol> delegates = from method in grapreplacedxtension.GetMembers().OfType<IMethodSymbol>()
												   where method.IsValidViewDelegate(pxContext) && viewsByName.ContainsKey(method.Name)
												   select method;

			foreach (IMethodSymbol d in delegates)
			{
				cancellation.ThrowIfCancellationRequested();

				SyntaxReference reference = d.DeclaringSyntaxReferences.FirstOrDefault();

				if (reference?.GetSyntax(cancellation) is MethodDeclarationSyntax declaration)
				{
					yield return (declaration, d);
				}
			}
		}

19 View Source File : DmnDefinitionFactory.cs
License : MIT License
Project Creator : 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 View Source File : DmnDefinitionFactory.cs
License : MIT License
Project Creator : 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 View Source File : DmnExecutionContext.cs
License : MIT License
Project Creator : adamecr

public DmnDecisionResult ExecuteDecision(string decisionName)
        {
            if (string.IsNullOrWhiteSpace(decisionName)) throw Logger.Fatal<ArgumentException>($"{nameof(decisionName)} is null or empty");
            if (!Decisions.ContainsKey(decisionName)) throw Logger.Fatal<DmnExecutorException>($"ExecuteDecision: - decision {decisionName} not found");

            var decision = Decisions[decisionName];
            return ExecuteDecision(decision);
        }

19 View Source File : DmnExecutionContext.cs
License : MIT License
Project Creator : adamecr

public DmnExecutionVariable GetVariable(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
                throw Logger.Fatal<ArgumentException>($"{nameof(name)} is null or empty");

            if (!Variables.ContainsKey(name))
            {
                throw Logger.Fatal<DmnExecutorException>($"GetVariable: - variable {name} not found");
            }

            return Variables[name];
        }

19 View Source File : ServerApi.cs
License : MIT License
Project Creator : adamped

public static bool IsPropertyExist(dynamic settings, string name)
		{
			if (settings is ExpandoObject)
				return ((IDictionary<string, object>)settings).ContainsKey(name);

			return settings.GetType().GetProperty(name) != null;
		}

19 View Source File : POGenerator.cs
License : MIT License
Project Creator : adams85

private IPOEntry CreateHeaderEntry()
        {
            IDictionary<string, string> headers;
            if (!HasFlags(Flags.SkipInfoHeaders) && _catalog.Headers != null)
            {
#if USE_COMMON
                if (HasFlags(Flags.PreserveHeadersOrder))
                    headers = new OrderedDictionary<string, string>(_catalog.Headers, StringComparer.OrdinalIgnoreCase);
                else
#endif
                headers = new Dictionary<string, string>(_catalog.Headers, StringComparer.OrdinalIgnoreCase);
            }
            else
                headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            if (_catalog.Encoding != null)
            {
                if (!headers.ContainsKey("Content-Transfer-Encoding"))
                    headers["Content-Transfer-Encoding"] = "8bit";

                headers["Content-Type"] = $"text/plain; charset={_catalog.Encoding}";
            }

            if (_catalog.Language != null)
                headers["Language"] = _catalog.Language;

            if (_catalog.PluralFormCount > 0 && _catalog.PluralFormSelector != null)
                headers["Plural-Forms"] = $"nplurals={_catalog.PluralFormCount.ToString(CultureInfo.InvariantCulture)}; plural={_catalog.PluralFormSelector};";

            IEnumerable<KeyValuePair<string, string>> orderedHeaders;
#if USE_COMMON
            if (headers is IOrderedDictionary<string, string>)
                orderedHeaders = headers.AsEnumerable();
            else
#endif
            orderedHeaders = headers.OrderBy(kvp => kvp.Key);

            var value =
                headers.Count > 0 ?
                string.Join("\n", orderedHeaders.Select(kvp => kvp.Key + ": " + kvp.Value).Append(string.Empty)) :
                string.Empty;

            return new POSingularEntry(new POKey(string.Empty))
            {
                Translation = value,
                Comments = _catalog.HeaderComments
            };
        }

19 View Source File : Avatar.razor.cs
License : MIT License
Project Creator : ADefWebserver

public async ValueTask RunAnimation(string name)
        {
            if (_runningAnimation != null)
            {
                await _runningAnimation.stop();
                _runningAnimation = null;
            }

            if (_animationMap.ContainsKey(name))
            {
                await _animationMap[name].play(true);
                _runningAnimation = _animationMap[name];
            }
        }

19 View Source File : EntityDefinition.cs
License : MIT License
Project Creator : Adoxio

public IEnumerable<RelationshipDefinition> GetFilteredRelationships(IDictionary<string, SolutionInfo> crmSolutions)
		{
			List<RelationshipDefinition> filteredRelationships = new List<RelationshipDefinition>();

			if (this.Relationships != null)
			{
				foreach (var relationship in this.Relationships)
				{
					// If solution name is missing in Relationship definition or CRM is missing this solution, do the filtering based on MicrosoftCrmPortalBase solution version.
					var solutionVersion = !string.IsNullOrEmpty(relationship.Solution) && crmSolutions.ContainsKey(relationship.Solution)
						? crmSolutions[relationship.Solution].SolutionVersion
						: crmSolutions["MicrosoftCrmPortalBase"].SolutionVersion;
					

					if (relationship.IntroducedVersion != null)
					{
						var relationshipVersion = relationship.IntroducedVersion;
						if (relationshipVersion.Major <= solutionVersion.Major && relationshipVersion.Minor <= solutionVersion.Minor)
						{
							filteredRelationships.Add(relationship);
						}
					}
					else
					{
						filteredRelationships.Add(relationship);
					}
				}
			}
			return filteredRelationships;
		}

19 View Source File : QueryBuilder.cs
License : MIT License
Project Creator : Adoxio

public override Fetch CreateQuery(EnreplacedyDefinition ed, IDictionary<string, object> parameters)
		{
			// the input links are appended to the query to filter the set of enreplacedies

			if (!parameters.ContainsKey("Links")) return null;

			var links = parameters["Links"] as ICollection<Link>;

			if (links == null) return null;

			var fetch = ed.CreateFetchExpression();

			if (Links != null && Links.Any())
			{
				// append the input links to the specified intermediate links

				var chains = Links.Clone();

				SetParameters(chains, links);

				fetch.Enreplacedy.Links = chains;
			}
			else
			{
				// replacedign the input links directly to the fetch

				fetch.Enreplacedy.Links = links;
			}

			// skip cache for ContentMap
			fetch.SkipCache = true;

			return fetch;
		}

19 View Source File : SolutionDefinition.cs
License : MIT License
Project Creator : Adoxio

public Dictionary<string, EnreplacedyDefinition> GetFilteredEnreplacedies(IDictionary<string, SolutionInfo> crmSolutions)
		{
			Dictionary<string, EnreplacedyDefinition> filteredEnreplacedies = new Dictionary<string, EnreplacedyDefinition>();
			foreach (var enreplacedy in this.Enreplacedies)
			{
				// If solution name is missing in enreplacedy definition or CRM is missing this solution, do the filtering based on MicrosoftCrmPortalBase solution version.
				var solutionVersion = !string.IsNullOrEmpty(enreplacedy.Value.Solution) && crmSolutions.ContainsKey(enreplacedy.Value.Solution)
						? crmSolutions[enreplacedy.Value.Solution].SolutionVersion
						: crmSolutions["MicrosoftCrmPortalBase"].SolutionVersion;

				if (enreplacedy.Value.IntroducedVersion != null)
				{
					var enreplacedyVersion = enreplacedy.Value.IntroducedVersion;
					if (enreplacedyVersion.Major <= solutionVersion.Major && enreplacedyVersion.Minor <= solutionVersion.Minor)
					{
						filteredEnreplacedies.Add(enreplacedy.Key, GetFilteredEnreplacedy(enreplacedy.Value, solutionVersion, crmSolutions));
					}
				}
				else
				{
					filteredEnreplacedies.Add(enreplacedy.Key, GetFilteredEnreplacedy(enreplacedy.Value, solutionVersion, crmSolutions));
				}
			}
			return filteredEnreplacedies;
		}

19 View Source File : EntityListODataPathRouteContstraint.cs
License : MIT License
Project Creator : Adoxio

public override bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
		{
			if (request == null)
				throw new ArgumentNullException("request");
			if (values == null)
				throw new ArgumentNullException("values");
			if (routeDirection != HttpRouteDirection.UriResolution)
				return true;
			object obj;
			if (values.TryGetValue(ODataRouteConstants.ODataPath, out obj))
			{
				var enreplacedylistODataFeedDataAdapter = new EnreplacedyListODataFeedDataAdapter(new PortalConfigurationDataAdapterDependencies());
				EdmModel = enreplacedylistODataFeedDataAdapter.GetEdmModel();
				
				string odataPath1 = obj as string ?? string.Empty;
				ODataPath odataPath2;
				try
				{
					odataPath2 = PathHandler.Parse(EdmModel, odataPath1);
				}
				catch (ODataException ex)
				{
					throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, "The OData path is invalid.", ex));
				}
				if (odataPath2 != null)
				{
					var odataProperties = request.ODataProperties();
					odataProperties.Model = EdmModel;
					odataProperties.PathHandler = PathHandler;
					odataProperties.Path = odataPath2;
					odataProperties.RouteName = RouteName;
					odataProperties.RoutingConventions = RoutingConventions;
					if (!values.ContainsKey(ODataRouteConstants.Controller))
					{
						string str = SelectControllerName(odataPath2, request);
						if (str != null)
							values[ODataRouteConstants.Controller] = str;
					}
					return true;
				}
			}
			return false;
		}

19 View Source File : CmsEntityEditingMetadataProvider.cs
License : MIT License
Project Creator : Adoxio

private static bool EnreplacedyNameExistsInSchema(string enreplacedyLogicalName, IDictionary<string, EnreplacedyMetadata> allEnreplacedies)
		{
			return allEnreplacedies.ContainsKey(enreplacedyLogicalName);
		}

19 View Source File : FederationAuthenticationHandler.cs
License : MIT License
Project Creator : Adoxio

public virtual bool TryHandleSignInResponse(HttpContext context, WSFederationAuthenticationModule fam, IDictionary<string, string> signInContext)
		{
			string resultCode = null;
			string idenreplacedyProvider, userName, email, displayName;
			var sessionSecurityToken = GetSessionSecurityToken(context, fam, signInContext, out idenreplacedyProvider, out userName, out email, out displayName);

			using (var serviceContext = CreateServiceContext(context, fam, signInContext))
			{
				// check if the user already exists

				var existingContact = FindContactByUserName(
					context,
					fam,
					signInContext,
					serviceContext,
					idenreplacedyProvider,
					userName);

				TraceInformation("TryHandleSignInResponse", "existingContact={0}", existingContact);

				if (existingContact == null)
				{
					// begin registration process if it is enabled

					if (!RegistrationSettings.Enabled) return true;

					// check if this is a Live ID account transfer

					if (signInContext.ContainsKey(LiveIdTokenKey))
					{
						return TryTransferFromLiveId(
							context,
							fam,
							signInContext,
							serviceContext,
							sessionSecurityToken,
							idenreplacedyProvider,
							userName,
							email,
							displayName);
					}

					if (TryRegisterNewContact(
						context,
						fam,
						signInContext,
						serviceContext,
						sessionSecurityToken,
						idenreplacedyProvider,
						userName,
						email,
						displayName))
					{
						return true;
					}
				}
				else
				{
					var logonEnabled = existingContact.GetAttributeValue<bool>(AttributeMapLogonEnabled);

					TraceInformation("TryHandleSignInResponse", "logonEnabled={0}", logonEnabled);

					if (logonEnabled)
					{
						// successfully found an existing contact

						if (TryAuthenticateExistingContact(context, fam, signInContext, serviceContext, idenreplacedyProvider, userName, existingContact, sessionSecurityToken))
						{
							return true;
						}
					}
					else
					{
						resultCode = _inactive;
					}

					if (!RegistrationSettings.Enabled) return true;

					if (TryRegisterExistingContact(
						context,
						fam,
						signInContext,
						serviceContext,
						sessionSecurityToken,
						idenreplacedyProvider,
						userName,
						email,
						displayName,
						existingContact))
					{
						return true;
					}
				}

				// invalid user account

				if (TryHandleUnregisteredUser(
					context,
					fam,
					signInContext,
					serviceContext,
					sessionSecurityToken,
					idenreplacedyProvider,
					userName,
					email,
					displayName,
					resultCode))
				{
					return true;
				}
			}

			return false;
		}

19 View Source File : FederationAuthenticationHandler.cs
License : MIT License
Project Creator : Adoxio

protected virtual Enreplacedy CreateNewConfirmationContact(
			HttpContext context,
			WSFederationAuthenticationModule fam,
			IDictionary<string, string> signInContext,
			OrganizationServiceContext serviceContext,
			string idenreplacedyProvider,
			string userName,
			string email,
			string displayName)
		{
			// verify that an email address is provided in the signInContext

			if (!signInContext.ContainsKey(AttributeMapEmail))
			{
				return null;
			}

			var invitationCode = Guid.NewGuid().ToString().Replace("-", string.Empty).ToUpper();
			var now = DateTime.UtcNow.Floor(RoundTo.Second);
			var invitationCodeExpiryDate = RegistrationSettings.InvitationCodeDuration != null
				? now + RegistrationSettings.InvitationCodeDuration
				: null;

			return CreateNewConfirmationContact(context, fam, signInContext, serviceContext, idenreplacedyProvider, userName, email, displayName, invitationCode, invitationCodeExpiryDate);
		}

19 View Source File : AssemblyComparer.cs
License : MIT License
Project Creator : adrianoc

private static bool CheckTypeMember<T>(IMemberDiffVisitor memberVisitor, IMemberDefinition sourceMember, TypeDefinition target, IDictionary<string, T> targetMembers) where T : IMemberDefinition
        {
            if (!targetMembers.ContainsKey(sourceMember.FullName))
            {
                return memberVisitor.VisitMissing(sourceMember, target);
            }

            var targetMember = targetMembers[sourceMember.FullName];
            if (sourceMember.FullName != targetMember.FullName)
            {
                if (!memberVisitor.VisitName(sourceMember, targetMember))
                {
                    return false;
                }
            }

            if (sourceMember.DeclaringType.FullName != targetMember.DeclaringType.FullName)
            {
                if (!memberVisitor.VisitDeclaringType(sourceMember, target))
                {
                    return false;
                }
            }

            return true;
        }

19 View Source File : MimeMappingProvider.cs
License : GNU General Public License v3.0
Project Creator : aduskin

public bool TryGetMimeMapping(string filename,out string mimeMapping)
        {
            var extension = Path.GetExtension(filename);
            if (MimeMaps.ContainsKey(extension))
            {
                mimeMapping = MimeMaps[extension];
                return true;
            }
            mimeMapping = FallbackMime;
            return false;
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public void Edit<T>(IreplacedetData replacedet)
        {
            Monitor.Log("Editing replacedet " + replacedet.replacedetName);
            if (replacedet.replacedetNameEquals("Data/Events/HaleyHouse"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;

                data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"] = Regex.Replace(data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 3", "");
                data["choseToExplain"] = Regex.Replace(data["choseToExplain"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
                data["lifestyleChoice"] = Regex.Replace(data["lifestyleChoice"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
            }
            else if (replacedet.replacedetNameEquals("Data/Events/Saloon"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;

                string aData = data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"];
                data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 3", "");
                aData = data["choseToExplain"];
                data["choseToExplain"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"", $"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
                aData = data["crying"];
                data["crying"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
            }
            else if (replacedet.replacedetNameEquals("Strings/StringsFromCSFiles"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                data["NPC.cs.3985"] = Regex.Replace(data["NPC.cs.3985"],  @"\.\.\.\$s.+", $"$n#$b#$c 0.5#{data["ResourceCollectionQuest.cs.13681"]}#{data["ResourceCollectionQuest.cs.13683"]}");
                Monitor.Log($"NPC.cs.3985 is set to \"{data["NPC.cs.3985"]}\"");
            }
            else if (replacedet.replacedetNameEquals("Data/animationDescriptions"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                List<string> sleepKeys = data.Keys.ToList().FindAll((s) => s.EndsWith("_Sleep"));
                foreach(string key in sleepKeys)
                {
                    if (!data.ContainsKey(key.ToLower()))
                    {
                        Monitor.Log($"adding {key.ToLower()} to animationDescriptions");
                        data.Add(key.ToLower(), data[key]);
                    }
                }
            }
            else if (replacedet.replacedetNameEquals("Data/EngagementDialogue"))
            {
                if (!config.RomanceAllVillagers)
                    return;
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                Farmer f = Game1.player;
                if (f == null)
                {
                    return;
                }
                foreach (string friend in f.friendshipData.Keys)
                {
                    if (!data.ContainsKey(friend+"0"))
                    {
                        data[friend + "0"] = "";
                    }
                    if (!data.ContainsKey(friend+"1"))
                    {
                        data[friend + "1"] = "";
                    }
                }
            }
            else if (replacedet.replacedetName.StartsWith("Characters/schedules") || replacedet.replacedetName.StartsWith("Characters\\schedules"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                List<string> keys = new List<string>(data.Keys);
                foreach (string key in keys)
                {
                    if(!data.ContainsKey($"marriage_{key}"))
                        data[$"marriage_{key}"] = data[key]; 
                }
            }
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public void Edit<T>(IreplacedetData replacedet)
        {
            Monitor.Log("Editing replacedet " + replacedet.replacedetName);
            if (replacedet.replacedetNameEquals("Data/Events/HaleyHouse"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;

                data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"] = Regex.Replace(data["195012/f Haley 2500/f Emily 2500/f Penny 2500/f Abigail 2500/f Leah 2500/f Maru 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 38/e 2123343/e 10/e 901756/e 54/e 15/k 195019"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 3", "");
                data["choseToExplain"] = Regex.Replace(data["choseToExplain"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
                data["lifestyleChoice"] = Regex.Replace(data["lifestyleChoice"], "(pause 1000/speak Maru \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-female")}$h\"/emote Haley 21 true/emote Emily 21 true/emote Penny 21 true/emote Maru 21 true/emote Leah 21 true/emote Abigail 21").Replace("/dump girls 4", "");
            }
            else if (replacedet.replacedetNameEquals("Data/Events/Saloon"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;

                string aData = data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"];
                data["195013/f Shane 2500/f Sebastian 2500/f Sam 2500/f Harvey 2500/f Alex 2500/f Elliott 2500/o Abigail/o Penny/o Leah/o Emily/o Maru/o Haley/o Shane/o Harvey/o Sebastian/o Sam/o Elliott/o Alex/e 911526/e 528052/e 9581348/e 43/e 384882/e 233104/k 195099"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 3", "");
                aData = data["choseToExplain"];
                data["choseToExplain"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"", $"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
                aData = data["crying"];
                data["crying"] = Regex.Replace(aData, "(pause 1000/speak Sam \\\")[^$]+.a\\\"",$"$1{PHelper.Translation.Get("confrontation-male")}$h\"/emote Shane 21 true/emote Sebastian 21 true/emote Sam 21 true/emote Harvey 21 true/emote Alex 21 true/emote Elliott 21").Replace("/dump guys 4", "");
            }
            else if (replacedet.replacedetNameEquals("Strings/StringsFromCSFiles"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                data["NPC.cs.3985"] = Regex.Replace(data["NPC.cs.3985"],  @"\.\.\.\$s.+", $"$n#$b#$c 0.5#{data["ResourceCollectionQuest.cs.13681"]}#{data["ResourceCollectionQuest.cs.13683"]}");
                Monitor.Log($"NPC.cs.3985 is set to \"{data["NPC.cs.3985"]}\"");
            }
            else if (replacedet.replacedetNameEquals("Data/animationDescriptions"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                List<string> sleepKeys = data.Keys.ToList().FindAll((s) => s.EndsWith("_Sleep"));
                foreach(string key in sleepKeys)
                {
                    if (!data.ContainsKey(key.ToLower()))
                    {
                        Monitor.Log($"adding {key.ToLower()} to animationDescriptions");
                        data.Add(key.ToLower(), data[key]);
                    }
                }
            }
            else if (replacedet.replacedetNameEquals("Data/EngagementDialogue"))
            {
                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                if (!config.RomanceAllVillagers)
                    return;
                Farmer f = Game1.player;
                if (f == null)
                {
                    return;
                }
                foreach (string friend in f.friendshipData.Keys)
                {
                    if (!data.ContainsKey(friend+"0"))
                    {
                        data[friend + "0"] = "";
                    }
                    if (!data.ContainsKey(friend+"1"))
                    {
                        data[friend + "1"] = "";
                    }
                }
            }
            else if (replacedet.replacedetName.StartsWith("Characters/schedules") || replacedet.replacedetName.StartsWith("Characters\\schedules"))
            {


                IDictionary<string, string> data = replacedet.AsDictionary<string, string>().Data;
                List<string> keys = new List<string>(data.Keys);
                foreach (string key in keys)
                {
                    if(!data.ContainsKey($"marriage_{key}"))
                        data[$"marriage_{key}"] = data[key]; 
                }
            }
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static string GetSocialNetworkString(string name, string key, bool npcSpecific)
        {
            IDictionary<string, string> data;
            try
            {
                if (npcSpecific)
                {
                    if (npcStrings.ContainsKey(name) && npcStrings[name].ContainsKey(key))
                        return npcStrings[name][key];
                    data = Helper.Content.Load<Dictionary<string, string>>($"Characters\\Dialogue\\{name}", ContentSource.GameContent);
                    if (data.ContainsKey(key))
                    {
                        string str = data[key];
                        if (!npcStrings.ContainsKey(name))
                            npcStrings.Add(name, new Dictionary<string, string>() { { key, str } });
                        else
                            npcStrings[name].Add(key, str);
                        return str;
                    }
                    else
                        return null;
                }
                else
                {
                    if (socialNetworkStrings.ContainsKey(key))
                        return socialNetworkStrings[key];
                    data = Helper.Content.Load<Dictionary<string, string>>($"SocialNetworkStrings", ContentSource.GameContent);
                    string str = data[key];
                    socialNetworkStrings.Add(key, str);
                    return str;
                }
            }
            catch
            {
                return null;
            }
        }

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static int AddPosts(string[] postKeys)
        {
            int posts = 0; 
            foreach (KeyValuePair<string, Netcode.NetRef<Friendship>> kvp in Game1.player.friendshipData.FieldDict)
            {
                IDictionary<string, string> data;
                try
                {
                    data = Helper.Content.Load<Dictionary<string, string>>($"Characters\\Dialogue\\{kvp.Key}", ContentSource.GameContent);
                }
                catch
                {
                    continue;
                }

                if (data == null)
                    continue;

                foreach(string postKey in postKeys)
                {
                    if (data.ContainsKey(postKey))
                    {
                        NPC npc = Game1.getCharacterFromName(kvp.Key);
                        Texture2D portrait = npc.Sprite.Texture;
                        Rectangle sourceRect = npc.getMugShotSourceRect();
                        ModEntry.postList.Add(new SocialPost(npc, portrait, sourceRect, data[postKey]));
                        Monitor.Log($"added {postKey} post from {npc.displayName}");
                        posts++;
                    }
                }
            }
            return posts;
        }

19 View Source File : Track.cs
License : MIT License
Project Creator : Aeroluna

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

19 View Source File : Track.cs
License : MIT License
Project Creator : 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 View Source File : CollectionEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static string SafeAdd<TV>(this IDictionary<string, TV> dictionary, string k, TV v)
        {
            if (k == null)
                return null;
            var name = k;
            var idx = 1;
            while (dictionary.ContainsKey(name))
            {
                name = $"{k}{idx++}";
            }
            dictionary.Add(name, v);
            return name;
        }

19 View Source File : CollectionEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void AddOnce<TValue>(this IDictionary<string, TValue> dictionary, string key, TValue value)
        {
            if (!dictionary.ContainsKey(key))
            {
                dictionary.Add(key, value);
            }
        }

19 View Source File : CollectionEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void AddOrSwitch<TValue>(this IDictionary<string, TValue> dictionary, string key, TValue value)
        {
            if (!dictionary.ContainsKey(key))
            {
                dictionary.Add(key, value);
            }
            else
            {
                dictionary[key] = value;
            }
        }

19 View Source File : CollectionEx.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static void OnlyAdd<TValue>(this IDictionary<string, TValue> dictionary, string key, TValue value)
        {
            if (dictionary == null)
            {
                return;
            }
            if (!dictionary.ContainsKey(key))
            {
                dictionary.Add(key, value);
            }
        }

19 View Source File : Elements.cs
License : MIT License
Project Creator : agens-no

public bool Contains(string key)
        {
            return values.ContainsKey(key);
        }

19 View Source File : JsonParser.cs
License : MIT License
Project Creator : agens-no

public bool Contains(string key)
        {
            return this.values.ContainsKey(key);
        }

19 View Source File : AtomJobHistoryRenderer.cs
License : MIT License
Project Creator : ahydrax

public static NonEscapedString AtomRender(HtmlHelper helper, IDictionary<string, string> stateData)
        {
            var builder = new StringBuilder();

            if (stateData.ContainsKey(nameof(AtomCreatedState.AtomId)))
            {
                var atomId = stateData[nameof(AtomCreatedState.AtomId)];
                builder.Append("<dl clreplaced=\"dl-horizontal\">");
                builder.Append("<dt>Atom details:</dt>");
                builder.Append($"<dd>{helper.AtomLink(atomId)}</dd>");
                builder.Append("</dl>");
            }

            if (stateData.ContainsKey(nameof(SubAtomCreatedState.ContinuationOptions)))
            {
                var continuationOption = stateData[nameof(SubAtomCreatedState.ContinuationOptions)];
                builder.Append("<dl clreplaced=\"dl-horizontal\">");
                builder.Append("<dt>Atom progress:</dt>");
                builder.Append($"<dd><code>{continuationOption}</code></dd>");
                builder.Append("</dl>");
            }

            if (stateData.ContainsKey(nameof(SubAtomCreatedState.NextState)))
            {
                var state = JsonUtils.Deserialize<IState>(stateData[nameof(SubAtomCreatedState.NextState)]);
                builder.Append("<dl clreplaced=\"dl-horizontal\">");
                builder.Append("<dt>Next state:</dt>");

                var stateColor = JobHistoryRenderer.GetForegroundStateColor(state.Name);
                builder.Append($"<dd><span clreplaced=\"label label-default\" style=\"background-color: {stateColor};\">{state.Name}</span></dd>");
                builder.Append("</dl>");
            }

            return new NonEscapedString(builder.ToString());
        }

19 View Source File : ConfigurationBase.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void SetConfigurations(IDictionary<string, object> dic)
		{
			try
			{
				lock (_root)
				{
					FieldInfo[] fields = this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public);
					foreach (var f in fields)
					{
						if (dic.ContainsKey(f.Name))
						{
							var val = DataConverter.ChangeType(dic[f.Name], f.FieldType);
							f.SetValue(this, val);
						}
					}
					PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
					foreach (var p in props)
					{
						if (dic.ContainsKey(p.Name))
						{
							var val = DataConverter.ChangeType(dic[p.Name], p.PropertyType);
							p.SetValue(this, val, null);
						}
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 View Source File : ConfigurationBase.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void SetConfigurations(IDictionary<string, object> dic)
		{
			try
			{
				BindingFlags flag = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | 
					BindingFlags.SetField | BindingFlags.SetProperty;
				lock (_root)
				{
					FieldInfo[] fields = this.GetType().GetFields(flag);
					foreach (var f in fields)
					{
						if (f.IsPrivate || f.IsInitOnly)
							continue;
						if (dic.ContainsKey(f.Name))
						{
							var val = DataConverter.ChangeType(dic[f.Name], f.FieldType);
							f.SetValue(this, val);
						}
					}
					PropertyInfo[] props = this.GetType().GetProperties(flag);
					foreach (var p in props)
					{
						if (dic.ContainsKey(p.Name))
						{
							var val = DataConverter.ChangeType(dic[p.Name], p.PropertyType);
							p.SetValue(this, val, null);
						}
					}
				}
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 View Source File : DataConverter.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static T Convert<T>(IDictionary<string, object> vals, object obj, bool hasInternal)
		{
			if (obj == null)
				obj = System.Activator.CreateInstance<T>();
			Debug.replacedert(obj is T);
			return (T)StructFromValues(obj, (k) => vals.ContainsKey(k) ? vals[k] : null, true, hasInternal);
		}

See More Examples