System.Collections.Generic.HashSet.Contains(string)

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

3461 Examples 7

19 Source : Watchdog.cs
with MIT License
from 0ffffffffh

private bool IsWatchableProcess(Process proc)
        {
            return watchList.Contains(proc.ProcessName.ToLower());
        }

19 Source : CacheManager.cs
with MIT License
from 0ffffffffh

internal static bool AddKey(KeysetId setId, string key)
        {
            CacheKeySetContext cskc;
            HashSet<string> set;
            
            cskc = GetKeysetContext(setId);

            if (!CacheManager.TryGetCachedResult<HashSet<string>>(cskc.CacheSetKey,out set))
            {
                set = new HashSet<string>();
                set.Add(key);
                CacheManager.CacheObject(cskc.CacheSetKey, set);
            }
            else
            {
                lock (cskc.lck)
                {
                    if (setId.ValidateKeys)
                        CheckSetKeys(set);

                    if (!set.Contains(key))
                        set.Add(key);
                }

                CacheManager.CacheObject(cskc.CacheSetKey, set);
            }

            return true;
        }

19 Source : EdisFace.cs
with MIT License
from 0ffffffffh

private void CacheDeniedClient(string clientIp)
        {
            string key = Edi.MakeUniqueCacheKey("EDI_DENYLIST");

            HashSet<string> denyHashlist = null;

            lock (lck)
            {
                if (!CacheManager.TryGetCachedResult<HashSet<string>>(
                    key,
                    out denyHashlist)
                    )
                {
                    denyHashlist = new HashSet<string>();
                }


                if (!denyHashlist.Contains(clientIp))
                {
                    denyHashlist.Add(clientIp);
                    CacheManager.CacheObject(key, denyHashlist,TimeSpan.FromHours(3));
                }
            }

            denyHashlist.Clear();
            denyHashlist = null;
        }

19 Source : EdisFace.cs
with MIT License
from 0ffffffffh

private bool IsClientDeniedAtThisSessionBefore(string clientIp)
        {
            bool denied = false;
            string key = Edi.MakeUniqueCacheKey("EDI_DENYLIST");

            HashSet<string> denyHashlist = null;

            lock (lck)
            {
                if (!CacheManager.TryGetCachedResult<HashSet<string>>(
                    key,
                    out denyHashlist)
                    )
                {
                    return false;
                }
            }

            denied = denyHashlist.Contains(clientIp);

            denyHashlist.Clear();
            denyHashlist = null;

            return denied;
        }

19 Source : StringMap.cs
with MIT License
from 0x0ade

public void CountRead(string value) {
            if (value.Length <= MinLength)
                return;

            lock (Pending) {
                if (MappedRead.Contains(value) || Pending.Contains(value))
                    return;

                if (!Counting.TryGetValue(value, out int count))
                    count = 0;
                if (++count >= PromotionCount) {
                    Counting.Remove(value);
                    Pending.Add(value);
                } else {
                    Counting[value] = count;
                }

                if (Counting.Count >= MaxCounting)
                    Cleanup();
            }
        }

19 Source : Frontend.cs
with MIT License
from 0x0ade

public bool IsAuthorized(HttpRequestEventArgs c)
            => c.Request.Cookies[COOKIE_SESSION]?.Value is string session && CurrentSessionKeys.Contains(session);

19 Source : ModelClassGenerator.cs
with MIT License
from 0x1000000

private static ClreplacedDeclarationSyntax GenerateClreplaced(SqModelMeta meta, bool rwClreplacedes, ClreplacedDeclarationSyntax? existingClreplaced)
        {
            ClreplacedDeclarationSyntax result;
            MemberDeclarationSyntax[]? oldMembers = null;
            Dictionary<string,SyntaxList<AttributeListSyntax>>? oldAttributes = null;
            if (existingClreplaced != null)
            {
                result = existingClreplaced;

                oldMembers = result.Members
                    .Where(md =>
                    {
                        if (md is ConstructorDeclarationSyntax)
                        {
                            return false;
                        }

                        if (md is IncompleteMemberSyntax)
                        {
                            return false;
                        }

                        if (md is PropertyDeclarationSyntax p)
                        {
                            if (meta.Properties.Any(mp => mp.Name == p.Identifier.ValueText))
                            {
                                if (p.AttributeLists.Count > 0)
                                {
                                    oldAttributes ??= new Dictionary<string, SyntaxList<AttributeListSyntax>>();
                                    oldAttributes.Add(p.Identifier.ValueText, p.AttributeLists);
                                }
                                return false;
                            }
                        }

                        if (md is MethodDeclarationSyntax method)
                        {
                            var name = method.Identifier.ValueText;

                            if (name.StartsWith("With") || AllMethods.Contains(name) || name.StartsWith(MethodNameGetReader + "For") || name.StartsWith(MethodNameGetUpdater + "For"))
                            {
                                return false;
                            }
                        }

                        if (md is ClreplacedDeclarationSyntax clreplacedDeclaration)
                        {
                            var name = clreplacedDeclaration.Identifier.ValueText;

                            if (name == meta.Name + ReaderClreplacedSuffix || name.StartsWith(meta.Name + ReaderClreplacedSuffix + "For"))
                            {
                                return false;
                            }
                            if (name == meta.Name + UpdaterClreplacedSuffix || name.StartsWith(meta.Name + UpdaterClreplacedSuffix + "For"))
                            {
                                return false;
                            }
                        }

                        return true;
                    })
                    .ToArray();

                result = result.RemoveNodes(result.DescendantNodes().OfType<MemberDeclarationSyntax>(), SyntaxRemoveOptions.KeepNoTrivia)!;

            }
            else
            {
                result = SyntaxFactory.ClreplacedDeclaration(meta.Name)
                    .WithModifiers(existingClreplaced?.Modifiers ?? Modifiers(SyntaxKind.PublicKeyword));
            }

            result = result
                .AddMembers(Constructors(meta)
                    .Concat(GenerateStaticFactory(meta))
                    .Concat(rwClreplacedes ? GenerateOrdinalStaticFactory(meta) : Array.Empty<MemberDeclarationSyntax>())
                    .Concat(Properties(meta, oldAttributes))
                    .Concat(GenerateWithModifiers(meta))
                    .Concat(GenerateGetColumns(meta))
                    .Concat(GenerateMapping(meta))
                    .Concat(rwClreplacedes ? GenerateReaderClreplaced(meta): Array.Empty<MemberDeclarationSyntax>())
                    .Concat(rwClreplacedes ? GenerateWriterClreplaced(meta) : Array.Empty<MemberDeclarationSyntax>())
                    .ToArray());

            if (oldMembers != null && oldMembers.Length > 0)
            {
                result = result.AddMembers(oldMembers);
            }

            return result;
        }

19 Source : XnaToFnaUtil.cs
with zlib License
from 0x0ade

public void ApplyCommonChanges(ModuleDefinition mod, string tag = "Relink") {
            if (DestroyPublicKeyTokens.Contains(mod.replacedembly.Name.Name)) {
                Log($"[{tag}] Destroying public key token for module {mod.replacedembly.Name.Name}");
                mod.replacedembly.Name.PublicKeyToken = new byte[0];
            }

            Log($"[{tag}] Updating dependencies");
            for (int i = 0; i < mod.replacedemblyReferences.Count; i++) {
                replacedemblyNameReference dep = mod.replacedemblyReferences[i];

                // Main mapping mreplaced.
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mapping.Sources.Contains(dep.Name) &&
                        // Check if the target module has been found and cached
                        Modder.DependencyCache.ContainsKey(mapping.Target)) {
                        // Check if module already depends on the remap
                        if (mod.replacedemblyReferences.Any(existingDep => existingDep.Name == mapping.Target)) {
                            // If so, just remove the dependency.
                            mod.replacedemblyReferences.RemoveAt(i);
                            i--;
                            goto NextDep;
                        }
                        Log($"[{tag}] Replacing dependency {dep.Name} -> {mapping.Target}");
                        // Replace the dependency.
                        mod.replacedemblyReferences[i] = Modder.DependencyCache[mapping.Target].replacedembly.Name;
                        // Only check until first match found.
                        goto NextDep;
                    }

                // Didn't remap; Check for RemoveDeps
                if (RemoveDeps.Contains(dep.Name)) {
                    // Remove any unwanted (f.e. mixed) dependencies.
                    Log($"[{tag}] Removing unwanted dependency {dep.Name}");
                    mod.replacedemblyReferences.RemoveAt(i);
                    i--;
                    goto NextDep;
                }

                // Didn't remove

                // Check for DestroyPublicKeyTokens
                if (DestroyPublicKeyTokens.Contains(dep.Name)) {
                    Log($"[{tag}] Destroying public key token for dependency {dep.Name}");
                    dep.PublicKeyToken = new byte[0];
                }

                // Check for ModulesToStub (formerly managed references)
                if (ModulesToStub.Any(stub => stub.replacedembly.Name.Name == dep.Name)) {
                    // Fix stubbed dependencies.
                    Log($"[{tag}] Fixing stubbed dependency {dep.Name}");
                    dep.IsWindowsRuntime = false;
                    dep.HasPublicKey = false;
                }

                // Check for .NET compact (X360) version
                if (dep.Version == DotNetX360Version) {
                    // Replace public key token.
                    dep.PublicKeyToken = DotNetFrameworkKeyToken;
                    // Technically .NET 2(?), but let's just bump the version.
                    dep.Version = DotNetFramework4Version;
                }

                NextDep:
                continue;
            }
            if (AddreplacedemblyReference && !mod.replacedemblyReferences.Any(dep => dep.Name == ThisreplacedemblyName)) {
                // Add XnaToFna as dependency
                Log($"[{tag}] Adding dependency XnaToFna");
                mod.replacedemblyReferences.Add(Modder.DependencyCache[ThisreplacedemblyName].replacedembly.Name);
            }

            if (mod.Runtime < TargetRuntime.Net_4_0) {
                // XNA 3.0 / 3.1 and X360 games depend on a .NET Framework pre-4.0
                mod.Runtime = TargetRuntime.Net_4_0;
                // TODO: What about the System.*.dll dependencies?
            }

            Log($"[{tag}] Updating module attributes");
            mod.Attributes &= ~ModuleAttributes.StrongNameSigned;
            if (PreferredPlatform != ILPlatform.Keep) {
                // "Clear" to AnyCPU.
                mod.Architecture = TargetArchitecture.I386;
                mod.Attributes &= ~ModuleAttributes.Required32Bit & ~ModuleAttributes.Preferred32Bit;

                switch (PreferredPlatform) {
                    case ILPlatform.x86:
                        mod.Architecture = TargetArchitecture.I386;
                        mod.Attributes |= ModuleAttributes.Required32Bit;
                        break;
                    case ILPlatform.x64:
                        mod.Architecture = TargetArchitecture.AMD64;
                        break;
                    case ILPlatform.x86Pref:
                        mod.Architecture = TargetArchitecture.I386;
                        mod.Attributes |= ModuleAttributes.Preferred32Bit;
                        break;
                }
            }

            bool mixed = (mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly;
            if (ModulesToStub.Count != 0 || mixed) {
                Log($"[{tag}] Making replacedembly unsafe");
                mod.Attributes |= ModuleAttributes.ILOnly;
                for (int i = 0; i < mod.replacedembly.CustomAttributes.Count; i++) {
                    CustomAttribute attrib = mod.replacedembly.CustomAttributes[i];
                    if (attrib.AttributeType.FullName == "System.CLSCompliantAttribute") {
                        mod.replacedembly.CustomAttributes.RemoveAt(i);
                        i--;
                    }
                }
                if (!mod.CustomAttributes.Any(ca => ca.AttributeType.FullName == "System.Security.UnverifiableCodeAttribute"))
                    mod.AddAttribute(mod.ImportReference(m_UnverifiableCodeAttribute_ctor));
            }

            // MonoMod needs to relink some types (f.e. XnaToFnaHelper) via FindType, which requires a dependency map.
            Log($"[{tag}] Mapping dependencies for MonoMod");
            Modder.MapDependencies(mod);
        }

19 Source : IrdProvider.cs
with MIT License
from 13xforever

public async Task<HashSet<DiscKeyInfo>> EnumerateAsync(string discKeyCachePath, string ProductCode, CancellationToken cancellationToken)
        {
            ProductCode = ProductCode?.ToUpperInvariant();
            var result = new HashSet<DiscKeyInfo>();
            var knownFilenames = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
            Log.Trace("Searching local cache for a match...");
            if (Directory.Exists(discKeyCachePath))
            {
                var matchingIrdFiles = Directory.GetFiles(discKeyCachePath, "*.ird", SearchOption.TopDirectoryOnly);
                foreach (var irdFile in matchingIrdFiles)
                {
                    try
                    {
                        try
                        {
                            var ird = IrdParser.Parse(File.ReadAllBytes(irdFile));
                            result.Add(new DiscKeyInfo(ird.Data1, null, irdFile, KeyType.Ird, ird.Crc32.ToString("x8")));
                            knownFilenames.Add(Path.GetFileName(irdFile));
                        }
                        catch (InvalidDataException)
                        {
                            File.Delete(irdFile);
                            continue;
                        }
                        catch (Exception e)
                        {
                            Log.Warn(e);
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        Log.Warn(e, e.Message);
                    }
                }
            }

            Log.Trace("Searching IRD Library for match...");
            var irdInfoList = await Client.SearchAsync(ProductCode, cancellationToken).ConfigureAwait(false);
            var irdList = irdInfoList?.Data?.Where(
                              i => !knownFilenames.Contains(i.Filename) && i.Filename.Substring(0, 9).ToUpperInvariant() == ProductCode
                          ).ToList() ?? new List<SearchResulreplacedem>(0);
            if (irdList.Count == 0)
                Log.Debug("No matching IRD file was found in the Library");
            else
            {
                Log.Info($"Found {irdList.Count} new match{(irdList.Count == 1 ? "" : "es")} in the IRD Library");
                foreach (var irdInfo in irdList)
                {
                    var ird = await Client.DownloadAsync(irdInfo, discKeyCachePath, cancellationToken).ConfigureAwait(false);
                    result.Add(new DiscKeyInfo(ird.Data1, null, Path.Combine(discKeyCachePath, irdInfo.Filename), KeyType.Ird, ird.Crc32.ToString("x8")));
                    knownFilenames.Add(irdInfo.Filename);
                }
            }
            if (knownFilenames.Count == 0)
            {
                Log.Warn("No valid matching IRD file could be found");
                Log.Info($"If you have matching IRD file, you can put it in '{discKeyCachePath}' and try dumping the disc again");
            }

            Log.Info($"Found {result.Count} IRD files");
            return result;
        }

19 Source : DotNetToJScript.cs
with MIT License
from 1y0n

public static string Generate()
        {
            try
            {
                /*
                if (Environment.Version.Major != 2)
                {
                    WriteError("This tool should only be run on v2 of the CLR");
                    Environment.Exit(1);
                }
                */

                string output_file = null;
                string entry_clreplaced_name = DEFAULT_ENTRY_CLreplaced_NAME;
                string additional_script = String.Empty;
                bool mscorlib_only = false;
                bool scriptlet_moniker = false;
                bool scriptlet_uninstall = false;
                bool enable_debug = false;
                RuntimeVersion version = RuntimeVersion.Auto;
                ScriptLanguage language = ScriptLanguage.JScript;
                Guid clsid = Guid.Empty;

                bool show_help = false;
                

                string replacedembly_path = Global_Var.dll_path;
                /*
                if (!File.Exists(replacedembly_path) || show_help)
                {
                    Console.Error.WriteLine(@"Usage: DotNetToJScript {0} [options] path\to\asm", VERSION);
                    Console.Error.WriteLine("Copyright (C) James Forshaw 2017. Licensed under GPLv3.");
                    Console.Error.WriteLine("Source code at https://github.com/tyranid/DotNetToJScript");
                    Console.Error.WriteLine("Options");
                    opts.WriteOptionDescriptions(Console.Error);
                    Environment.Exit(1);
                }
                */

                IScriptGenerator generator;
                switch (language)
                {
                    case ScriptLanguage.JScript:
                        generator = new JScriptGenerator();
                        break;
                    case ScriptLanguage.VBA:
                        generator = new VBAGenerator();
                        break;
                    case ScriptLanguage.VBScript:
                        generator = new VBScriptGenerator();
                        break;
                    default:
                        throw new ArgumentException("Invalid script language option");
                }

                byte[] replacedembly = File.ReadAllBytes(replacedembly_path);
                try
                {
                    HashSet<string> valid_clreplacedes = GetValidClreplacedes(replacedembly);
                    if (!valid_clreplacedes.Contains(entry_clreplaced_name))
                    {
                        WriteError("Error: Clreplaced '{0}' not found is replacedembly.", entry_clreplaced_name);
                        if (valid_clreplacedes.Count == 0)
                        {
                            WriteError("Error: replacedembly doesn't contain any public, default constructable clreplacedes");
                        }
                        else
                        {
                            WriteError("Use one of the follow options to specify a valid clreplacedes");
                            foreach (string name in valid_clreplacedes)
                            {
                                WriteError("-c {0}", name);
                            }
                        }
                        Environment.Exit(1);
                    }
                }
                catch (Exception)
                {
                    WriteError("Error: loading replacedembly information.");
                    WriteError("The generated script might not work correctly");
                }

                BinaryFormatter fmt = new BinaryFormatter();
                MemoryStream stm = new MemoryStream();
                fmt.Serialize(stm, mscorlib_only ? BuildLoaderDelegateMscorlib(replacedembly) : BuildLoaderDelegate(replacedembly));

                string script = generator.GenerateScript(stm.ToArray(), entry_clreplaced_name, additional_script, version, enable_debug);
                if (scriptlet_moniker || scriptlet_uninstall)
                {
                    if (!generator.SupportsScriptlet)
                    {
                        throw new ArgumentException(String.Format("{0} generator does not support Scriptlet output", generator.ScriptName));
                    }
                    script = CreateScriptlet(script, generator.ScriptName, scriptlet_uninstall, clsid);
                }

                /*
                if (!String.IsNullOrEmpty(output_file))
                {
                    File.WriteAllText(output_file, script, new UTF8Encoding(false));
                }
                else
                {
                    Console.WriteLine(script);
                }
                */
                return script;
            }
            catch (Exception ex)
            {
                ReflectionTypeLoadException tex = ex as ReflectionTypeLoadException;
                if (tex != null)
                {
                    WriteError("Couldn't load replacedembly file");
                    foreach (var e in tex.LoaderExceptions)
                    {
                        WriteError(e.Message);
                    }
                }
                else
                {
                    WriteError(ex.Message);
                }
                return null;
            }
        }

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

public bool Run(bool skipConnVerification)
        {
            var hostConnStr = CensorConnectionString(_connectionStringResolver.GetNameOrConnectionString(new ConnectionStringResolveArgs(MulreplacedenancySides.Host)));
            if (hostConnStr.IsNullOrWhiteSpace())
            {
                _log.Write("Configuration file should contain a connection string named 'Default'");
                return false;
            }

            _log.Write("Host database: " + ConnectionStringHelper.GetConnectionString(hostConnStr));
            if (!skipConnVerification)
            {
                _log.Write("Continue to migration for this host database and all tenants..? (Y/N): ");
                var command = Console.ReadLine();
                if (!command.IsIn("Y", "y"))
                {
                    _log.Write("Migration canceled.");
                    return false;
                }
            }

            _log.Write("HOST database migration started...");

            try
            {
                _migrator.CreateOrMigrateForHost(SeedHelper.SeedHostDb);
            }
            catch (Exception ex)
            {
                _log.Write("An error occured during migration of host database:");
                _log.Write(ex.ToString());
                _log.Write("Canceled migrations.");
                return false;
            }

            _log.Write("HOST database migration completed.");
            _log.Write("--------------------------------------------------------");

            var migratedDatabases = new HashSet<string>();
            var tenants = _tenantRepository.GetAllList(t => t.ConnectionString != null && t.ConnectionString != "");
            for (var i = 0; i < tenants.Count; i++)
            {
                var tenant = tenants[i];
                _log.Write(string.Format("Tenant database migration started... ({0} / {1})", (i + 1), tenants.Count));
                _log.Write("Name              : " + tenant.Name);
                _log.Write("TenancyName       : " + tenant.TenancyName);
                _log.Write("Tenant Id         : " + tenant.Id);
                _log.Write("Connection string : " + SimpleStringCipher.Instance.Decrypt(tenant.ConnectionString));

                if (!migratedDatabases.Contains(tenant.ConnectionString))
                {
                    try
                    {
                        _migrator.CreateOrMigrateForTenant(tenant);
                    }
                    catch (Exception ex)
                    {
                        _log.Write("An error occured during migration of tenant database:");
                        _log.Write(ex.ToString());
                        _log.Write("Skipped this tenant and will continue for others...");
                    }

                    migratedDatabases.Add(tenant.ConnectionString);
                }
                else
                {
                    _log.Write("This database has already migrated before (you have more than one tenant in same database). Skipping it....");
                }

                _log.Write(string.Format("Tenant database migration completed. ({0} / {1})", (i + 1), tenants.Count));
                _log.Write("--------------------------------------------------------");
            }

            _log.Write("All databases have been migrated.");

            return true;
        }

19 Source : UnityARUserAnchorExample.cs
with MIT License
from 734843327

public void ExampleAddAnchor(ARUserAnchor anchor)
	{
		if (m_Clones.Contains(anchor.identifier))
		{
            Console.WriteLine("Our anchor was added!");
		}
	}

19 Source : UnityARUserAnchorExample.cs
with MIT License
from 734843327

public void AnchorRemoved(ARUserAnchor anchor)
	{
		if (m_Clones.Contains(anchor.identifier))
		{
            m_Clones.Remove(anchor.identifier);
            Console.WriteLine("AnchorRemovedExample: " + anchor.identifier);
		}
	}

19 Source : SettingsManager.cs
with MIT License
from a1xd

public void SetActiveHandles()
        {
            ActiveNormTaggedHandles.Clear();

            bool ActiveProfileIsFirst = ActiveProfile == ActiveConfig.profiles[0];

            foreach (var sysDev in SystemDevices)
            {
                void AddHandlesFromSysDev(bool normalized)
                {
                    ActiveNormTaggedHandles.AddRange(sysDev.handles.Select(h => (h, normalized)));
                }

                var settings = ActiveConfig.devices.Find(d => d.id == sysDev.id);

                if (settings is null)
                {
                    if (ActiveProfileIsFirst && !ActiveConfig.defaultDeviceConfig.disable)
                    {
                        AddHandlesFromSysDev(ActiveConfig.defaultDeviceConfig.dpi > 0);
                    }
                }
                else if (!settings.config.disable &&
                            ((ActiveProfileIsFirst &&
                                    (string.IsNullOrEmpty(settings.profile) ||
                                        !ActiveProfileNamesSet.Contains(settings.profile))) ||
                                ActiveProfile.name == settings.profile))
                {
                    AddHandlesFromSysDev(settings.config.dpi > 0);
                }
            }
        }

19 Source : UMACrowdRandomSet.cs
with Apache License 2.0
from A7ocin

public static void Apply(UMA.UMAData umaData, CrowdRaceData race, Color skinColor, Color HairColor, Color Shine, HashSet<string> Keywords, SlotLibraryBase slotLibrary, OverlayLibraryBase overlayLibrary)
		{
			var slotParts = new HashSet<string>();
			umaData.umaRecipe.slotDataList = new SlotData[race.slotElements.Length];
			for (int i = 0; i < race.slotElements.Length; i++)
			{
				var currentElement = race.slotElements[i];
				if (!string.IsNullOrEmpty(currentElement.requirement) && !slotParts.Contains(currentElement.requirement)) continue;
				if (!string.IsNullOrEmpty(currentElement.condition))
				{
					if (currentElement.condition.StartsWith("!"))
					{
						if (Keywords.Contains(currentElement.condition.Substring(1))) continue;
					}
					else
					{
						if (!Keywords.Contains(currentElement.condition)) continue;
					}
				}
				if (currentElement.possibleSlots.Length == 0) continue;
				int randomResult = Random.Range(0, currentElement.possibleSlots.Length);
				var slot = currentElement.possibleSlots[randomResult];
				if (string.IsNullOrEmpty(slot.slotID)) continue;
				slotParts.Add(slot.slotID);
				SlotData slotData;
				if (slot.useSharedOverlayList && slot.overlayListSource >= 0 && slot.overlayListSource < i)
				{
					slotData = slotLibrary.InstantiateSlot(slot.slotID, umaData.umaRecipe.slotDataList[slot.overlayListSource].GetOverlayList());
				}
				else
				{
					if (slot.useSharedOverlayList)
					{
						Debug.LogError("UMA Crowd: Invalid overlayListSource for " + slot.slotID);
					}
					slotData = slotLibrary.InstantiateSlot(slot.slotID);
				}
				umaData.umaRecipe.slotDataList[i] = slotData;
				for (int overlayIdx = 0; overlayIdx < slot.overlayElements.Length; overlayIdx++)
				{
					var currentOverlayElement = slot.overlayElements[overlayIdx];
					randomResult = Random.Range(0, currentOverlayElement.possibleOverlays.Length);
					var overlay = currentOverlayElement.possibleOverlays[randomResult];
					if (string.IsNullOrEmpty(overlay.overlayID)) continue;
					overlay.UpdateVersion();
					slotParts.Add(overlay.overlayID);
					Color overlayColor = Color.black;
					var overlayData = overlayLibrary.InstantiateOverlay(overlay.overlayID, overlayColor);


					switch (overlay.overlayType)
					{
						case UMACrowdRandomSet.OverlayType.Color:
							overlayColor = overlay.minRGB;
							overlayData.colorData.color = overlayColor;

							break;
						case UMACrowdRandomSet.OverlayType.Texture:
							overlayColor = Color.white;
							overlayData.colorData.color = overlayColor;
							break;
						case UMACrowdRandomSet.OverlayType.Hair:
							overlayColor = HairColor * overlay.hairColorMultiplier;
							overlayColor.a = 1.0f;
							overlayData.colorData.color = overlayColor;
							break;
						case UMACrowdRandomSet.OverlayType.Skin:
							overlayColor = skinColor;//  + new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), 1);
							overlayData.colorData.color = overlayColor;
							if (overlayData.colorData.channelAdditiveMask.Length > 2)
							{
								overlayData.colorData.channelAdditiveMask[2] = Shine;
							}
							else
							{
								break;
							}
							break;
						case UMACrowdRandomSet.OverlayType.Random:
							{
								float randomShine = Random.Range(0.05f, 0.25f);
								float randomMetal = Random.Range(0.1f, 0.3f);

								overlayColor = new Color(Random.Range(overlay.minRGB.r, overlay.maxRGB.r), Random.Range(overlay.minRGB.g, overlay.maxRGB.g), Random.Range(overlay.minRGB.b, overlay.maxRGB.b), Random.Range(overlay.minRGB.a, overlay.maxRGB.a));
								overlayData.colorData.color = overlayColor;
								if (overlayData.colorData.channelAdditiveMask.Length > 2)
								{
									overlayData.colorData.channelAdditiveMask[2] = new Color(randomMetal, randomMetal, randomMetal, randomShine);
								}
							}
							break;
						default:
							Debug.LogError("Unknown RandomSet overlayType: "+((int)overlay.overlayType));
							overlayColor = overlay.minRGB;
							overlayData.colorData.color = overlayColor;
							break;
					}
		
					slotData.AddOverlay(overlayData);
					if (overlay.colorChannelUse != ChannelUse.None)
					{
						overlayColor.a *= overlay.minRGB.a;
						if (overlay.colorChannelUse == ChannelUse.InverseColor)
						{
							Vector3 color = new Vector3(overlayColor.r, overlayColor.g, overlayColor.b);
							var len = color.magnitude;
							if (len < 1f) len = 1f;
							color = new Vector3(1.001f, 1.001f, 1.001f) - color;
							color = color.normalized* len;
							overlayColor = new Color(color.x, color.y, color.z, overlayColor.a);
						}
						overlayData.SetColor(overlay.colorChannel, overlayColor);
					}
				}
			}
		}

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public static bool CheckIsBanIP(string IP)
        {
            if ((DateTime.UtcNow - BlockipUpdate).TotalSeconds > 30)
            {
                var fileName = Loger.PathLog + "blockip.txt";

                BlockipUpdate = DateTime.UtcNow;
                if (!File.Exists(fileName)) Blockip = new HashSet<string>();
                else
                    try
                    {
                        var listBlock = File.ReadAllLines(fileName, Encoding.UTF8);
                        if (listBlock.Any(b => b.Contains("/")))
                        {
                            listBlock = listBlock
                                .SelectMany(b =>
                                {
                                    var bb = b.Trim();
                                    var comment = "";
                                    var ic = bb.IndexOf(" ");
                                    if (ic > 0)
                                    {
                                        comment = bb.Substring(ic);
                                        bb = bb.Substring(0, ic);
                                    }
                                    if (bb.Any(c => !char.IsDigit(c) && c != '.' && c != '/')) return new List<string>();
                                    var ls = bb.LastIndexOf("/");
                                    if (ls < 0) return new List<string>() { bb + comment };
                                    var lp = bb.LastIndexOf(".");
                                    if (lp <= 0) return new List<string>();
                                    var ib = int.Parse(bb.Substring(lp + 1, ls - (lp + 1)));
                                    var ie = int.Parse(bb.Substring(ls + 1));
                                    var res = new List<string>();
                                    var s = bb.Substring(0, lp + 1);
                                    for (int i = ib; i <= ie; i++)
                                        res.Add(s + i.ToString() + comment);
                                    return res;
                                })
                                .ToArray();
                            File.WriteAllLines(fileName, listBlock, Encoding.Default);
                        }
                        Blockip = new HashSet<string>(listBlock
                            .Select(b => b.Contains(" ") ? b.Substring(0, b.IndexOf(" ")) : b));
                    }
                    catch (Exception exp)
                    {
                        Loger.Log("CheckIsBanIP error " + exp.Message);
                        Blockip = new HashSet<string>();
                        return false;
                    }

            }

            return Blockip.Contains(IP.Trim());
        }

19 Source : CommonUtils.cs
with Apache License 2.0
from AantCoder

static string Process(object obj, int level, string prefLine, Dictionary<object, int> forParentLink, HashSet<string> excludeTypes)
        {
            try
            {
                if (obj == null) return "";
                Type type = obj.GetType();
                if (excludeTypes.Contains(type.Name)) return "<skip>";
                if (type == typeof(DateTime))
                {
                    return ((DateTime)obj).ToString("g");
                }
                else if (type.IsValueType || type == typeof(string))
                {
                    return obj.ToString();
                }
                else if (type.IsArray || obj is IEnumerable)
                {
                    string elementType = null;
                    Array array = null;

                    if (type.IsArray)
                    {
                        var tt = Type.GetType(type.FullName.Replace("[]", string.Empty));
                        if (tt != null)
                        {
                            elementType = tt.ToString();
                            if (excludeTypes.Contains(tt.Name)) return "<skips>";
                        }
                        //else return "<EEEEEEE" + type.FullName;
                        array = obj as Array;
                    }
                    else
                    {
                        //как лучше узнать кол-во и тип?
                        int cnt = 0;
                        foreach (var o in obj as IEnumerable) cnt++;
                        array = Array.CreateInstance(typeof(object), cnt);
                        int i = 0;
                        foreach (var o in obj as IEnumerable)
                        {
                            if (elementType == null && o != null)
                            {
                                var tt = o.GetType();
                                if (excludeTypes.Contains(tt.Name)) return "<skips>";
                                elementType = tt.ToString();
                            }
                            array.SetValue(o, i++);
                        }
                    }

                    if (elementType == null) elementType = "Object";

                    if (excludeTypes.Contains(elementType)) return "<skips>";

                    var info = "<" + elementType + "[" + array.Length.ToString() + "]" + ">";

                    if (level == 0)
                    {
                        return info + "[...]";
                    }

                    if (array.Length > 0)
                    {
                        var ress = new string[array.Length];
                        var resl = 0;
                        for (int i = 0; i < array.Length; i++)
                        {
                            ress[i] = Process(array.GetValue(i), level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
                            resl += ress[i].Length;
                        }

                        if (resl < LineLength)
                        {
                            var res = info + "[" + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", " + ress[i];
                            }
                            return res + "]";
                        }
                        else
                        {
                            var res = info + "["
                                + Environment.NewLine + prefLine + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", "
                                    + Environment.NewLine + prefLine + ress[i];
                            }
                            return res + Environment.NewLine + prefLine + "]";
                        }
                    }
                    return info + "[]";
                }
                else if (obj is Type) return "<Type>" + obj.ToString();
                else if (type.IsClreplaced)
                {
                    var info = "<" + type.Name + ">";

                    if (forParentLink.ContainsKey(obj))
                    {
                        if (forParentLink[obj] >= level)
                            return info + "{duplicate}";
                        else
                            forParentLink[obj] = level;
                    }
                    else
                        forParentLink.Add(obj, level);

                    if (level == 0)
                    {
                        return info + "{...}";
                    }

                    FieldInfo[] fields = type.GetFields(BindingFlags.Public |
                                BindingFlags.NonPublic | BindingFlags.Instance);

                    if (fields.Length > 0)
                    {
                        var ress = new string[fields.Length];
                        var resl = 0;
                        for (int i = 0; i < fields.Length; i++)
                        {
                            object fieldValue = fields[i].GetValue(obj);
                            ress[i] = fieldValue == null
                                ? fields[i].Name + ": null"
                                : fields[i].Name + ": " + Process(fieldValue, level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
                            resl += ress[i].Length;
                        }

                        if (resl < LineLength)
                        {
                            var res = info + "{" + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", " + ress[i];
                            }
                            return res + "}";
                        }
                        else
                        {
                            var res = info + "{"
                                + Environment.NewLine + prefLine + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", "
                                    + Environment.NewLine + prefLine + ress[i];
                            }
                            return res + Environment.NewLine + prefLine + "}";
                        }
                    }
                    return info + "{}";
                }
                else
                    throw new ArgumentException("Unknown type");
            }
            catch
            {
                return "<exception>";
            }
        }

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public static bool CheckIsIntruder(string key)
        {
            if ((DateTime.UtcNow - BlockkeyUpdate).TotalSeconds > 30)
            {
                var fileName = Loger.PathLog + "blockkey.txt";

                BlockkeyUpdate = DateTime.UtcNow;
                if (!File.Exists(fileName)) Blockkey = new HashSet<string>();
                else
                    try
                    {
                        var listBlock = File.ReadAllLines(fileName, Encoding.UTF8)
                            .Select(b => b.Replace("@@@", "").Trim())
                            .Select(b => b.Contains(" ") ? b.Substring(0, b.IndexOf(" ")) : b)
                            .Where(b => b != String.Empty)
                            .ToArray();
                        Blockkey = new HashSet<string>(listBlock);
                    }
                    catch (Exception exp)
                    {
                        Loger.Log("CheckIsIntruder error " + exp.Message);
                        Blockkey = new HashSet<string>();
                        return false;
                    }
            }
            var k = key.Replace("@@@", "").Trim();
            return Blockkey.Contains(k);
        }

19 Source : MixedRealitySearchUtility.cs
with Apache License 2.0
from abist-co-ltd

private static IEnumerable<SerializedProperty> GatherProperties (UnityEngine.Object profile)
        {
            List<SerializedProperty> properties = new List<SerializedProperty>();
            SerializedProperty iterator = new SerializedObject(profile).Gereplacederator();
            bool hasNextProperty = iterator.Next(true);
            while (hasNextProperty)
            {
                if (!serializedPropertiesToIgnore.Contains(iterator.name) && iterator.depth < maxChildSearchDepth)
                {
                    properties.Add(iterator.Copy());
                }

                if (serializedPropertyTypesToFlatten.Contains(iterator.type))
                {
                    hasNextProperty = iterator.Next(false);
                }
                else
                {
                    hasNextProperty = iterator.Next(true);
                }
            }
            return properties;
        }

19 Source : AudioDeviceSource.cs
with MIT License
from ABTSoftware

private void RefreshDevices()
        {
            if (!_dispatcher.CheckAccess())
            {
                _dispatcher.BeginInvoke((Action)RefreshDevices);
                return;
            }
            DefaultDevice = GetDefaultDevice();

            var deviceMap = Devices.ToDictionary(d => d.ID, d => d);
            var presentDevices = new HashSet<string>();

            foreach (var d in _enumerator.EnumerateAudioEndPoints(DataFlow.Capture, DeviceState.Active))
            {
                presentDevices.Add(d.ID);
                if(deviceMap.TryGetValue(d.ID, out var device))
                {
                    device.Update(d);
                }
                else
                {
                    Devices.Add(new AudioDeviceInfo(d));
                }
                d.Dispose();
            }

            for (int i = Devices.Count - 1; i >=0; i--)
            {
                if (!presentDevices.Contains(Devices[i].ID))
                {
                    Devices.RemoveAt(i);
                }
            }

            DevicesChanged?.Invoke(this, EventArgs.Empty);
        }

19 Source : PageRenderService.cs
with Apache License 2.0
from acblog

public async Task<string> Render(Page page, Layout? layout)
        {
            string content = page.Content;
            var features = new HashSet<string>(page.Features.Items.Select(x => x.ToLowerInvariant()));
            if (features.Contains(nameof(PageFeature.Markdown).ToLowerInvariant()))
            {
                content = await MarkdownRenderService.RenderHtml(content);
            }

            if (layout is null)
            {
                return content;
            }
            else
            {
                var template = Template.Parse(layout.Template);
                Context context = new Context
                {
                    replacedle = page.replacedle,
                    Content = content
                };
                foreach (var item in page.Properties.Raw)
                {
                    context.Properties.Add(item.Key, JsonConvert.DeserializeObject<dynamic>(item.Value));
                }
                return await template.RenderAsync(new
                {
                    Context = context,
                    Props = context.Properties,
                    Content = context.Content
                }, member => member.Name);
            }
        }

19 Source : LootSwap.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void ParseFolder(string folder, Dictionary<string, Dictionary<string, object>> files)
        {
            var di = new DirectoryInfo(folder);

            if (!di.Exists)
            {
                Console.WriteLine($"{folder} not found");
                return;
            }

            var _files = di.GetFiles();

            foreach (var file in _files)
            {
                if (!file.Name.EndsWith(".cs"))
                    continue;

                if (excludeList.Contains(file.Name))
                    continue;

                var clreplacedName = file.Name.Replace(".cs", "");
                var result = LootParser.ParseFile(file.FullName);
                files.Add(clreplacedName, result);
            }

            var subfolders = di.GetDirectories();

            foreach (var subfolder in subfolders)
                ParseFolder(subfolder.FullName, files);
        }

19 Source : ContractManager.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void NotifyOfQuestUpdate(string questName)
        {
            foreach (var contracts in MonitoredQuestFlags)
            {
                if (contracts.Value.Contains(questName.ToLower()))
                    Update(contracts.Key);
            }
        }

19 Source : ActionCommand.cs
with MIT License
from actions

public static bool TryParseV2(string message, HashSet<string> registeredCommands, out ActionCommand command)
        {
            command = null;
            if (string.IsNullOrEmpty(message))
            {
                return false;
            }

            try
            {
                // the message needs to start with the keyword after trim leading space.
                message = message.TrimStart();
                if (!message.StartsWith(_commandKey))
                {
                    return false;
                }

                // Get the index of the separator between the command info and the data.
                int endIndex = message.IndexOf(_commandKey, _commandKey.Length);
                if (endIndex < 0)
                {
                    return false;
                }

                // Get the command info (command and properties).
                int cmdIndex = _commandKey.Length;
                string cmdInfo = message.Substring(cmdIndex, endIndex - cmdIndex);

                // Get the command name
                int spaceIndex = cmdInfo.IndexOf(' ');
                string commandName =
                    spaceIndex < 0
                    ? cmdInfo
                    : cmdInfo.Substring(0, spaceIndex);

                if (registeredCommands.Contains(commandName))
                {
                    // Initialize the command.
                    command = new ActionCommand(commandName);
                }
                else
                {
                    return false;
                }

                // Set the properties.
                if (spaceIndex > 0)
                {
                    string propertiesStr = cmdInfo.Substring(spaceIndex + 1).Trim();
                    string[] splitProperties = propertiesStr.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string propertyStr in splitProperties)
                    {
                        string[] pair = propertyStr.Split(new[] { '=' }, count: 2, options: StringSplitOptions.RemoveEmptyEntries);
                        if (pair.Length == 2)
                        {
                            command.Properties[pair[0]] = UnescapeProperty(pair[1]);
                        }
                    }
                }

                command.Data = UnescapeData(message.Substring(endIndex + _commandKey.Length));
                return true;
            }
            catch
            {
                command = null;
                return false;
            }
        }

19 Source : ActionCommand.cs
with MIT License
from actions

public static bool TryParse(string message, HashSet<string> registeredCommands, out ActionCommand command)
        {
            command = null;
            if (string.IsNullOrEmpty(message))
            {
                return false;
            }

            try
            {
                // Get the index of the prefix.
                int prefixIndex = message.IndexOf(Prefix);
                if (prefixIndex < 0)
                {
                    return false;
                }

                // Get the index of the separator between the command info and the data.
                int rbIndex = message.IndexOf(']', prefixIndex);
                if (rbIndex < 0)
                {
                    return false;
                }

                // Get the command info (command and properties).
                int cmdIndex = prefixIndex + Prefix.Length;
                string cmdInfo = message.Substring(cmdIndex, rbIndex - cmdIndex);

                // Get the command name
                int spaceIndex = cmdInfo.IndexOf(' ');
                string commandName =
                    spaceIndex < 0
                    ? cmdInfo
                    : cmdInfo.Substring(0, spaceIndex);

                if (registeredCommands.Contains(commandName))
                {
                    // Initialize the command.
                    command = new ActionCommand(commandName);
                }
                else
                {
                    return false;
                }

                // Set the properties.
                if (spaceIndex > 0)
                {
                    string propertiesStr = cmdInfo.Substring(spaceIndex + 1);
                    string[] splitProperties = propertiesStr.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string propertyStr in splitProperties)
                    {
                        string[] pair = propertyStr.Split(new[] { '=' }, count: 2, options: StringSplitOptions.RemoveEmptyEntries);
                        if (pair.Length == 2)
                        {
                            command.Properties[pair[0]] = Unescape(pair[1]);
                        }
                    }
                }

                command.Data = Unescape(message.Substring(rbIndex + 1));
                return true;
            }
            catch
            {
                command = null;
                return false;
            }
        }

19 Source : ProjectRootFolder.cs
with MIT License
from action-bi-toolkit

public void Dispose()
        {
            // Do not delete anything if an unhandled error has occurred
            if (!_committed) return;

            if (_filesWritten.Count == 0)
            {
                if (Directory.Exists(BasePath))
                {
                    Directory.Delete(BasePath, recursive: true);
                    Log.Information("No files written. Removed base folder: {Path}", BasePath);
                }

                return;
            }

            // Remove any existing files that have not been updated
            foreach (var path in Directory.GetFiles(BasePath, "*.*", SearchOption.AllDirectories))
            {
                if (!_filesWritten.Contains(path))
                {
                    File.Delete(path);
                    Log.Information("Removed file: {Path}", path);
                }
            }

            // Remove empty dirs:
            foreach (var dir in Directory.GetDirectories(BasePath, "*", SearchOption.AllDirectories).ToArray())
            {
                if (Directory.Exists(dir) && Directory.EnumerateFiles(dir, "*.*", SearchOption.AllDirectories).FirstOrDefault() == null)
                {
                    Directory.Delete(dir, recursive: true); // Could be root of a series of empty folders
                    Log.Information("Removed empty directory: {Path}", dir);
                }
            }

            // TODO Check if nested empty dirs need to be removed explicitly
            // ./ROOT
            // ./ROOT/dir1
            // ./ROOT/dir1/file.txt
            // ./ROOT/dir1/empty/ ***
        }

19 Source : CommandLineParser.cs
with MIT License
from actions

public void Parse(string[] args)
        {
            _trace.Info(nameof(Parse));
            ArgUtil.NotNull(args, nameof(args));
            _trace.Info("Parsing {0} args", args.Length);

            string argScope = null;
            foreach (string arg in args)
            {
                _trace.Info("parsing argument");

                HasArgs = HasArgs || arg.StartsWith("--");
                _trace.Info("HasArgs: {0}", HasArgs);

                if (string.Equals(arg, "/?", StringComparison.Ordinal))
                {
                    Flags.Add("help");
                }
                else if (!HasArgs)
                {
                    _trace.Info("Adding Command: {0}", arg);
                    Commands.Add(arg.Trim());
                }
                else
                {
                    // it's either an arg, an arg value or a flag
                    if (arg.StartsWith("--") && arg.Length > 2)
                    {
                        string argVal = arg.Substring(2);
                        _trace.Info("arg: {0}", argVal);

                        // this means two --args in a row which means previous was a flag
                        if (argScope != null)
                        {
                            _trace.Info("Adding flag: {0}", argScope);
                            Flags.Add(argScope.Trim());
                        }

                        argScope = argVal;
                    }
                    else if (!arg.StartsWith("-"))
                    {
                        // we found a value - check if we're in scope of an arg
                        if (argScope != null && !Args.ContainsKey(argScope = argScope.Trim()))
                        {
                            if (SecretArgNames.Contains(argScope))
                            {
                                _secretMasker.AddValue(arg);
                            }

                            _trace.Info("Adding option '{0}': '{1}'", argScope, arg);
                            // ignore duplicates - first wins - below will be val1
                            // --arg1 val1 --arg1 val1
                            Args.Add(argScope, arg);
                            argScope = null;
                        }
                    }
                    else
                    {
                        //
                        // ignoring the second value for an arg (val2 below) 
                        // --arg val1 val2

                        // ignoring invalid things like empty - and --
                        // --arg val1 -- --flag
                        _trace.Info("Ignoring arg");
                    }
                }
            }

            _trace.Verbose("done parsing arguments");

            // handle last arg being a flag
            if (argScope != null)
            {
                Flags.Add(argScope);
            }

            _trace.Verbose("Exiting parse");
        }

19 Source : CheckUtil.cs
with MIT License
from actions

protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            base.OnEventWritten(eventData);
            lock (_lock)
            {
                if (_ignoredEvent.TryGetValue(eventData.EventSource.Name, out var ignored) &&
                    ignored.Contains(eventData.EventName))
                {
                    return;
                }

                _logs.Add($"{DateTime.UtcNow.ToString("O")} [START {eventData.EventSource.Name} - {eventData.EventName}]");
                _logs.AddRange(eventData.Payload.Select(x => string.Join(Environment.NewLine, x.ToString().Split(Environment.NewLine).Select(y => $"{DateTime.UtcNow.ToString("O")} {y}"))));
                _logs.Add($"{DateTime.UtcNow.ToString("O")} [END {eventData.EventSource.Name} - {eventData.EventName}]");
            }
        }

19 Source : ActionRunner.cs
with MIT License
from actions

public async Task RunAsync()
        {
            // Validate args.
            Trace.Entering();
            ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
            ArgUtil.NotNull(Action, nameof(Action));
            var taskManager = HostContext.GetService<IActionManager>();
            var handlerFactory = HostContext.GetService<IHandlerFactory>();

            // Load the task definition and choose the handler.
            Definition definition = taskManager.LoadAction(ExecutionContext, Action);
            ArgUtil.NotNull(definition, nameof(definition));

            ActionExecutionData handlerData = definition.Data?.Execution;
            ArgUtil.NotNull(handlerData, nameof(handlerData));

            List<JobExtensionRunner> localActionContainerSetupSteps = null;
            // Handle Composite Local Actions
            // Need to download and expand the tree of referenced actions
            if (handlerData.ExecutionType == ActionExecutionType.Composite &&
                handlerData is CompositeActionExecutionData compositeHandlerData &&
                Stage == ActionRunStage.Main &&
                Action.Reference is Pipelines.RepositoryPathReference localAction &&
                string.Equals(localAction.RepositoryType, Pipelines.PipelineConstants.SelfAlias, StringComparison.OrdinalIgnoreCase))
            {
                var actionManager = HostContext.GetService<IActionManager>();
                var prepareResult = await actionManager.PrepareActionsAsync(ExecutionContext, compositeHandlerData.Steps, ExecutionContext.Id);

                // Reload definition since post may exist now (from embedded steps that were JIT downloaded)
                definition = taskManager.LoadAction(ExecutionContext, Action);
                ArgUtil.NotNull(definition, nameof(definition));
                handlerData = definition.Data?.Execution;
                ArgUtil.NotNull(handlerData, nameof(handlerData));

                // Save container setup steps so we can reference them later
                localActionContainerSetupSteps = prepareResult.ContainerSetupSteps;
            }

            if (handlerData.HasPre &&
                Action.Reference is Pipelines.RepositoryPathReference repoAction &&
                string.Equals(repoAction.RepositoryType, Pipelines.PipelineConstants.SelfAlias, StringComparison.OrdinalIgnoreCase))
            {
                ExecutionContext.Warning($"`pre` execution is not supported for local action from '{repoAction.Path}'");
            }

            // The action has post cleanup defined.
            // we need to create timeline record for them and add them to the step list that StepRunner is using
            if (handlerData.HasPost && (Stage == ActionRunStage.Pre || Stage == ActionRunStage.Main))
            {
                string postDisplayName = $"Post {this.DisplayName}";
                if (Stage == ActionRunStage.Pre &&
                    this.DisplayName.StartsWith("Pre ", StringComparison.OrdinalIgnoreCase))
                {
                    // Trim the leading `Pre ` from the display name.
                    // Otherwise, we will get `Post Pre xxx` as DisplayName for the Post step.
                    postDisplayName = $"Post {this.DisplayName.Substring("Pre ".Length)}";
                }
                var repositoryReference = Action.Reference as RepositoryPathReference;
                var pathString = string.IsNullOrEmpty(repositoryReference.Path) ? string.Empty : $"/{repositoryReference.Path}";
                var repoString = string.IsNullOrEmpty(repositoryReference.Ref) ? $"{repositoryReference.Name}{pathString}" :
                    $"{repositoryReference.Name}{pathString}@{repositoryReference.Ref}";

                ExecutionContext.Debug($"Register post job cleanup for action: {repoString}");

                var actionRunner = HostContext.CreateService<IActionRunner>();
                actionRunner.Action = Action;
                actionRunner.Stage = ActionRunStage.Post;
                actionRunner.Condition = handlerData.CleanupCondition;
                actionRunner.DisplayName = postDisplayName;

                ExecutionContext.RegisterPostJobStep(actionRunner);
            }

            IStepHost stepHost = HostContext.CreateService<IDefaultStepHost>();

            // Makes directory for event_path data
            var tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp);
            var workflowDirectory = Path.Combine(tempDirectory, "_github_workflow");
            Directory.CreateDirectory(workflowDirectory);

            var gitHubEvent = ExecutionContext.GetGitHubContext("event");

            // adds the GitHub event path/file if the event exists
            if (gitHubEvent != null)
            {
                var workflowFile = Path.Combine(workflowDirectory, "event.json");
                Trace.Info($"Write event payload to {workflowFile}");
                File.WriteAllText(workflowFile, gitHubEvent, new UTF8Encoding(false));
                ExecutionContext.SetGitHubContext("event_path", workflowFile);
            }

            // Set GITHUB_ACTION_REPOSITORY if this Action is from a repository
            if (Action.Reference is Pipelines.RepositoryPathReference repoPathReferenceAction &&
                !string.Equals(repoPathReferenceAction.RepositoryType, Pipelines.PipelineConstants.SelfAlias, StringComparison.OrdinalIgnoreCase))
            {
                ExecutionContext.SetGitHubContext("action_repository", repoPathReferenceAction.Name);
                ExecutionContext.SetGitHubContext("action_ref", repoPathReferenceAction.Ref);
            }
            else
            {
                ExecutionContext.SetGitHubContext("action_repository", null);
                ExecutionContext.SetGitHubContext("action_ref", null);
            }

            // Setup container stephost for running inside the container.
            if (ExecutionContext.Global.Container != null)
            {
                // Make sure required container is already created.
                ArgUtil.NotNullOrEmpty(ExecutionContext.Global.Container.ContainerId, nameof(ExecutionContext.Global.Container.ContainerId));
                var containerStepHost = HostContext.CreateService<IContainerStepHost>();
                containerStepHost.Container = ExecutionContext.Global.Container;
                stepHost = containerStepHost;
            }

            // Setup File Command Manager
            var fileCommandManager = HostContext.CreateService<IFileCommandManager>();
            fileCommandManager.InitializeFiles(ExecutionContext, null);

            // Load the inputs.
            ExecutionContext.Debug("Loading inputs");
            var templateEvaluator = ExecutionContext.ToPipelineTemplateEvaluator();
            var inputs = templateEvaluator.EvaluateStepInputs(Action.Inputs, ExecutionContext.ExpressionValues, ExecutionContext.ExpressionFunctions);

            var userInputs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            foreach (KeyValuePair<string, string> input in inputs)
            {
                userInputs.Add(input.Key);
                string message = "";
                if (definition.Data?.Deprecated?.TryGetValue(input.Key, out message) == true)
                {
                    ExecutionContext.Warning(String.Format("Input '{0}' has been deprecated with message: {1}", input.Key, message));
                }
            }

            var validInputs = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            if (handlerData.ExecutionType == ActionExecutionType.Container)
            {
                // container action always accept 'entryPoint' and 'args' as inputs
                // https://help.github.com/en/actions/reference/workflow-syntax-for-github-actions#jobsjob_idstepswithargs
                validInputs.Add("entryPoint");
                validInputs.Add("args");
            }
            // Merge the default inputs from the definition
            if (definition.Data?.Inputs != null)
            {
                var manifestManager = HostContext.GetService<IActionManifestManager>();
                foreach (var input in definition.Data.Inputs)
                {
                    string key = input.Key.replacedertString("action input name").Value;
                    validInputs.Add(key);
                    if (!inputs.ContainsKey(key))
                    {
                        inputs[key] = manifestManager.EvaluateDefaultInput(ExecutionContext, key, input.Value);
                    }
                }
            }

            // Validate inputs only for actions with action.yml
            if (Action.Reference.Type == Pipelines.ActionSourceType.Repository)
            {
                var unexpectedInputs = new List<string>();
                foreach (var input in userInputs)
                {
                    if (!validInputs.Contains(input))
                    {
                        unexpectedInputs.Add(input);
                    }
                }

                if (unexpectedInputs.Count > 0)
                {
                    ExecutionContext.Warning($"Unexpected input(s) '{string.Join("', '", unexpectedInputs)}', valid inputs are ['{string.Join("', '", validInputs)}']");
                }
            }

            // Load the action environment.
            ExecutionContext.Debug("Loading env");
            var environment = new Dictionary<String, String>(VarUtil.EnvironmentVariableKeyComparer);

#if OS_WINDOWS
            var envContext = ExecutionContext.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = ExecutionContext.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            // Apply environment from env context, env context contains job level env and action's evn block
            foreach (var env in envContext)
            {
                environment[env.Key] = env.Value.ToString();
            }

            // Apply action's intra-action state at last
            foreach (var state in ExecutionContext.IntraActionState)
            {
                environment[$"STATE_{state.Key}"] = state.Value ?? string.Empty;
            }

            // Create the handler.
            IHandler handler = handlerFactory.Create(
                            ExecutionContext,
                            Action.Reference,
                            stepHost,
                            handlerData,
                            inputs,
                            environment,
                            ExecutionContext.Global.Variables,
                            actionDirectory: definition.Directory,
                            localActionContainerSetupSteps: localActionContainerSetupSteps);

            // Print out action details
            handler.PrintActionDetails(Stage);

            // Run the task.
            try
            {
                await handler.RunAsync(Stage);
            }
            finally
            {
                fileCommandManager.ProcessFiles(ExecutionContext, ExecutionContext.Global.Container);
            }

        }

19 Source : ExecutionContext.cs
with MIT License
from actions

public void RemoveMatchers(IEnumerable<string> owners)
        {
            var root = Root;
            var distinctOwners = new HashSet<string>(owners, StringComparer.OrdinalIgnoreCase);
            var removedMatchers = new List<IssueMatcherConfig>();
            var newMatchers = new List<IssueMatcherConfig>();

            // Lock
            lock (root._matchersLock)
            {
                // Remove
                var existingMatchers = root._matchers ?? Array.Empty<IssueMatcherConfig>();
                foreach (var matcher in existingMatchers)
                {
                    if (distinctOwners.Contains(matcher.Owner))
                    {
                        removedMatchers.Add(matcher);
                    }
                    else
                    {
                        newMatchers.Add(matcher);
                    }
                }

                // Store
                root._matchers = newMatchers.ToArray();

                // Fire events
                foreach (var removedMatcher in removedMatchers)
                {
                    root._onMatcherChanged(null, new MatcherChangedEventArgs(new IssueMatcherConfig { Owner = removedMatcher.Owner }));
                }

                // Output
                owners = removedMatchers.Select(x => $"'{x.Owner}'");
                var joinedOwners = string.Join(", ", owners);
                // todo: loc
                this.Debug($"Removed matchers: {joinedOwners}");
            }
        }

19 Source : GitHubContext.cs
with MIT License
from actions

public IEnumerable<KeyValuePair<string, string>> GetRuntimeEnvironmentVariables()
        {
            foreach (var data in this)
            {
                if (_contextEnvAllowlist.Contains(data.Key))
                {
                    if (data.Value is StringContextData value)
                    {
                        yield return new KeyValuePair<string, string>($"GITHUB_{data.Key.ToUpperInvariant()}", value);
                    }
                    else if (data.Value is BooleanContextData booleanValue)
                    {
                        yield return new KeyValuePair<string, string>($"GITHUB_{data.Key.ToUpperInvariant()}", booleanValue.ToString());
                    }
                }
            }
        }

19 Source : JobExtension.cs
with MIT License
from actions

public void FinalizeJob(IExecutionContext jobContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc)
        {
            Trace.Entering();
            ArgUtil.NotNull(jobContext, nameof(jobContext));

            // create a new timeline record node for 'Finalize job'
            IExecutionContext context = jobContext.CreateChild(Guid.NewGuid(), "Complete job", $"{nameof(JobExtension)}_Final", null, null, ActionRunStage.Post);
            using (var register = jobContext.CancellationToken.Register(() => { context.CancelToken(); }))
            {
                try
                {
                    context.Start();
                    context.Debug("Starting: Complete job");

                    Trace.Info("Initialize Env context");

#if OS_WINDOWS
                    var envContext = new DictionaryContextData();
#else
                    var envContext = new CaseSensitiveDictionaryContextData();
#endif
                    context.ExpressionValues["env"] = envContext;
                    foreach (var pair in context.Global.EnvironmentVariables)
                    {
                        envContext[pair.Key] = new StringContextData(pair.Value ?? string.Empty);
                    }

                    // Populate env context for each step
                    Trace.Info("Initialize steps context");
                    context.ExpressionValues["steps"] = context.Global.StepsContext.GetScope(context.ScopeName);

                    var templateEvaluator = context.ToPipelineTemplateEvaluator();
                    // Evaluate job outputs
                    if (message.JobOutputs != null && message.JobOutputs.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set job outputs");

                            // Populate env context for each step
                            Trace.Info("Initialize Env context for evaluating job outputs");

                            var outputs = templateEvaluator.EvaluateJobOutput(message.JobOutputs, context.ExpressionValues, context.ExpressionFunctions);
                            foreach (var output in outputs)
                            {
                                if (string.IsNullOrEmpty(output.Value))
                                {
                                    context.Debug($"Skip output '{output.Key}' since it's empty");
                                    continue;
                                }

                                if (!string.Equals(output.Value, HostContext.SecretMasker.MaskSecrets(output.Value)))
                                {
                                    context.Warning($"Skip output '{output.Key}' since it may contain secret.");
                                    continue;
                                }

                                context.Output($"Set output '{output.Key}'");
                                jobContext.JobOutputs[output.Key] = output.Value;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Fail to evaluate job outputs");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    // Evaluate environment data
                    if (jobContext.ActionsEnvironment?.Url != null && jobContext.ActionsEnvironment?.Url.Type != TokenType.Null)
                    {
                        try
                        {
                            context.Output($"Evaluate and set environment url");

                            var environmentUrlToken = templateEvaluator.EvaluateEnvironmentUrl(jobContext.ActionsEnvironment.Url, context.ExpressionValues, context.ExpressionFunctions);
                            var environmentUrl = environmentUrlToken.replacedertString("environment.url");
                            if (!string.Equals(environmentUrl.Value, HostContext.SecretMasker.MaskSecrets(environmentUrl.Value)))
                            {
                                context.Warning($"Skip setting environment url as environment '{jobContext.ActionsEnvironment.Name}' may contain secret.");
                            }
                            else
                            {
                                context.Output($"Evaluated environment url: {environmentUrl}");
                                jobContext.ActionsEnvironment.Url = environmentUrlToken;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Result = TaskResult.Failed;
                            context.Error($"Failed to evaluate environment url");
                            context.Error(ex);
                            jobContext.Result = TaskResultUtil.MergeTaskResults(jobContext.Result, TaskResult.Failed);
                        }
                    }

                    if (context.Global.Variables.GetBoolean(Constants.Variables.Actions.RunnerDebug) ?? false)
                    {
                        Trace.Info("Support log upload starting.");
                        context.Output("Uploading runner diagnostic logs");

                        IDiagnosticLogManager diagnosticLogManager = HostContext.GetService<IDiagnosticLogManager>();

                        try
                        {
                            diagnosticLogManager.UploadDiagnosticLogs(executionContext: context, parentContext: jobContext, message: message, jobStartTimeUtc: jobStartTimeUtc);

                            Trace.Info("Support log upload complete.");
                            context.Output("Completed runner diagnostic log upload");
                        }
                        catch (Exception ex)
                        {
                            // Log the error but make sure we continue gracefully.
                            Trace.Info("Error uploading support logs.");
                            context.Output("Error uploading runner diagnostic logs");
                            Trace.Error(ex);
                        }
                    }

                    if (_processCleanup)
                    {
                        context.Output("Cleaning up orphan processes");

                        // Only check environment variable for any process that doesn't run before we invoke our process.
                        Dictionary<int, Process> currentProcesses = SnapshotProcesses();
                        foreach (var proc in currentProcesses)
                        {
                            if (proc.Key == Process.GetCurrentProcess().Id)
                            {
                                // skip for current process.
                                continue;
                            }

                            if (_existingProcesses.Contains($"{proc.Key}_{proc.Value.ProcessName}"))
                            {
                                Trace.Verbose($"Skip existing process. PID: {proc.Key} ({proc.Value.ProcessName})");
                            }
                            else
                            {
                                Trace.Info($"Inspecting process environment variables. PID: {proc.Key} ({proc.Value.ProcessName})");

                                string lookupId = null;
                                try
                                {
                                    lookupId = proc.Value.GetEnvironmentVariable(HostContext, Constants.ProcessTrackingId);
                                }
                                catch (Exception ex)
                                {
                                    Trace.Warning($"Ignore exception during read process environment variables: {ex.Message}");
                                    Trace.Verbose(ex.ToString());
                                }

                                if (string.Equals(lookupId, _processLookupId, StringComparison.OrdinalIgnoreCase))
                                {
                                    context.Output($"Terminate orphan process: pid ({proc.Key}) ({proc.Value.ProcessName})");
                                    try
                                    {
                                        proc.Value.Kill();
                                    }
                                    catch (Exception ex)
                                    {
                                        Trace.Error("Catch exception during orphan process cleanup.");
                                        Trace.Error(ex);
                                    }
                                }
                            }
                        }
                    }

                    if (_diskSpaceCheckTask != null)
                    {
                        _diskSpaceCheckToken.Cancel();
                    }
                }
                catch (Exception ex)
                {
                    // Log and ignore the error from JobExtension finalization.
                    Trace.Error($"Caught exception from JobExtension finalization: {ex}");
                    context.Output(ex.Message);
                }
                finally
                {
                    context.Debug("Finishing: Complete job");
                    context.Complete();
                }
            }
        }

19 Source : ExecutionContext.cs
with MIT License
from actions

public void AddMatchers(IssueMatchersConfig config)
        {
            var root = Root;

            // Lock
            lock (root._matchersLock)
            {
                var newMatchers = new List<IssueMatcherConfig>();

                // Prepend
                var newOwners = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                foreach (var matcher in config.Matchers)
                {
                    newOwners.Add(matcher.Owner);
                    newMatchers.Add(matcher);
                }

                // Add existing non-matching
                var existingMatchers = root._matchers ?? Array.Empty<IssueMatcherConfig>();
                newMatchers.AddRange(existingMatchers.Where(x => !newOwners.Contains(x.Owner)));

                // Store
                root._matchers = newMatchers.ToArray();

                // Fire events
                foreach (var matcher in config.Matchers)
                {
                    root._onMatcherChanged(null, new MatcherChangedEventArgs(matcher));
                }

                // Output
                var owners = config.Matchers.Select(x => $"'{x.Owner}'");
                var joinedOwners = string.Join(", ", owners);
                // todo: loc
                this.Debug($"Added matchers: {joinedOwners}. Problem matchers scan action output for known warning or error strings and report these inline.");
            }
        }

19 Source : PipelineTemplateEvaluator.cs
with MIT License
from actions

private TemplateContext CreateContext(
            DictionaryContextData contextData,
            IList<IFunctionInfo> expressionFunctions,
            IEnumerable<KeyValuePair<String, Object>> expressionState = null)
        {
            var result = new TemplateContext
            {
                CancellationToken = CancellationToken.None,
                Errors = new TemplateValidationErrors(MaxErrors, MaxErrorMessageLength),
                Memory = new TemplateMemory(
                    maxDepth: MaxDepth,
                    maxEvents: MaxEvents,
                    maxBytes: MaxResultSize),
                Schema = m_schema,
                TraceWriter = m_trace,
            };

            // Add the file table
            if (m_fileTable?.Count > 0)
            {
                foreach (var file in m_fileTable)
                {
                    result.GetFileId(file);
                }
            }

            // Add named values
            if (contextData != null)
            {
                foreach (var pair in contextData)
                {
                    result.ExpressionValues[pair.Key] = pair.Value;
                }
            }

            // Add functions
            var functionNames = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
            if (expressionFunctions?.Count > 0)
            {
                foreach (var function in expressionFunctions)
                {
                    result.ExpressionFunctions.Add(function);
                    functionNames.Add(function.Name);
                }
            }

            // Add missing expression values and expression functions.
            // This solves the following problems:
            //   - Compat for new agent against old server (new contexts not sent down in job message)
            //   - Evaluating early when all referenced contexts are available, even though all allowed
            //     contexts may not yet be available. For example, evaluating step display name can often
            //     be performed early.
            foreach (var name in s_expressionValueNames)
            {
                if (!result.ExpressionValues.ContainsKey(name))
                {
                    result.ExpressionValues[name] = null;
                }
            }
            foreach (var name in s_expressionFunctionNames)
            {
                if (!functionNames.Contains(name))
                {
                    result.ExpressionFunctions.Add(new FunctionInfo<NoOperation>(name, 0, Int32.MaxValue));
                }
            }

            // Add state
            if (expressionState != null)
            {
                foreach (var pair in expressionState)
                {
                    result.State[pair.Key] = pair.Value;
                }
            }

            return result;
        }

19 Source : TemplateEvaluator.cs
with MIT License
from actions

private void HandleMappingWithWellKnownProperties(
            DefinitionInfo definition,
            List<MappingDefinition> mappingDefinitions,
            MappingToken mapping)
        {
            // Check if loose properties are allowed
            String looseKeyType = null;
            String looseValueType = null;
            DefinitionInfo? looseKeyDefinition = null;
            DefinitionInfo? looseValueDefinition = null;
            if (!String.IsNullOrEmpty(mappingDefinitions[0].LooseKeyType))
            {
                looseKeyType = mappingDefinitions[0].LooseKeyType;
                looseValueType = mappingDefinitions[0].LooseValueType;
            }

            var keys = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
            var hasExpressionKey = false;

            while (m_unraveler.AllowScalar(definition.Expand, out ScalarToken nextKeyScalar))
            {
                // Expression
                if (nextKeyScalar is ExpressionToken)
                {
                    hasExpressionKey = true;
                    var anyDefinition = new DefinitionInfo(definition, TemplateConstants.Any);
                    mapping.Add(nextKeyScalar, Evaluate(anyDefinition));
                    continue;
                }

                // Not a string, convert
                if (!(nextKeyScalar is StringToken nextKey))
                {
                    nextKey = new StringToken(nextKeyScalar.FileId, nextKeyScalar.Line, nextKeyScalar.Column, nextKeyScalar.ToString());
                }

                // Duplicate
                if (!keys.Add(nextKey.Value))
                {
                    m_context.Error(nextKey, TemplateStrings.ValueAlreadyDefined(nextKey.Value));
                    m_unraveler.SkipMappingValue();
                    continue;
                }

                // Well known
                if (m_schema.TryMatchKey(mappingDefinitions, nextKey.Value, out String nextValueType))
                {
                    var nextValueDefinition = new DefinitionInfo(definition, nextValueType);
                    var nextValue = Evaluate(nextValueDefinition);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Loose
                if (looseKeyType != null)
                {
                    if (looseKeyDefinition == null)
                    {
                        looseKeyDefinition = new DefinitionInfo(definition, looseKeyType);
                        looseValueDefinition = new DefinitionInfo(definition, looseValueType);
                    }

                    Validate(nextKey, looseKeyDefinition.Value);
                    var nextValue = Evaluate(looseValueDefinition.Value);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Error
                m_context.Error(nextKey, TemplateStrings.UnexpectedValue(nextKey.Value));
                m_unraveler.SkipMappingValue();
            }

            // Only one
            if (mappingDefinitions.Count > 1)
            {
                var hitCount = new Dictionary<String, Int32>();
                foreach (MappingDefinition mapdef in mappingDefinitions)
                {
                    foreach (String key in mapdef.Properties.Keys)
                    {
                        if (!hitCount.TryGetValue(key, out Int32 value))
                        {
                            hitCount.Add(key, 1);
                        }
                        else
                        {
                            hitCount[key] = value + 1;
                        }
                    }
                }

                List<String> nonDuplicates = new List<String>();
                foreach (String key in hitCount.Keys)
                {
                    if (hitCount[key] == 1)
                    {
                        nonDuplicates.Add(key);
                    }
                }
                nonDuplicates.Sort();

                String listToDeDuplicate = String.Join(", ", nonDuplicates);
                m_context.Error(mapping, TemplateStrings.UnableToDetermineOneOf(listToDeDuplicate));
            }
            else if (mappingDefinitions.Count == 1 && !hasExpressionKey)
            {
                foreach (var property in mappingDefinitions[0].Properties)
                {
                    if (property.Value.Required)
                    {
                        if (!keys.Contains(property.Key))
                        {
                            m_context.Error(mapping, $"Required property is missing: {property.Key}");
                        }
                    }
                }
            }

            m_unraveler.ReadMappingEnd();
        }

19 Source : TemplateReader.cs
with MIT License
from actions

private void HandleMappingWithWellKnownProperties(
            DefinitionInfo definition,
            List<MappingDefinition> mappingDefinitions,
            MappingToken mapping)
        {
            // Check if loose properties are allowed
            String looseKeyType = null;
            String looseValueType = null;
            DefinitionInfo? looseKeyDefinition = null;
            DefinitionInfo? looseValueDefinition = null;
            if (!String.IsNullOrEmpty(mappingDefinitions[0].LooseKeyType))
            {
                looseKeyType = mappingDefinitions[0].LooseKeyType;
                looseValueType = mappingDefinitions[0].LooseValueType;
            }

            var keys = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
            var hasExpressionKey = false;

            while (m_objectReader.AllowLiteral(out LiteralToken rawLiteral))
            {
                var nextKeyScalar = ParseScalar(rawLiteral, definition.AllowedContext);
                // Expression
                if (nextKeyScalar is ExpressionToken)
                {
                    hasExpressionKey = true;
                    // Legal
                    if (definition.AllowedContext.Length > 0)
                    {
                        m_memory.AddBytes(nextKeyScalar);
                        var anyDefinition = new DefinitionInfo(definition, TemplateConstants.Any);
                        mapping.Add(nextKeyScalar, ReadValue(anyDefinition));
                    }
                    // Illegal
                    else
                    {
                        m_context.Error(nextKeyScalar, TemplateStrings.ExpressionNotAllowed());
                        SkipValue();
                    }

                    continue;
                }

                // Not a string, convert
                if (!(nextKeyScalar is StringToken nextKey))
                {
                    nextKey = new StringToken(nextKeyScalar.FileId, nextKeyScalar.Line, nextKeyScalar.Column, nextKeyScalar.ToString());
                }

                // Duplicate
                if (!keys.Add(nextKey.Value))
                {
                    m_context.Error(nextKey, TemplateStrings.ValueAlreadyDefined(nextKey.Value));
                    SkipValue();
                    continue;
                }

                // Well known
                if (m_schema.TryMatchKey(mappingDefinitions, nextKey.Value, out String nextValueType))
                {
                    m_memory.AddBytes(nextKey);
                    var nextValueDefinition = new DefinitionInfo(definition, nextValueType);
                    var nextValue = ReadValue(nextValueDefinition);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Loose
                if (looseKeyType != null)
                {
                    if (looseKeyDefinition == null)
                    {
                        looseKeyDefinition = new DefinitionInfo(definition, looseKeyType);
                        looseValueDefinition = new DefinitionInfo(definition, looseValueType);
                    }

                    Validate(nextKey, looseKeyDefinition.Value);
                    m_memory.AddBytes(nextKey);
                    var nextValue = ReadValue(looseValueDefinition.Value);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Error
                m_context.Error(nextKey, TemplateStrings.UnexpectedValue(nextKey.Value));
                SkipValue();
            }

            // Only one
            if (mappingDefinitions.Count > 1)
            {
                var hitCount = new Dictionary<String, Int32>();
                foreach (MappingDefinition mapdef in mappingDefinitions)
                {
                    foreach (String key in mapdef.Properties.Keys)
                    {
                        if (!hitCount.TryGetValue(key, out Int32 value))
                        {
                            hitCount.Add(key, 1);
                        }
                        else
                        {
                            hitCount[key] = value + 1;
                        }
                    }
                }

                List<String> nonDuplicates = new List<String>();
                foreach (String key in hitCount.Keys)
                {
                    if(hitCount[key] == 1)
                    {
                        nonDuplicates.Add(key);
                    }
                }
                nonDuplicates.Sort();

                String listToDeDuplicate = String.Join(", ", nonDuplicates);
                m_context.Error(mapping, TemplateStrings.UnableToDetermineOneOf(listToDeDuplicate));
            }
            else if (mappingDefinitions.Count == 1 && !hasExpressionKey)
            {
                foreach (var property in mappingDefinitions[0].Properties)
                {
                    if (property.Value.Required)
                    {
                        if (!keys.Contains(property.Key))
                        {
                            m_context.Error(mapping, $"Required property is missing: {property.Key}");
                        }
                    }
                }
            }
            ExpectMappingEnd();
        }

19 Source : ActionCommandManager.cs
with MIT License
from actions

private void ValidateStopToken(IExecutionContext context, string stopToken)
        {
#if OS_WINDOWS
            var envContext = context.ExpressionValues["env"] as DictionaryContextData;
#else
            var envContext = context.ExpressionValues["env"] as CaseSensitiveDictionaryContextData;
#endif
            var allowUnsecureStopCommandTokens = false;
            allowUnsecureStopCommandTokens = StringUtil.ConvertToBoolean(Environment.GetEnvironmentVariable(Constants.Variables.Actions.AllowUnsupportedStopCommandTokens));
            if (!allowUnsecureStopCommandTokens && envContext.ContainsKey(Constants.Variables.Actions.AllowUnsupportedStopCommandTokens))
            {
                allowUnsecureStopCommandTokens = StringUtil.ConvertToBoolean(envContext[Constants.Variables.Actions.AllowUnsupportedStopCommandTokens].ToString());
            }

            bool isTokenInvalid = _registeredCommands.Contains(stopToken)
                || string.IsNullOrEmpty(stopToken)
                || string.Equals(stopToken, "pause-logging", StringComparison.OrdinalIgnoreCase);

            if (isTokenInvalid)
            {
                var telemetry = new JobTelemetry
                {
                    Message = $"Invoked ::stopCommand:: with token: [{stopToken}]",
                    Type = JobTelemetryType.ActionCommand
                };
                context.JobTelemetry.Add(telemetry);
            }

            if (isTokenInvalid && !allowUnsecureStopCommandTokens)
            {
                throw new Exception(Constants.Runner.UnsupportedStopCommandTokenDisabled);
            }
        }

19 Source : Worker.cs
with MIT License
from actions

private void InitializeSecretMasker(Pipelines.AgentJobRequestMessage message)
        {
            Trace.Entering();
            ArgUtil.NotNull(message, nameof(message));
            ArgUtil.NotNull(message.Resources, nameof(message.Resources));

            // Add mask hints for secret variables
            foreach (var variable in (message.Variables ?? new Dictionary<string, VariableValue>()))
            {
                // Need to ignore values on whitelist
                if (variable.Value.IsSecret && !SecretVariableMaskWhitelist.Contains(variable.Key))
                {
                    var value = variable.Value.Value?.Trim() ?? string.Empty;

                    // Add the entire value, even if it contains CR or LF. During expression tracing,
                    // invidual trace info may contain line breaks.
                    HostContext.SecretMasker.AddValue(value);

                    // Also add each individual line. Typically individual lines are processed from STDOUT of child processes.
                    var split = value.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var item in split)
                    {
                        HostContext.SecretMasker.AddValue(item.Trim());
                    }
                }
            }

            // Add mask hints
            foreach (MaskHint maskHint in (message.MaskHints ?? new List<MaskHint>()))
            {
                if (maskHint.Type == MaskType.Regex)
                {
                    HostContext.SecretMasker.AddRegex(maskHint.Value);

                    // We need this because the worker will print out the job message JSON to diag log
                    // and SecretMasker has JsonEscapeEncoder hook up
                    HostContext.SecretMasker.AddValue(maskHint.Value);
                }
                else
                {
                    // TODO: Should we fail instead? Do any additional pains need to be taken here? Should the job message not be traced?
                    Trace.Warning($"Unsupported mask type '{maskHint.Type}'.");
                }
            }

            // TODO: Avoid adding redundant secrets. If the endpoint auth matches the system connection, then it's added as a value secret and as a regex secret. Once as a value secret b/c of the following code that iterates over each endpoint. Once as a regex secret due to the hint sent down in the job message.

            // Add masks for service endpoints
            foreach (ServiceEndpoint endpoint in message.Resources.Endpoints ?? new List<ServiceEndpoint>())
            {
                foreach (string value in endpoint.Authorization?.Parameters?.Values ?? new string[0])
                {
                    if (!string.IsNullOrEmpty(value))
                    {
                        HostContext.SecretMasker.AddValue(value);
                    }
                }
            }
        }

19 Source : LocationCacheManager.cs
with MIT License
from actions

public Boolean TryFindService(String serviceType, Guid serviceIdentifier, out ServiceDefinition serviceDefinition)
        {
            EnsureDiskCacheLoaded();
            m_accessLock.EnterReadLock();

            try
            {
                Dictionary<Guid, ServiceDefinition> services = null;
                serviceDefinition = null;

                if (CacheDataExpired)
                {
                    return false;
                }

                if (m_services.TryGetValue(serviceType, out services))
                {
                    if (services.TryGetValue(serviceIdentifier, out serviceDefinition))
                    {
                        return true;
                    }
                }

                // Look in our cachedMisses to see if we can find it there.
                if (m_cachedMisses.Contains(BuildCacheMissString(serviceType, serviceIdentifier)))
                {
                    // We found an entry in cached misses so return true.
                    return true;
                }

                return false;
            }
            finally
            {
                m_accessLock.ExitReadLock();
            }
        }

19 Source : ControlDataRepository.cs
with MIT License
from Actipro

public bool IsFavorite(ControlData controlData) {
			return favorites.Contains(controlData.FullName);
		}

19 Source : ParsedDocument.cs
with GNU General Public License v3.0
from Acumatica

private static bool IsSupportedFileType(Doreplacedent doreplacedent) => allowedExtensions.Contains(Path.GetExtension(doreplacedent.FilePath));

19 Source : ParsedSymbolsCache.cs
with GNU General Public License v3.0
from Acumatica

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool IsBqlCommand(string nodeString) => DocTypes[TypeNames.BqlCommand].Contains(nodeString);

19 Source : ParsedSymbolsCache.cs
with GNU General Public License v3.0
from Acumatica

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool IsBqlParameter(string nodeString) => DocTypes[TypeNames.IBqlParameter].Contains(nodeString);

19 Source : ParsedSymbolsCache.cs
with GNU General Public License v3.0
from Acumatica

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool IsBqlOperator(string nodeString) => DocTypes[TypeNames.IBqlCreator].Contains(nodeString);

19 Source : ParsedSymbolsCache.cs
with GNU General Public License v3.0
from Acumatica

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool IsDAC(string nodeString) => DocTypes[TypeNames.IBqlTable].Contains(nodeString);

19 Source : ParsedSymbolsCache.cs
with GNU General Public License v3.0
from Acumatica

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool IsDacField(string nodeString) => DocTypes[TypeNames.IBqlField].Contains(nodeString);

19 Source : ParsedSymbolsCache.cs
with GNU General Public License v3.0
from Acumatica

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool IsBqlConstant(string nodeString) => DocTypes[TypeNames.Constant].Contains(nodeString);

19 Source : Settings.cs
with MIT License
from adlez27

public void LoadRecList()
        {
            if (init && File.Exists(RecListFile))
            {
                RecList.Clear();
                HashSet<string> uniqueStrings = new HashSet<string>();

                Encoding e;
                if (ReadUnicode)
                {
                    e = Encoding.UTF8;
                }
                else
                {
                    e = CodePagesEncodingProvider.Instance.GetEncoding(932);
                }

                var ext = Path.GetExtension(RecListFile);

                if (ext == ".txt")
                {
                    if (Path.GetFileName(RecListFile) == "OREMO-comment.txt")
                    {
                        var rawText = File.ReadAllLines(RecListFile, e);
                        foreach(string rawLine in rawText)
                        {
                            var line = rawLine.Split("\t");
                            if (!uniqueStrings.Contains(line[0]))
                            {
                                RecList.Add(new RecLisreplacedem(this, line[0], line[1]));
                                uniqueStrings.Add(line[0]);
                            }
                        }
                    }
                    else
                    {
                        string[] textArr;
                        if (SplitWhitespace)
                        {
                            var rawText = File.ReadAllText(RecListFile, e);
                            rawText = Regex.Replace(rawText, @"\s{2,}", " ");
                            textArr = Regex.Split(rawText, @"\s");
                        }
                        else
                        {
                            textArr = File.ReadAllLines(RecListFile, e);
                        }

                        foreach (string line in textArr)
                        {
                            if (!uniqueStrings.Contains(line))
                            {
                                RecList.Add(new RecLisreplacedem(this, line));
                                uniqueStrings.Add(line);
                            }
                        }
                    }
                }
                else if (ext == ".arl")
                {
                    var rawText = File.ReadAllText(RecListFile, e);
                    var deserializer = new Deserializer();
                    var tempDict = deserializer.Deserialize<Dictionary<string, string>>(rawText);
                    foreach (var item in tempDict)
                    {
                        RecList.Add(new RecLisreplacedem(this, item.Key, item.Value));
                    }
                }
                else if (ext == ".csv")
                {
                    using (TextFieldParser parser = new TextFieldParser(RecListFile))
                    {
                        parser.TextFieldType = FieldType.Delimited;
                        parser.SetDelimiters(",");
                        while (!parser.EndOfData)
                        {
                            string[] line = parser.ReadFields();
                            var text = line[0].Substring(0,line[0].Length - 4);
                            if (!uniqueStrings.Contains(text))
                            {
                                RecList.Add(new RecLisreplacedem(this, text, line[1]));
                                uniqueStrings.Add(text);
                            }
                        }
                    }
                    CopyIndex();
                }
                else if (ext == ".reclist")
                {
                    var rawText = File.ReadAllText(RecListFile, e);
                    var deserializer = new Deserializer();
                    var reclist = deserializer.Deserialize<WCTReclist>(rawText);
                    foreach(var line in reclist.Files)
                    {
                        if (!uniqueStrings.Contains(line.Filename))
                        {
                            RecList.Add(new RecLisreplacedem(this, line.Filename, line.Description));
                            uniqueStrings.Add(line.Filename);
                        }
                    }
                }
                else if (ext == ".ust"){
                    var rawText = File.ReadAllLines(RecListFile, e);
                    foreach (var line in rawText)
                    {
                        if (line.StartsWith("Lyric="))
                        {
                            var lyric = line.Substring(6);
                            if (lyric != "R" && lyric != "r" && lyric != "" && !uniqueStrings.Contains(lyric))
                            {
                                RecList.Add(new RecLisreplacedem(this, lyric));
                                uniqueStrings.Add(lyric);
                            }
                        }
                    }
                }
            }
        }

19 Source : Settings.cs
with MIT License
from adlez27

public void LoadRecList()
        {
            if (init && File.Exists(RecListFile))
            {
                RecList.Clear();
                HashSet<string> uniqueStrings = new HashSet<string>();

                Encoding e;
                if (ReadUnicode)
                {
                    e = Encoding.UTF8;
                }
                else
                {
                    e = CodePagesEncodingProvider.Instance.GetEncoding(932);
                }

                var ext = Path.GetExtension(RecListFile);

                if (ext == ".txt")
                {
                    if (Path.GetFileName(RecListFile) == "OREMO-comment.txt")
                    {
                        var rawText = File.ReadAllLines(RecListFile, e);
                        foreach(string rawLine in rawText)
                        {
                            var line = rawLine.Split("\t");
                            if (!uniqueStrings.Contains(line[0]))
                            {
                                RecList.Add(new RecLisreplacedem(this, line[0], line[1]));
                                uniqueStrings.Add(line[0]);
                            }
                        }
                    }
                    else
                    {
                        string[] textArr;
                        if (SplitWhitespace)
                        {
                            var rawText = File.ReadAllText(RecListFile, e);
                            rawText = Regex.Replace(rawText, @"\s{2,}", " ");
                            textArr = Regex.Split(rawText, @"\s");
                        }
                        else
                        {
                            textArr = File.ReadAllLines(RecListFile, e);
                        }

                        foreach (string line in textArr)
                        {
                            if (!uniqueStrings.Contains(line))
                            {
                                RecList.Add(new RecLisreplacedem(this, line));
                                uniqueStrings.Add(line);
                            }
                        }
                    }
                }
                else if (ext == ".arl")
                {
                    var rawText = File.ReadAllText(RecListFile, e);
                    var deserializer = new Deserializer();
                    var tempDict = deserializer.Deserialize<Dictionary<string, string>>(rawText);
                    foreach (var item in tempDict)
                    {
                        RecList.Add(new RecLisreplacedem(this, item.Key, item.Value));
                    }
                }
                else if (ext == ".csv")
                {
                    using (TextFieldParser parser = new TextFieldParser(RecListFile))
                    {
                        parser.TextFieldType = FieldType.Delimited;
                        parser.SetDelimiters(",");
                        while (!parser.EndOfData)
                        {
                            string[] line = parser.ReadFields();
                            var text = line[0].Substring(0,line[0].Length - 4);
                            if (!uniqueStrings.Contains(text))
                            {
                                RecList.Add(new RecLisreplacedem(this, text, line[1]));
                                uniqueStrings.Add(text);
                            }
                        }
                    }
                    CopyIndex();
                }
                else if (ext == ".reclist")
                {
                    var rawText = File.ReadAllText(RecListFile, e);
                    var deserializer = new Deserializer();
                    var reclist = deserializer.Deserialize<WCTReclist>(rawText);
                    foreach(var line in reclist.Files)
                    {
                        if (!uniqueStrings.Contains(line.Filename))
                        {
                            RecList.Add(new RecLisreplacedem(this, line.Filename, line.Description));
                            uniqueStrings.Add(line.Filename);
                        }
                    }
                }
                else if (ext == ".ust"){
                    var rawText = File.ReadAllLines(RecListFile, e);
                    foreach (var line in rawText)
                    {
                        if (line.StartsWith("Lyric="))
                        {
                            var lyric = line.Substring(6);
                            if (lyric != "R" && lyric != "r" && lyric != "" && !uniqueStrings.Contains(lyric))
                            {
                                RecList.Add(new RecLisreplacedem(this, lyric));
                                uniqueStrings.Add(lyric);
                            }
                        }
                    }
                }
            }
        }

19 Source : EntityNamePrivacy.cs
with MIT License
from Adoxio

public static string GetEnreplacedyName(string enreplacedyLogicalName)
		{
			if (string.IsNullOrEmpty(enreplacedyLogicalName))
			{
				return enreplacedyLogicalName;
			}
			
			return PortalEnreplacedyAllowedList.Contains(enreplacedyLogicalName)
				? enreplacedyLogicalName
				: Convert.ToBase64String(HashPii.ComputeHashPiiSha256(Encoding.UTF8.GetBytes(enreplacedyLogicalName)));
		}

See More Examples