System.Collections.Generic.List.ForEach(System.Action)

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

6344 Examples 7

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

public bool TryAddToInventory(WorldObject worldObject, out Container container, int placementPosition = 0, bool limitToMainPackOnly = false, bool burdenCheck = true)
        {
            // bug: should be root owner
            if (this is Player player && burdenCheck)
            {
                if (!player.HasEnoughBurdenToAddToInventory(worldObject))
                {
                    container = null;
                    return false;
                }
            }

            IList<WorldObject> containerItems;

            if (worldObject.UseBackpackSlot)
            {
                containerItems = Inventory.Values.Where(i => i.UseBackpackSlot).ToList();

                if ((ContainerCapacity ?? 0) <= containerItems.Count)
                {
                    container = null;
                    return false;
                }
            }
            else
            {
                containerItems = Inventory.Values.Where(i => !i.UseBackpackSlot).ToList();

                if ((ItemCapacity ?? 0) <= containerItems.Count)
                {
                    // Can we add this to any side pack?
                    if (!limitToMainPackOnly)
                    {
                        var containers = Inventory.Values.OfType<Container>().ToList();
                        containers.Sort((a, b) => (a.Placement ?? 0).CompareTo(b.Placement ?? 0));

                        foreach (var sidePack in containers)
                        {
                            if (sidePack.TryAddToInventory(worldObject, out container, placementPosition, true))
                            {
                                EnreplacedbranceVal += (worldObject.EnreplacedbranceVal ?? 0);
                                Value += (worldObject.Value ?? 0);

                                return true;
                            }
                        }
                    }

                    container = null;
                    return false;
                }
            }

            if (Inventory.ContainsKey(worldObject.Guid))
            {
                container = null;
                return false;
            }

            worldObject.Location = null;
            worldObject.Placement = ACE.Enreplacedy.Enum.Placement.Resting;

            worldObject.OwnerId = Guid.Full;
            worldObject.ContainerId = Guid.Full;
            worldObject.Container = this;
            worldObject.PlacementPosition = placementPosition; // Server only variable that we use to remember/restore the order in which items exist in a container

            // Move all the existing items PlacementPosition over.
            if (!worldObject.UseBackpackSlot)
                containerItems.Where(i => !i.UseBackpackSlot && i.PlacementPosition >= placementPosition).ToList().ForEach(i => i.PlacementPosition++);
            else
                containerItems.Where(i => i.UseBackpackSlot && i.PlacementPosition >= placementPosition).ToList().ForEach(i => i.PlacementPosition++);

            Inventory.Add(worldObject.Guid, worldObject);

            EnreplacedbranceVal += (worldObject.EnreplacedbranceVal ?? 0);
            Value += (worldObject.Value ?? 0);

            container = this;

            OnAddItem();

            return true;
        }

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

public bool TryRemoveFromInventory(ObjectGuid objectGuid, out WorldObject item, bool forceSave = false)
        {
            // first search me / add all items of type.
            if (Inventory.Remove(objectGuid, out item))
            {
                int removedItemsPlacementPosition = item.PlacementPosition ?? 0;

                item.OwnerId = null;
                item.ContainerId = null;
                item.Container = null;
                item.PlacementPosition = null;

                // Move all the existing items PlacementPosition over.
                if (!item.UseBackpackSlot)
                    Inventory.Values.Where(i => !i.UseBackpackSlot && i.PlacementPosition > removedItemsPlacementPosition).ToList().ForEach(i => i.PlacementPosition--);
                else
                    Inventory.Values.Where(i => i.UseBackpackSlot && i.PlacementPosition > removedItemsPlacementPosition).ToList().ForEach(i => i.PlacementPosition--);

                EnreplacedbranceVal -= (item.EnreplacedbranceVal ?? 0);
                Value -= (item.Value ?? 0);

                if (forceSave)
                    item.SaveBiotaToDatabase();

                OnRemoveItem(item);

                return true;
            }

            // next search all containers for item.. run function again for each container.
            var sideContainers = Inventory.Values.Where(i => i.WeenieType == WeenieType.Container).ToList();
            foreach (var container in sideContainers)
            {
                if (((Container)container).TryRemoveFromInventory(objectGuid, out item))
                {
                    EnreplacedbranceVal -= (item.EnreplacedbranceVal ?? 0);
                    Value -= (item.Value ?? 0);

                    return true;
                }
            }

            return false;
        }

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

public void CreateSentinelBuffPlayers(IEnumerable<Player> players, bool self = false, ulong maxLevel = 8)
        {
            if (!(Session.AccessLevel >= AccessLevel.Sentinel)) return;

            var SelfOrOther = self ? "Self" : "Other";

            // ensure level 8s are installed
            var maxSpellLevel = Math.Clamp(maxLevel, 1, 8);
            if (maxSpellLevel == 8 && DatabaseManager.World.GetCachedSpell((uint)SpellId.ArmorOther8) == null)
                maxSpellLevel = 7;

            var tySpell = typeof(SpellId);
            List<BuffMessage> buffMessages = new List<BuffMessage>();
            // prepare messages
            List<string> buffsNotImplementedYet = new List<string>();
            foreach (var spell in Buffs)
            {
                var spellNamPrefix = spell;
                bool isBane = false;
                if (spellNamPrefix.StartsWith("@"))
                {
                    isBane = true;
                    spellNamPrefix = spellNamPrefix.Substring(1);
                }
                string fullSpellEnumName = spellNamPrefix + ((isBane) ? string.Empty : SelfOrOther) + maxSpellLevel;
                string fullSpellEnumNameAlt = spellNamPrefix + ((isBane) ? string.Empty : ((SelfOrOther == "Self") ? "Other" : "Self")) + maxSpellLevel;
                uint spellID = (uint)Enum.Parse(tySpell, fullSpellEnumName);
                var buffMsg = BuildBuffMessage(spellID);

                if (buffMsg == null)
                {
                    spellID = (uint)Enum.Parse(tySpell, fullSpellEnumNameAlt);
                    buffMsg = BuildBuffMessage(spellID);
                }

                if (buffMsg != null)
                {
                    buffMsg.Bane = isBane;
                    buffMessages.Add(buffMsg);
                }
                else
                {
                    buffsNotImplementedYet.Add(fullSpellEnumName);
                }
            }
            // buff each player
            players.ToList().ForEach(targetPlayer =>
            {
                if (buffMessages.Any(k => !k.Bane))
                {
                    // bake player into the messages
                    buffMessages.Where(k => !k.Bane).ToList().ForEach(k => k.SetTargetPlayer(targetPlayer));
                    // update client-side enchantments
                    targetPlayer.Session.Network.EnqueueSend(buffMessages.Where(k => !k.Bane).Select(k => k.SessionMessage).ToArray());
                    // run client-side effect scripts, omitting duplicates
                    targetPlayer.EnqueueBroadcast(buffMessages.Where(k => !k.Bane).ToList().GroupBy(m => m.Spell.TargetEffect).Select(a => a.First().LandblockMessage).ToArray());
                    // update server-side enchantments

                    var buffsForPlayer = buffMessages.Where(k => !k.Bane).ToList().Select(k => k.Enchantment);

                    var lifeBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.LifeMagic).ToList();
                    var critterBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.CreatureEnchantment).ToList();
                    var itemBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.ItemEnchantment).ToList();

                    lifeBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                    critterBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                    itemBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                }
                if (buffMessages.Any(k => k.Bane))
                {
                    // Impen/bane
                    var items = targetPlayer.EquippedObjects.Values.ToList();
                    var itembuffs = buffMessages.Where(k => k.Bane).ToList();
                    foreach (var itemBuff in itembuffs)
                    {
                        foreach (var item in items)
                        {
                            if ((item.WeenieType == WeenieType.Clothing || item.IsShield) && item.IsEnchantable)
                                CreateEnchantmentSilent(itemBuff.Spell, item);
                        }
                    }
                }
            });
        }

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

public void CreateSentinelBuffPlayers(IEnumerable<Player> players, bool self = false, ulong maxLevel = 8)
        {
            if (!(Session.AccessLevel >= AccessLevel.Sentinel)) return;

            var SelfOrOther = self ? "Self" : "Other";

            // ensure level 8s are installed
            var maxSpellLevel = Math.Clamp(maxLevel, 1, 8);
            if (maxSpellLevel == 8 && DatabaseManager.World.GetCachedSpell((uint)SpellId.ArmorOther8) == null)
                maxSpellLevel = 7;

            var tySpell = typeof(SpellId);
            List<BuffMessage> buffMessages = new List<BuffMessage>();
            // prepare messages
            List<string> buffsNotImplementedYet = new List<string>();
            foreach (var spell in Buffs)
            {
                var spellNamPrefix = spell;
                bool isBane = false;
                if (spellNamPrefix.StartsWith("@"))
                {
                    isBane = true;
                    spellNamPrefix = spellNamPrefix.Substring(1);
                }
                string fullSpellEnumName = spellNamPrefix + ((isBane) ? string.Empty : SelfOrOther) + maxSpellLevel;
                string fullSpellEnumNameAlt = spellNamPrefix + ((isBane) ? string.Empty : ((SelfOrOther == "Self") ? "Other" : "Self")) + maxSpellLevel;
                uint spellID = (uint)Enum.Parse(tySpell, fullSpellEnumName);
                var buffMsg = BuildBuffMessage(spellID);

                if (buffMsg == null)
                {
                    spellID = (uint)Enum.Parse(tySpell, fullSpellEnumNameAlt);
                    buffMsg = BuildBuffMessage(spellID);
                }

                if (buffMsg != null)
                {
                    buffMsg.Bane = isBane;
                    buffMessages.Add(buffMsg);
                }
                else
                {
                    buffsNotImplementedYet.Add(fullSpellEnumName);
                }
            }
            // buff each player
            players.ToList().ForEach(targetPlayer =>
            {
                if (buffMessages.Any(k => !k.Bane))
                {
                    // bake player into the messages
                    buffMessages.Where(k => !k.Bane).ToList().ForEach(k => k.SetTargetPlayer(targetPlayer));
                    // update client-side enchantments
                    targetPlayer.Session.Network.EnqueueSend(buffMessages.Where(k => !k.Bane).Select(k => k.SessionMessage).ToArray());
                    // run client-side effect scripts, omitting duplicates
                    targetPlayer.EnqueueBroadcast(buffMessages.Where(k => !k.Bane).ToList().GroupBy(m => m.Spell.TargetEffect).Select(a => a.First().LandblockMessage).ToArray());
                    // update server-side enchantments

                    var buffsForPlayer = buffMessages.Where(k => !k.Bane).ToList().Select(k => k.Enchantment);

                    var lifeBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.LifeMagic).ToList();
                    var critterBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.CreatureEnchantment).ToList();
                    var itemBuffsForPlayer = buffsForPlayer.Where(k => k.Spell.School == MagicSchool.ItemEnchantment).ToList();

                    lifeBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                    critterBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                    itemBuffsForPlayer.ForEach(spl =>
                    {
                        CreateEnchantmentSilent(spl.Spell, targetPlayer);
                    });
                }
                if (buffMessages.Any(k => k.Bane))
                {
                    // Impen/bane
                    var items = targetPlayer.EquippedObjects.Values.ToList();
                    var itembuffs = buffMessages.Where(k => k.Bane).ToList();
                    foreach (var itemBuff in itembuffs)
                    {
                        foreach (var item in items)
                        {
                            if ((item.WeenieType == WeenieType.Clothing || item.IsShield) && item.IsEnchantable)
                                CreateEnchantmentSilent(itemBuff.Spell, item);
                        }
                    }
                }
            });
        }

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

private static void AutoApplyWorldCustomizations()
        {
            var content_folders_search_option = ConfigManager.Config.Offline.RecurseWorldCustomizationPaths ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            var content_folders = new List<string> { GetContentFolder() };
            content_folders.AddRange(ConfigManager.Config.Offline.WorldCustomizationAddedPaths);
            content_folders.Sort();

            Console.WriteLine($"Searching for World Customization SQL scripts .... ");

            content_folders.ForEach(path =>
            {
                var contentDI = new DirectoryInfo(path);
                if (contentDI.Exists)
                {
                    Console.Write($"Searching for SQL files within {path} .... ");

                    foreach (var file in contentDI.GetFiles("*.sql", content_folders_search_option).OrderBy(f => f.FullName))
                    {
                        Console.Write($"Found {file.FullName} .... ");
                        var sqlDBFile = File.ReadAllText(file.FullName);
                        var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={ConfigManager.Config.MySql.World.Host};port={ConfigManager.Config.MySql.World.Port};user={ConfigManager.Config.MySql.World.Username};preplacedword={ConfigManager.Config.MySql.World.Preplacedword};database={ConfigManager.Config.MySql.World.Database};DefaultCommandTimeout=120");
                        sqlDBFile = sqlDBFile.Replace("ace_world", ConfigManager.Config.MySql.World.Database);
                        var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                        Console.Write($"Importing into World database on SQL server at {ConfigManager.Config.MySql.World.Host}:{ConfigManager.Config.MySql.World.Port} .... ");
                        try
                        {
                            script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                            var count = script.Execute();
                            //Console.Write($" {count} database records affected ....");
                            Console.WriteLine(" complete!");
                        }
                        catch (MySql.Data.MySqlClient.MySqlException ex)
                        {
                            Console.WriteLine($" error!");
                            Console.WriteLine($" Unable to apply patch due to following exception: {ex}");
                        }
                    }
                }
            });

            Console.WriteLine($"World Customization SQL scripts import complete!");
        }

19 Source : ImprovedPoV.cs
with MIT License
from acidbubbles

private void OnPreRender(Camera cam)
    {
        if (!IsPovCamera(cam)) return;

        try
        {
            if (_skinHandler != null)
                _skinHandler.BeforeRender();
            if (_hairHandlers != null)
                _hairHandlers.ForEach(x =>
                {
                    if (x != null)
                        x.BeforeRender();
                });
        }
        catch (Exception e)
        {
            if (_failedOnce) return;
            _failedOnce = true;
            SuperController.LogError("Failed to execute pre render Improved PoV: " + e);
        }
    }

19 Source : ImprovedPoV.cs
with MIT License
from acidbubbles

private void OnPostRender(Camera cam)
    {
        if (!IsPovCamera(cam)) return;

        try
        {
            if (_skinHandler != null)
                _skinHandler.AfterRender();
            if (_hairHandlers != null)
                _hairHandlers.ForEach(x =>
                {
                    if (x != null)
                        x.AfterRender();
                });
        }
        catch (Exception e)
        {
            if (_failedOnce) return;
            _failedOnce = true;
            SuperController.LogError("Failed to execute post render Improved PoV: " + e);
        }
    }

19 Source : ImprovedPoV.cs
with MIT License
from acidbubbles

public void Update()
    {
        try
        {
            var active = _headControl.possessed || !_possessedOnlyJSON.val;

            if (!_lastActive && active)
            {
                ApplyAll(true);
                _lastActive = true;
            }
            else if (_lastActive && !active)
            {
                ApplyAll(false);
                _lastActive = false;
            }
            else if (_dirty)
            {
                _dirty = false;
                ApplyAll(_lastActive);
            }
            else if (_lastActive && _selector.selectedCharacter != _character)
            {
                _skinHandler?.Restore();
                _skinHandler = null;
                ApplyAll(true);
            }
            else if (_lastActive && !_selector.hairItems.Where(h => h.active).SequenceEqual(_hair))
            {
                // Note: This only checks if the first hair changed. It'll be good enough for most purposes, but imperfect.
                if (_hairHandlers != null)
                {
                    _hairHandlers.ForEach(x =>
                    {
                        if (x != null)
                            x.Restore();
                    });
                    _hairHandlers = null;
                }
                ApplyAll(true);
            }
        }
        catch (Exception e)
        {
            if (_failedOnce) return;
            _failedOnce = true;
            SuperController.LogError("Failed to update Improved PoV: " + e);
        }
    }

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

public override void BeforePrepareUsage(HookContext context)
        {
            context.Definition.RemoveAutoAliases();

            // remove hidden args:
            new List<CommandLineAction>(
                context.Definition.Actions.Where(a => a.Metadata.HasMeta<OmitFromUsageDocs>())
            )
            .ForEach(a => context.Definition.Actions.Remove(a));
        }

19 Source : BankIdBuilder.cs
with MIT License
from ActiveLogin

public void EnableHttpBankIdApiClient()
        {
            AuthenticationBuilder.Services.AddHttpClient<IBankIdApiClient, BankIdApiClient>(httpClient =>
                {
                    _httpClientConfigurators.ForEach(configurator => configurator(httpClient));
                })
                .ConfigurePrimaryHttpMessageHandler(() =>
                {
                    var httpClientHandler = new SocketsHttpHandler();
                    _httpClientHandlerConfigurators.ForEach(configurator => configurator(httpClientHandler));
                    return httpClientHandler;
                });
        }

19 Source : GrandIdBuilder.cs
with MIT License
from ActiveLogin

public void EnableHttpClient()
        {
            AuthenticationBuilder.Services.AddHttpClient<IGrandIdApiClient, GrandIdApiClient>(httpClient =>
                {
                    _httpClientConfigurators.ForEach(configurator => configurator(httpClient));
                })
                .ConfigurePrimaryHttpMessageHandler(() =>
                {
                    var httpClientHandler = new SocketsHttpHandler();
                    _httpClientHandlerConfigurators.ForEach(configurator => configurator(httpClientHandler));
                    return httpClientHandler;
                });
        }

19 Source : GraphListeners.cs
with Apache License 2.0
from activey

public void NotifyEdgeCreated(AbstractGraphEdge graphEdge)
		{
			listeners.ForEach (listener => {
				listener.GraphEdgeCreated(graphEdge);
			});
		}

19 Source : GraphSceneComponents.cs
with Apache License 2.0
from activey

public void AcceptEdge(GraphSceneEdgeVisitor edgeVisitor)
		{
			edgeComponents.ForEach (edge => {
				edgeVisitor(edge);
			});
		}

19 Source : GraphBackendListeners.cs
with Apache License 2.0
from activey

public void NotifyGraphBackendCreated(AbstractGraphNode graphNode)
		{
			listeners.ForEach (listener => {
				listener.GraphBackendNodeCreated(graphNode);
			});
		}

19 Source : GraphBackendListeners.cs
with Apache License 2.0
from activey

public void NotifyGraphBackendCreated(AbstractGraphEdge graphEdge)
		{
			listeners.ForEach (listener => {
				listener.GraphBackendEdgeCreated(graphEdge);
			});
		}

19 Source : GraphListeners.cs
with Apache License 2.0
from activey

public void NotifyNodeCreated(AbstractGraphNode graphNode)
		{
			listeners.ForEach (listener => {
				listener.GraphNodeCreated(graphNode);
			});
		}

19 Source : GraphSceneComponents.cs
with Apache License 2.0
from activey

public void AcceptNode(GraphSceneNodeVisitor nodeVisitor)
		{
			nodeComponents.ForEach (node => {
				nodeVisitor(node);
			});
		}

19 Source : Graph.cs
with Apache License 2.0
from activey

public void Accept(NodeVisitor visitor)
		{
			loadedNodes.ForEach (loadedNode => {
				visitor(loadedNode);
			});
		}

19 Source : Reference.cs
with MIT License
from adamant

private void PruneBorrowers()
        {
            // First prune recursively
            borrowers.ForEach(r => r.PruneBorrowers());

            var newBorrowers = new List<Reference>();
            // Remove released borrowers
            borrowers.RemoveAll(r =>
            {
                var released = r.Phase == Phase.Released;
                if (released)
                    // But grab their pruned list of borrowers
                    newBorrowers.AddRange(r.Borrowers);

                return released;
            });
            // And add it to ours instead
            borrowers.AddRange(newBorrowers);
        }

19 Source : Serialization.Load.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void Smooth(ref GNFS gnfs)
                {
                    string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.SmoothRelations)}.json");
                    if (File.Exists(filename))
                    {
                        List<Relation> temp = Load.GenericFixedArray<List<Relation>>(filename);
                        temp.ForEach(rel => rel.IsPersisted = true);
                        gnfs.CurrentRelationsProgress.SmoothRelationsCounter = temp.Count;
                        gnfs.CurrentRelationsProgress.Relations.SmoothRelations = temp;
                    }
                }

19 Source : Serialization.Load.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void Rough(ref GNFS gnfs)
                {
                    string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.RoughRelations)}.json");
                    if (File.Exists(filename))
                    {
                        List<Relation> temp = Load.GenericFixedArray<List<Relation>>(filename);
                        temp.ForEach(rel => rel.IsPersisted = true);
                        gnfs.CurrentRelationsProgress.Relations.RoughRelations = temp;
                    }
                }

19 Source : Serialization.Load.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void Free(ref GNFS gnfs)
                {
                    if (gnfs.CurrentRelationsProgress.Relations.FreeRelations.Any(lst => lst.Any(rel => !rel.IsPersisted)))
                    {
                        List<List<Relation>> unsaved = gnfs.CurrentRelationsProgress.Relations.FreeRelations.Where(lst => lst.Any(rel => !rel.IsPersisted)).ToList();
                        foreach (List<Relation> solution in unsaved)
                        {
                            Serialization.Save.Object(solution, Path.Combine(gnfs.SaveLocations.SaveDirectory, $"!!UNSAVED__{nameof(RelationContainer.FreeRelations)}.json"));
                        }
                    }

                    gnfs.CurrentRelationsProgress.Relations.FreeRelations.Clear();
                    gnfs.CurrentRelationsProgress.FreeRelationsCounter = 0;

                    IEnumerable<string> freeRelations = Directory.EnumerateFiles(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.FreeRelations)}_*.json");
                    foreach (string solution in freeRelations)
                    {
                        List<Relation> temp = Load.Generic<List<Relation>>(solution);
                        temp.ForEach(rel => rel.IsPersisted = true);
                        gnfs.CurrentRelationsProgress.Relations.FreeRelations.Add(temp);
                        gnfs.CurrentRelationsProgress.FreeRelationsCounter += 1;
                    }
                }

19 Source : Serialization.Save.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void AppendList(GNFS gnfs, List<Relation> roughRelations)
                    {
                        if (roughRelations != null && roughRelations.Any())
                        {
                            string filename = Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.RoughRelations)}.json");
                            string json = JsonConvert.SerializeObject(roughRelations, Formatting.Indented);
                            json = json.Replace("[", "").Replace("]", ",");
                            File.AppendAllText(filename, json);
                            roughRelations.ForEach(rel => rel.IsPersisted = true);
                        }
                    }

19 Source : Serialization.Save.cs
with GNU General Public License v3.0
from AdamWhiteHat

public static void SingleSolution(GNFS gnfs, List<Relation> solution)
                    {
                        if (solution.Any())
                        {
                            solution.ForEach(rel => rel.IsPersisted = true);
                            Save.Object(solution, Path.Combine(gnfs.SaveLocations.SaveDirectory, $"{nameof(RelationContainer.FreeRelations)}_{gnfs.CurrentRelationsProgress.FreeRelationsCounter}.json"));
                            gnfs.CurrentRelationsProgress.FreeRelationsCounter += 1;
                        }
                    }

19 Source : MainWindow.xaml.cs
with MIT License
from ADeltaX

private void SMTC_SessionsChanged(GlobalSystemMediaTransportControlsSessionManager sender, SessionsChangedEventArgs args)
        {
            Dispatcher.BeginInvoke(DispatcherPriority.Send, new Action(() =>
            {

                var lol = args.GetType();

                var sessions = SMTC.GetSessions();

                var CLR = sessions.ToList();

                // DELETE IF IT DOESN'T EXIST ANYMORE.

                var toDelete = new List<SessionControl>();

                //Find if we have the mythical beast already in list.
                foreach (var sessControl in SessionsStackPanel.Children)
                {
                    var tmp = (SessionControl)sessControl;
                    //if (!sessions.Any(s => s.SourceAppUserModelId == tmp.SMTCSession.SourceAppUserModelId)) //Sad this doesn't work if there are two SourceAppUserModelId with the same name :( 
                    toDelete.Add(tmp);
                }

                toDelete.ForEach(ses => 
                {
                    ses.SMTCSession = null;
                    SessionsStackPanel.Children.Remove(ses);
                });


                //ADD IF IT'S NEW

                var toAdd = new List<SessionControl>();

                foreach (var session in sessions)
                {
                    if (!SessionsStackPanel.Children.Cast<SessionControl>().Any(s => s.SMTCSession.SourceAppUserModelId == session.SourceAppUserModelId))
                    {
                        toAdd.Add(new SessionControl
                        {
                            SMTCSession = session,
                            Margin = new Thickness(0, 2, 0, 0)
                        });
                    }
                }

                toAdd.ForEach(ses => SessionsStackPanel.Children.Add(ses));


                if (SessionsStackPanel.Children.Count > 0)
                {
                    SessionsStackPanel.Margin = new Thickness(0, 2, 0, 0);
                    (SessionsStackPanel.Children[0] as SessionControl).Margin = new Thickness(0);
                }
                else
                    SessionsStackPanel.Margin = new Thickness(0);

            }));
        }

19 Source : PortalCacheInvalidatorThread.cs
with MIT License
from Adoxio

private void LogTimeTelemetry(DateTime pushedToCache, Dictionary<string, EnreplacedyRecordMessage> processingRecords, TimeBasedChangedData crmQueryResults, Dictionary<string, string> timeStampTable)
		{
			var filteredProcessingRecords = processingRecords.Where(item => item.Value.MessageType == MessageType.Create || item.Value.MessageType == MessageType.Update);
			var filteredCrmQueryResults = crmQueryResults.UpdatedEnreplacedyRecords.OfType<Microsoft.Xrm.Sdk.NewOrUpdatedItem>()
				// Only add telemetry for non-initial load enreplacedies (timestamp already has been recorded.
				// This will avoid awful timespan values being captured on initial startup
				.Where(filteredResult => timeStampTable.ContainsKey(filteredResult.NewOrUpdatedEnreplacedy.LogicalName)
					// Timestamp table stores string dataTokens from CRM in the form of 123456!04/04/2004 04:04:04.04
					? filteredResult.NewOrUpdatedEnreplacedy.GetAttributeValue<DateTime>("modifiedon") > DateTime.Parse(timeStampTable[filteredResult.NewOrUpdatedEnreplacedy.LogicalName].Split('!')[1])
					: false);

			IEnumerable<TimeTrackingEntry> entries = filteredProcessingRecords.Join(
				// With list
				filteredCrmQueryResults,
				// Keys
				processingRecord => processingRecord.Key,
				crmQueryResult => crmQueryResult.NewOrUpdatedEnreplacedy.LogicalName,
				// How to join
				(processingRecord, crmqueryResult) => new TimeTrackingEntry(
					processingRecord.Key, pushedToCache,
					crmqueryResult.NewOrUpdatedEnreplacedy.GetAttributeValue<DateTime>("modifiedon"),
					processingRecord.Value.Received));

			entries.ToList().ForEach(traceEntry =>
			{
				ADXTrace.Instance.TraceInfo(TraceCategory.Application,
					string.Format("Overall the '{0}' change took {1} to propagate\n\tMessage to reach portal through Azure: {2}\n\tSleep and Retreival of change from CRM: {3}",
					traceEntry.EnreplacedyLogicalName,
					traceEntry.OverallDelta,
					traceEntry.AzureProcessingDelta,
					traceEntry.InvalidationDelta));
			});
		}

19 Source : SearchMetadataCache.cs
with MIT License
from Adoxio

public HashSet<string> GetPortalSearchEnabledEnreplacedies()
		{
			this.SearchEnabledEnreplacedies = new HashSet<string>();
			this.SearchSavedQueries = new HashSet<SearchSavedQuery>();

			FilterExpression filterExpression = new FilterExpression();
			filterExpression.AddCondition("name", ConditionOperator.Equal, this.GetSearchSavedQueryViewName());
			filterExpression.AddCondition("componentstate", ConditionOperator.Equal, 0);
			QueryExpression query = new QueryExpression()
			{
				EnreplacedyName = "savedquery",
				ColumnSet = new ColumnSet("returnedtypecode", "savedqueryidunique"),
				Criteria = filterExpression
			};
			var request = new RetrieveMultipleRequest() { Query = query };
			var response = (RetrieveMultipleResponse)this.OrganizationServiceContext.Execute(request);
			var enreplacedies = response.EnreplacedyCollection.Enreplacedies;

			foreach (Enreplacedy enreplacedy in enreplacedies)
			{
				var savedQueryItem = new SearchSavedQuery(enreplacedy);
				ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Enreplacedy {0} has Portal Search View Present in CRM ", savedQueryItem.EnreplacedyName));
				this.SearchEnabledEnreplacedies.Add(savedQueryItem.EnreplacedyName);
				this.SearchSavedQueries.Add(savedQueryItem);
			}

			// These enreplacedies are not searchable but changes to them can invalidate certain searchable enreplacedies
			List<string> searchAffectingEnreplacedies = new List<string>()
			{
				"adx_webpageaccesscontrolrule",
				"adx_communityforumaccesspermission",
				"connection",
				"adx_contentaccesslevel",
				"adx_knowledgearticlecontentaccesslevel",
				"adx_webpageaccesscontrolrule_webrole",
				"adx_website",
				"savedquery"
			};
			searchAffectingEnreplacedies.ForEach(x => this.SearchEnabledEnreplacedies.Add(x));
			return this.SearchEnabledEnreplacedies;
		}

19 Source : FSDirectorySearchProvider.cs
with MIT License
from Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().Name;
			}

			base.Initialize(name, config);

			var dataContextName = config["dataContextName"];

			SearchDataContextName = config["searchDataContextName"] ?? dataContextName;
			UpdateDataContextName = config["updateDataContextName"] ?? dataContextName;

			var indexPath = config["indexPath"];

			if (string.IsNullOrEmpty(indexPath))
			{
				throw new ProviderException("The search provider {0} requires the attribute indexPath to be set.".FormatWith(name));
			}

			IndexDirectory = new DirectoryInfo(
				(indexPath.StartsWith(@"~/", StringComparison.Ordinal) || indexPath.StartsWith(@"~\", StringComparison.Ordinal))
					? HostingEnvironment.MapPath(indexPath) ?? indexPath
					: indexPath);

			var useEncryptedDirectory = false;
			bool.TryParse(config["useEncryptedDirectory"], out useEncryptedDirectory);
			UseEncryptedDirectory = useEncryptedDirectory;

			var isOnlinePortal = false;
			bool.TryParse(config["isOnlinePortal"], out isOnlinePortal);
			IsOnlinePortal = isOnlinePortal;

			IndexQueryName = config["indexQueryName"] ?? _defaultIndexQueryName;
			Stemmer = CultureInfo.CurrentUICulture.Parent.EnglishName;

			var stopWords = config["stopWords"];

			StopWords = string.IsNullOrEmpty(stopWords)
				? new string[] { }
				: stopWords.Split(',').Select(word => word.Trim()).Where(word => !string.IsNullOrEmpty(word)).ToArray();

			var searcherCacheMode = config["indexSearcherCacheMode"];

			IndexSearcherCacheMode mode;

			_searcherPool = !string.IsNullOrEmpty(searcherCacheMode) && Enum.TryParse(searcherCacheMode, out mode) && mode == IndexSearcherCacheMode.SingleUse
				? new SingleUseIndexSearcherPool()
				: _sharedSearcherPool;

			var indexVersion = config["indexVersion"];

			Version version;

			Version = !string.IsNullOrEmpty(indexVersion) && Enum.TryParse(indexVersion, out version)
				? version
				: Version.LUCENE_23;

			Guid websiteId;
			WebsiteId = Guid.TryParse(config["websiteId"], out websiteId)
				? websiteId
				: (Guid?)null;

			var recognizedAttributes = new List<string>
			{
				"name",
				"description",
				"dataContextName",
				"indexPath",
				"indexQueryName",
				"indexSearcherCacheMode",
				"indexVersion",
				"searchDataContextName",
				"stemmer",
				"stopWords",
				"updateDataContextName",
				"isOnlinePortal",
				"useEncryptedDirectory",
				"websiteId",
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ProviderException("The search provider {0} does not currently recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}
		}

19 Source : PortalSearchProvider.cs
with MIT License
from Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}

			bool displayNotes;

			PortalName = config["portalName"];
			NotesFilter = config["notesFilter"];
			ArticlesLanguageCode = config["articlesLanguageCode"];
			DisplayNotes = bool.TryParse(config["displayNotes"], out displayNotes) && displayNotes;

			var recognizedAttributes = new List<string>
			{
				"portalName",
				"notesFilter",
				"displayNotes",
				"articlesLanguageCode"
			};

			recognizedAttributes.ForEach(config.Remove);

			base.Initialize(name, config);
		}

19 Source : FetchXmlResultsFilter.cs
with MIT License
from Adoxio

public string Aggregate(string fetchXml, string primaryKeyFieldName, params string[] fields)
		{
			var fetchXmlParsed = XDoreplacedent.Parse(fetchXml);
			var inputResults = fetchXmlParsed.Descendants("result").ToList();

			if (inputResults.Count == 0)
			{
				return fetchXml;
			}

			var aggregatedResults = new Dictionary<string, XElement>();
			var parsedResultSet = new FetchXmlResultSet(fetchXml);

			bool isFirstPage = this.lastResultOnPage == null;
			bool isLastPage = !parsedResultSet.MoreRecords;

			//// Check if last result of last page and first result of this page are the same article.
			//// If not, we need to add the aggregated result from last page during this round.
			//// If so, the past CAL/product ids should still be stored and we'll just add to 
			if (!isFirstPage)
			{
				var firstId = inputResults.First().Descendants(primaryKeyFieldName).FirstOrDefault().Value;
				var previousPageLastId = this.lastResultOnPage.Descendants(primaryKeyFieldName).FirstOrDefault().Value;
				if (firstId != previousPageLastId)
				{
					aggregatedResults[previousPageLastId] = this.lastResultOnPage;
				}
			}
			var lastId = inputResults.Descendants(primaryKeyFieldName).FirstOrDefault().Value;

			var collectionOfFields = fields.Select(fieldName => new RelatedField(fieldName)).ToList();

			//// Iterating through fetchXml retrieving multiple related fields
			foreach (var resultNode in inputResults)
			{
				var primaryKeyFieldNode = resultNode.Descendants(primaryKeyFieldName).FirstOrDefault();
				if (primaryKeyFieldNode == null) { return fetchXml; }

				////Retrieving fields
				collectionOfFields.ForEach(field => this.GetRelatedFields(resultNode, field, primaryKeyFieldNode.Value));
				////Removing duplicate nodes
				aggregatedResults[primaryKeyFieldNode.Value] = resultNode;
			}

			var node = inputResults.FirstOrDefault();
			if (node == null)
			{
				return fetchXml;
			}
			var parentNode = node.Parent;
			if (parentNode == null)
			{
				return fetchXml;
			}

			fetchXmlParsed.Descendants("result").Remove();

			//// Inserting retrieved above related fields and deduplicated results.
			collectionOfFields.ForEach(field => this.InsertRelatedFields(aggregatedResults, field));

			//// Remove and store the last aggregated result, as this might be the same article as the first result on the 
			//// next page.
			this.lastResultOnPage = aggregatedResults[lastId];
			if (!isLastPage)
			{
				aggregatedResults.Remove(lastId);
			}

			fetchXmlParsed.Element(parentNode.Name).Add(aggregatedResults.Values);
			return fetchXmlParsed.ToString();
		}

19 Source : RoleInstanceEndpointPortalSearchProvider.cs
with MIT License
from Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().Name;
			}

			base.Initialize(name, config);

			PortalName = config["portalName"];
			BindingConfiguration = config["bindingConfiguration"];

			var recognizedAttributes = new List<string>
			{
				"name",
				"description",
				"portalName",
				"bindingConfiguration"
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ProviderException("The search provider {0} does not currently recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}

			try
			{
				var serviceRoleName = RoleEnvironment.GetConfigurationSettingValue("Adxstudio.Xrm.Search.WindowsAzure.ServiceRole");

				if (string.IsNullOrEmpty(serviceRoleName))
				{
					throw new ProviderException("Configuration value Adxstudio.Xrm.Search.WindowsAzure.ServiceRole cannot be null or empty.");
				}

				Role serviceRole;

				if (!RoleEnvironment.Roles.TryGetValue(serviceRoleName, out serviceRole))
				{
					throw new ProviderException("Unable to retrieve the role {0}.".FormatWith(serviceRoleName));
				}

				var serviceEndpointName = RoleEnvironment.GetConfigurationSettingValue("Adxstudio.Xrm.Search.WindowsAzure.ServiceEndpoint");

				if (string.IsNullOrEmpty(serviceEndpointName))
				{
					throw new ProviderException("Configuration value Adxstudio.Xrm.Search.WindowsAzure.ServiceEndpoint cannot be null or empty.");
				}

				var serviceEndpoint = serviceRole.Instances.Select(instance =>
				{
					RoleInstanceEndpoint endpoint;

					return instance.InstanceEndpoints.TryGetValue(serviceEndpointName, out endpoint) ? endpoint : null;
				}).FirstOrDefault(endpoint => endpoint != null);

				if (serviceEndpoint == null)
				{
					throw new ProviderException("Unable to retrieve the endpoint {0} from role {1}.".FormatWith(serviceEndpointName, serviceRole.Name));
				}

				ServiceEndpointAddress = new EndpointAddress(string.Format(CultureInfo.InvariantCulture, "net.tcp://{0}/search", serviceEndpoint.IPEndpoint));

				var binding = string.IsNullOrEmpty(BindingConfiguration)
					? new NetTcpBinding(SecurityMode.None) { ReceiveTimeout = TimeSpan.FromDays(1), SendTimeout = TimeSpan.FromDays(1) }
					: new NetTcpBinding(BindingConfiguration);

				ServiceChannelFactory = new ChannelFactory<ISearchService>(binding);

				ServiceChannelFactory.Faulted += OnServiceChannelFactoryFaulted;
			}
			catch (Exception e)
			{
				ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Error initializing provider ""{0}"": {1}", name, e.ToString()));

                throw;
			}
		}

19 Source : CrmProfileProvider.cs
with MIT License
from Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (_initialized) return;

			if (config == null) throw new ArgumentNullException("config");

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().FullName;
			}

			if (string.IsNullOrEmpty(config["description"]))
			{
				config["description"] = "Adxstudio CRM Profile Provider";
			}

			base.Initialize(name, config);

			replacedertRequiredCustomAttributes(config);

			ApplicationName = config["applicationName"] ?? "/";

			_attributeMapStateCode = config["attributeMapStateCode"];

			_attributeMapIsDisabled = config["attributeMapIsDisabled"];

			_attributeMapIsAnonymous = config["attributeMapIsAnonymous"];

			_attributeMapLastActivityDate = config["attributeMapLastActivityDate"];

			_attributeMapLastUpdatedDate = config["attributeMapLastUpdatedDate"];

			_attributeMapUsername = config["attributeMapUsername"];

			ContextName = config["contextName"];

			var enableActivityTrackingConfig = config["enableActivityTracking"];
			bool enableActivityTrackingValue;

			// Profile activity tracking is disabled by default, for performance reasons. Updating the profile
			// activity timestamp on each request generally adds over 100ms--too much.
			_enableActivityTracking = bool.TryParse(enableActivityTrackingConfig, out enableActivityTrackingValue)
				? enableActivityTrackingValue
				: false;

			_profileEnreplacedyName = config["profileEnreplacedyName"];

			var recognizedAttributes = new List<string>
			{
				"name",
				"applicationName",
				"attributeMapStateCode",
				"attributeMapIsDisabled",
				"attributeMapIsAnonymous",
				"attributeMapLastActivityDate",
				"attributeMapLastUpdatedDate",
				"attributeMapUsername",
				"crmDataContextName",
				"enableActivityTracking",
				"profileEnreplacedyName"
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ConfigurationErrorsException("The {0} doesn't recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}

			_initialized = true;
		}

19 Source : CrmContactRoleProvider.cs
with MIT License
from Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (_initialized)
			{
				return;
			}

			config.ThrowOnNull("config");

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().FullName;
			}

			if (string.IsNullOrEmpty(config["description"]))
			{
				config["description"] = "XRM Role Provider";
			}

			base.Initialize(name, config);

			replacedertRequiredCustomAttributes(config);

			ApplicationName = config["applicationName"] ?? Utility.GetDefaultApplicationName();

			_attributeMapIsAuthenticatedUsersRole = config["attributeMapIsAuthenticatedUsersRole"];

			bool authenticatedUsersRolesEnabledConfigurationValue;

			// Whether "Authenticated Users" role is supported is determine by a config switch, and whether
			// or not an attribute map for that boolean has been supplied. The feature is enabled by default,
			// provided that an attribute map has been supplied.
			_authenticatedUsersRolesEnabled = !string.IsNullOrWhiteSpace(_attributeMapIsAuthenticatedUsersRole)
				&& bool.TryParse(config["authenticatedUsersRolesEnabled"], out authenticatedUsersRolesEnabledConfigurationValue)
					? authenticatedUsersRolesEnabledConfigurationValue
					: true;

			_attributeMapStateCode = config["attributeMapStateCode"];

			_attributeMapIsDisabled = config["attributeMapIsDisabled"];

			_attributeMapRoleName = config["attributeMapRoleName"];

			_attributeMapRoleWebsiteId = config["attributeMapRoleWebsiteId"];

			_attributeMapUsername = config["attributeMapUsername"];

			PortalName = config["portalName"];

			_roleEnreplacedyName = config["roleEnreplacedyName"];

			_roleToUserRelationshipName = config["roleToUserRelationshipName"];

			_userEnreplacedyName = config["userEnreplacedyName"];

			_roleEnreplacedyId = config["roleEnreplacedyId"];

			_userEnreplacedyId = config["userEnreplacedyId"];

			var recognizedAttributes = new List<string>
			{
				"name",
				"applicationName",
				"attributeMapStateCode",
				"attributeMapIsDisabled",
				"attributeMapIsAuthenticatedUsersRole",
				"attributeMapRoleName",
				"attributeMapRoleWebsiteId",
				"attributeMapUsername",
				"portalName",
				"roleEnreplacedyName",
				"roleToUserRelationshipName",
				"userEnreplacedyName",
				"roleEnreplacedyId",
				"userEnreplacedyId"
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ConfigurationErrorsException("The {0} doesn't recognize or support the attribute {1}.".FormatWith(name, unrecognizedAttribute));
				}
			}

			_initialized = true;
		}

19 Source : CrmContactAccountRoleProvider.cs
with MIT License
from Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			_attributeMapParentId = config["attributeMapParentId"] ?? "accountid";
			_attributeMapRoleId = config["attributeMapRoleId"] ?? "adx_webroleid";
			_attributeMapUserParentId = config["attributeMapUserParentId"] ?? "parentcustomerid";
			_parentEnreplacedyName = config["parentEnreplacedyName"] ?? "account";
			_roleToParentRelationshipName = config["roleToParentRelationshipName"] ?? "adx_webrole_account";
			_roleToParentRelationshipEnreplacedyName = config["roleToParentRelationshipEnreplacedyName"] ?? _roleToParentRelationshipName;

			var privateRecognizedConfigurationAttributes = new List<string>
			{
				"attributeMapParentId",
				"attributeMapUserParentId",
				"parentEnreplacedyName",
				"roleToParentRelationshipName",
				"roleToParentRelationshipEnreplacedyName",
			};

			// Remove all of the known configuration values recognized by this provider, but not the base one.
			privateRecognizedConfigurationAttributes.ForEach(config.Remove);

			// Add default attribute values for base provider, and capture them as private member variables for internal use.
			_attributeMapStateCode = config["attributeMapStateCode"] = config["attributeMapStateCode"] ?? "statecode";
			_attributeMapRoleName = config["attributeMapRoleName"] = config["attributeMapRoleName"] ?? "adx_name";
			_attributeMapRoleWebsiteId = config["attributeMapRoleWebsiteId"] = config["attributeMapRoleWebsiteId"] ?? "adx_websiteid";
			_attributeMapUsername = config["attributeMapUsername"] = config["attributeMapUsername"] ?? "adx_idenreplacedy_username";
			_roleEnreplacedyName = config["roleEnreplacedyName"] = config["roleEnreplacedyName"] ?? "adx_webrole";
			_userEnreplacedyName = config["userEnreplacedyName"] = config["userEnreplacedyName"] ?? "contact";
			config["userEnreplacedyId"] = config["userEnreplacedyId"] ?? "contactid";
			config["roleEnreplacedyId"] = config["roleEnreplacedyId"] ?? "adx_webroleid";

			base.Initialize(name, config);
		}

19 Source : CrmRoleProvider.cs
with MIT License
from Adoxio

public override void Initialize(string name, NameValueCollection config)
		{
			if (_initialized)
			{
				return;
			}

			config.ThrowOnNull("config");

			if (string.IsNullOrEmpty(name))
			{
				name = GetType().FullName;
			}

			if (string.IsNullOrEmpty(config["description"]))
			{
				config["description"] = "XRM Role Provider";
			}

			base.Initialize(name, config);

			replacedertRequiredCustomAttributes(config);

			ApplicationName = config["applicationName"] ?? Utility.GetDefaultApplicationName();

			_attributeMapIsAuthenticatedUsersRole = config["attributeMapIsAuthenticatedUsersRole"];

			bool authenticatedUsersRolesEnabledConfigurationValue;

			// Whether "Authenticated Users" role is supported is determine by a config switch, and whether
			// or not an attribute map for that boolean has been supplied. The feature is enabled by default,
			// provided that an attribute map has been supplied.
			_authenticatedUsersRolesEnabled = !string.IsNullOrWhiteSpace(_attributeMapIsAuthenticatedUsersRole)
				&& bool.TryParse(config["authenticatedUsersRolesEnabled"], out authenticatedUsersRolesEnabledConfigurationValue)
					? authenticatedUsersRolesEnabledConfigurationValue
					: true;

			_attributeMapRoleName = config["attributeMapRoleName"];

			_attributeMapRoleWebsiteId = config["attributeMapRoleWebsiteId"];

			_attributeMapUsername = config["attributeMapUsername"];

			PortalName = config["portalName"];

			_roleEnreplacedyName = config["roleEnreplacedyName"];

			_roleToUserRelationshipName = config["roleToUserRelationshipName"];

			_userEnreplacedyName = config["userEnreplacedyName"];

			var recognizedAttributes = new List<string>
			{
				"name",
				"applicationName",
				"attributeMapIsAuthenticatedUsersRole",
				"attributeMapRoleName",
				"attributeMapRoleWebsiteId",
				"attributeMapUsername",
				"portalName",
				"roleEnreplacedyName",
				"roleToUserRelationshipName",
				"userEnreplacedyName"
			};

			// Remove all of the known configuration values. If there are any left over, they are unrecognized.
			recognizedAttributes.ForEach(config.Remove);

			if (config.Count > 0)
			{
				var unrecognizedAttribute = config.GetKey(0);

				if (!string.IsNullOrEmpty(unrecognizedAttribute))
				{
					throw new ConfigurationErrorsException("The {0} does not currently recognize or support the attribute '{1}'".FormatWith(name, unrecognizedAttribute));
				}
			}

			_initialized = true;
		}

19 Source : PropertyDeclarationVisitor.cs
with MIT License
from adrianoc

private void ProcessPropertyAccessors(BasePropertyDeclarationSyntax node, string propertyDeclaringTypeVar, string propName, string propertyType, string propDefVar, List<ParamData> parameters, ArrowExpressionClauseSyntax? arrowExpression)
        {
            var propInfo = (IPropertySymbol) Context.SemanticModel.GetDeclaredSymbol(node);
            var accessorModifiers = node.Modifiers.MethodModifiersToCecil((targetEnum, modifiers, defaultAccessibility) => ModifiersToCecil(modifiers, targetEnum, defaultAccessibility), "MethodAttributes.SpecialName", propInfo.GetMethod ?? propInfo.SetMethod);

            var declaringType = node.ResolveDeclaringType<TypeDeclarationSyntax>();
            if (arrowExpression != null)
            {
                AddExpressionBodiedGetterMethod();
                return;
            }
            
            foreach (var accessor in node.AccessorList!.Accessors)
            {
                Context.WriteNewLine();
                switch (accessor.Keyword.Kind())
                {
                    case SyntaxKind.GetKeyword:
                        AddGetterMethod(accessor);
                        break;

                    case SyntaxKind.InitKeyword:
                        Context.WriteComment(" Init");
                        var setterReturnType = $"new RequiredModifierType({ImportExpressionForType(typeof(IsExternalInit))}, {Context.TypeResolver.Bcl.System.Void})";
                        AddSetterMethod(setterReturnType, accessor);
                        break;
                    
                    case SyntaxKind.SetKeyword:
                        Context.WriteComment(" Setter");
                        AddSetterMethod(Context.TypeResolver.Bcl.System.Void, accessor);
                        break; 
                    default:
                        throw new NotImplementedException($"Accessor: {accessor.Keyword}");
                }
            }

            void AddBackingFieldIfNeeded(AccessorDeclarationSyntax accessor, bool hasInitProperty)
            {
                if (backingFieldVar != null)
                    return;

                backingFieldVar = Context.Naming.FieldDeclaration(node, "bf");
                var backingFieldName = $"<{propName}>k__BackingField";
                var modifiers = ModifiersToCecil(accessor.Modifiers, "FieldAttributes", "Private");
                if (hasInitProperty)
                {
                    modifiers = modifiers + " | FieldAttributes.InitOnly";
                }
                
                var backingFieldExps = new[]
                {
                    //TODO: NOW: CecilDefinitionsFactory.Field()
                    $"var {backingFieldVar} = new FieldDefinition(\"{backingFieldName}\", {modifiers}, {propertyType});",
                    $"{propertyDeclaringTypeVar}.Fields.Add({backingFieldVar});"
                };

                AddCecilExpressions(backingFieldExps);
            }

            void AddSetterMethod(string setterReturnType, AccessorDeclarationSyntax accessor)
            {
                var setMethodVar = Context.Naming.SyntheticVariable("set", ElementKind.LocalVariable);
                
                var localParams = new List<string>(parameters.Select(p => p.Type));
                localParams.Add(Context.GetTypeInfo(node.Type).Type.Name); // Setters always have at least one `value` parameter.
                Context.DefinitionVariables.RegisterMethod(declaringType.Identifier.Text, $"set_{propName}", localParams.ToArray(), setMethodVar);
                var ilSetVar = Context.Naming.ILProcessor("set", declaringType.Identifier.Text);

                //TODO : NEXT : try to use CecilDefinitionsFactory.Method()
                AddCecilExpression($"var {setMethodVar} = new MethodDefinition(\"set_{propName}\", {accessorModifiers}, {setterReturnType});");
                parameters.ForEach(p => AddCecilExpression($"{setMethodVar}.Parameters.Add({p.VariableName});"));
                AddCecilExpression($"{propertyDeclaringTypeVar}.Methods.Add({setMethodVar});");

                AddCecilExpression($"{setMethodVar}.Body = new MethodBody({setMethodVar});");
                AddCecilExpression($"{propDefVar}.SetMethod = {setMethodVar};");

                AddCecilExpression($"{setMethodVar}.Parameters.Add(new ParameterDefinition(\"value\", ParameterAttributes.None, {propertyType}));");
                AddCecilExpression($"var {ilSetVar} = {setMethodVar}.Body.GetILProcessor();");

                if (propInfo.ContainingType.TypeKind == TypeKind.Interface)
                    return;

                if (accessor.Body == null && accessor.ExpressionBody == null) //is this an auto property ?
                {
                    AddBackingFieldIfNeeded(accessor, node.AccessorList.Accessors.Any(acc => acc.IsKind(SyntaxKind.InitAccessorDeclaration)));

                    AddCilInstruction(ilSetVar, OpCodes.Ldarg_0); // TODO: This replacedumes instance properties...
                    AddCilInstruction(ilSetVar, OpCodes.Ldarg_1);
                    AddCilInstruction(ilSetVar, OpCodes.Stfld, Utils.MakeGenericTypeIfAppropriate(Context, propInfo, backingFieldVar, propertyDeclaringTypeVar));
                }
                else if (accessor.Body != null)
                {
                    StatementVisitor.Visit(Context, ilSetVar, accessor.Body);
                }
                else
                {
                    ExpressionVisitor.Visit(Context, ilSetVar, accessor.ExpressionBody);
                }

                AddCilInstruction(ilSetVar, OpCodes.Ret);
            }

            string AddGetterMethodGuts(CSharpSyntaxNode accessor)
            {
                Context.WriteComment(" Getter");
                var getMethodVar = Context.Naming.SyntheticVariable("get", ElementKind.Method);
                Context.DefinitionVariables.RegisterMethod(declaringType.Identifier.Text, $"get_{propName}", parameters.Select(p => p.Type).ToArray(), getMethodVar);

                AddCecilExpression($"var {getMethodVar} = new MethodDefinition(\"get_{propName}\", {accessorModifiers}, {propertyType});");
                parameters.ForEach(p => AddCecilExpression($"{getMethodVar}.Parameters.Add({p.VariableName});"));
                AddCecilExpression($"{propertyDeclaringTypeVar}.Methods.Add({getMethodVar});");

                AddCecilExpression($"{getMethodVar}.Body = new MethodBody({getMethodVar});");
                AddCecilExpression($"{propDefVar}.GetMethod = {getMethodVar};");

                if (propInfo.ContainingType.TypeKind == TypeKind.Interface)
                    return null;

                var ilVar = Context.Naming.ILProcessor("get", declaringType.Identifier.Text);
                AddCecilExpression($"var {ilVar} = {getMethodVar}.Body.GetILProcessor();");
                return ilVar;
            }
            
            void AddExpressionBodiedGetterMethod()
            {
                var ilVar = AddGetterMethodGuts(arrowExpression);
                ProcessExpressionBodiedGetter(ilVar, arrowExpression);
            }
            
            void AddGetterMethod(AccessorDeclarationSyntax accessor)
            {
                var ilVar = AddGetterMethodGuts(accessor);
                if (ilVar == null)
                    return;
                
                if (accessor.Body == null && accessor.ExpressionBody == null) //is this an auto property ?
                {
                    AddBackingFieldIfNeeded(accessor, node.AccessorList.Accessors.Any(acc => acc.IsKind(SyntaxKind.InitAccessorDeclaration)));

                    AddCilInstruction(ilVar, OpCodes.Ldarg_0); // TODO: This replacedumes instance properties...
                    AddCilInstruction(ilVar, OpCodes.Ldfld, Utils.MakeGenericTypeIfAppropriate(Context, propInfo, backingFieldVar, propertyDeclaringTypeVar));

                    AddCilInstruction(ilVar, OpCodes.Ret);
                }
                else if (accessor.Body != null)
                {
                    StatementVisitor.Visit(Context, ilVar, accessor.Body);
                }
                else
                {
                    ProcessExpressionBodiedGetter(ilVar, accessor.ExpressionBody);
                }
            }

            void ProcessExpressionBodiedGetter(string ilVar, ArrowExpressionClauseSyntax arrowExpression)
            {
                ExpressionVisitor.Visit(Context, ilVar, arrowExpression);
                AddCilInstruction(ilVar, OpCodes.Ret);
            }
        }

19 Source : ChatroomAgent.cs
with MIT License
from adrenak

void RemoveAllPeers() =>
            PeerSettings.Keys.ToList().ForEach(x => RemovePeer(x));

19 Source : AduNavigationPanel.cs
with GNU General Public License v3.0
from aduskin

private void NavigationPanel_Loaded(object sender, RoutedEventArgs e)
        {
            mHeaderList = VisualHelper.FindVisualChildrenEx<AduGroupBoxNor>(this.PART_ContentPresenter);
            if (mHeaderList != null)
            {
                List<object> list = new List<object>();
                mHeaderList.ForEach(p => list.Add(p));
                this.ItemsSource = list;
            }
            this.mScrollViewer = VisualHelper.FindVisualChild<ScrollViewer>(this.PART_ContentPresenter);
            if (this.mScrollViewer != null)
            {
                this.mScrollViewer.ScrollChanged += MScrollViewer_ScrollChanged;
            }

            object item = this.mHeaderList[this.IndicatorSelectedIndex];
            this.ScrollToSelection(item);
        }

19 Source : ProfitContractTestBase.cs
with MIT License
from AElfProject

private SystemContractDeploymentInput.Types.SystemTransactionMethodCallList
            GenerateTokenInitializationCallList()
        {
            const string symbol = "ELF";
            var tokenContractCallList = new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList();
            tokenContractCallList.Add(nameof(TokenContract.Create), new CreateInput
            {
                Symbol = symbol,
                Decimals = 2,
                IsBurnable = true,
                TokenName = "elf token",
                TotalSupply = ProfitContractTestConstants.NativeTokenTotalSupply,
                Issuer = Starter,
                LockWhiteList =
                {
                    ProfitContractAddress
                }
            });

            // For creating `Treasury` profit scheme.
            tokenContractCallList.Add(nameof(TokenContract.Issue), new IssueInput
            {
                Symbol = symbol,
                Amount = (long) (ProfitContractTestConstants.NativeTokenTotalSupply * 0.12),
                To = Address.FromPublicKey(StarterKeyPair.PublicKey),
                Memo = "Issue token to default user for vote.",
            });

            CreatorKeyPair.ForEach(creatorKeyPair => tokenContractCallList.Add(nameof(TokenContract.Issue),
                new IssueInput
                {
                    Symbol = symbol,
                    Amount = (long) (ProfitContractTestConstants.NativeTokenTotalSupply * 0.1),
                    To = Address.FromPublicKey(creatorKeyPair.PublicKey),
                    Memo = "set voters few amount for voting."
                }));

            NormalKeyPair.ForEach(normalKeyPair => tokenContractCallList.Add(nameof(TokenContract.Issue),
                new IssueInput
                {
                    Symbol = symbol,
                    Amount = (long) (ProfitContractTestConstants.NativeTokenTotalSupply * 0.05),
                    To = Address.FromPublicKey(normalKeyPair.PublicKey),
                    Memo = "set voters few amount for voting."
                }));

            return tokenContractCallList;
        }

19 Source : TokenHolderContractTestBase.cs
with MIT License
from AElfProject

private SystemContractDeploymentInput.Types.SystemTransactionMethodCallList
            GenerateTokenInitializationCallList()
        {
            var tokenContractCallList = new SystemContractDeploymentInput.Types.SystemTransactionMethodCallList();
            tokenContractCallList.Add(nameof(TokenContract.Create), new CreateInput
            {
                Symbol = TokenHolderContractTestConstants.NativeTokenSymbol,
                Decimals = 8,
                IsBurnable = true,
                TokenName = "elf token",
                TotalSupply = TokenHolderContractTestConstants.NativeTokenTotalSupply,
                Issuer = Starter,
                LockWhiteList =
                {
                    ProfitContractAddress,
                    TokenHolderContractAddress
                }
            });
            tokenContractCallList.Add(nameof(TokenContract.SetPrimaryTokenSymbol),
                new SetPrimaryTokenSymbolInput {Symbol = "ELF"});
            tokenContractCallList.Add(nameof(TokenContract.Issue), new IssueInput
            {
                Symbol = TokenHolderContractTestConstants.NativeTokenSymbol,
                Amount = (long) (TokenHolderContractTestConstants.NativeTokenTotalSupply * 0.12),
                To = Address.FromPublicKey(StarterKeyPair.PublicKey),
                Memo = "Issue token to default user for vote.",
            });

            UserKeyPairs.ForEach(creatorKeyPair => tokenContractCallList.Add(nameof(TokenContract.Issue),
                new IssueInput
                {
                    Symbol = TokenHolderContractTestConstants.NativeTokenSymbol,
                    Amount = (long) (TokenHolderContractTestConstants.NativeTokenTotalSupply * 0.1),
                    To = Address.FromPublicKey(creatorKeyPair.PublicKey),
                    Memo = "set voters few amount for voting."
                }));

            return tokenContractCallList;
        }

19 Source : PointDefinition.cs
with MIT License
from Aeroluna

public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder("{ ");
            if (_points != null)
            {
                _points.ForEach(n => stringBuilder.Append($"{n.Point} "));
            }

            stringBuilder.Append("}");
            return stringBuilder.ToString();
        }

19 Source : NoteCutSoundEffectManager.cs
with MIT License
from Aeroluna

private void Update()
        {
            if (_hitsoundQueue.Count > 0 && Time.frameCount != _lastFrame)
            {
                List<NoteController> noteControllers = new List<NoteController>(_hitsoundQueue);
                _hitsoundQueue.Clear();
                noteControllers.ForEach(_noteCutSoundEffectManager!.HandleNoteWreplacedpawned);
                Plugin.Logger.Log($"{noteControllers.Count} cut sounds moved to next frame!");
            }
        }

19 Source : BeatmapObjectsInTimeRowProcessor.cs
with MIT License
from Aeroluna

private static void Prefix(List<NoteData> notesInTimeRow)
        {
            if (notesInTimeRow.FirstOrDefault() is CustomNoteData)
            {
                List<CustomNoteData> notesToSetFlip = new List<CustomNoteData>();

                Dictionary<float, List<CustomNoteData>> notesInColumns = new Dictionary<float, List<CustomNoteData>>();
                for (int i = 0; i < notesInTimeRow.Count; i++)
                {
                    CustomNoteData noteData = (CustomNoteData)notesInTimeRow[i];
                    Dictionary<string, object?> dynData = noteData.customData;

                    IEnumerable<float?>? position = dynData.GetNullableFloats(POSITION);
                    float lineIndex = position?.ElementAtOrDefault(0) ?? (noteData.lineIndex - 2);
                    float lineLayer = position?.ElementAtOrDefault(1) ?? (float)noteData.noteLineLayer;

                    if (!notesInColumns.TryGetValue(lineIndex, out List<CustomNoteData> list))
                    {
                        list = new List<CustomNoteData>(1);
                        notesInColumns.Add(lineIndex, list);
                    }

                    bool flag = false;
                    for (int k = 0; k < list.Count; k++)
                    {
                        IEnumerable<float?>? listPosition = list[k].customData.GetNullableFloats(POSITION);
                        float listLineLayer = listPosition?.ElementAtOrDefault(1) ?? (float)list[k].noteLineLayer;
                        if (listLineLayer > lineLayer)
                        {
                            list.Insert(k, noteData);
                            flag = true;
                            break;
                        }
                    }

                    if (!flag)
                    {
                        list.Add(noteData);
                    }

                    // Flippy stuff
                    IEnumerable<float?>? flip = dynData.GetNullableFloats(FLIP);
                    float? flipX = flip?.ElementAtOrDefault(0);
                    float? flipY = flip?.ElementAtOrDefault(1);
                    if (flipX.HasValue || flipY.HasValue)
                    {
                        if (flipX.HasValue)
                        {
                            dynData["flipLineIndex"] = flipX.Value;
                        }

                        if (flipY.HasValue)
                        {
                            dynData["flipYSide"] = flipY.Value;
                        }
                    }
                    else if (!dynData.ContainsKey("flipYSide"))
                    {
                        notesToSetFlip.Add(noteData);
                    }
                }

                foreach (KeyValuePair<float, List<CustomNoteData>> keyValue in notesInColumns)
                {
                    List<CustomNoteData> list2 = keyValue.Value;
                    for (int m = 0; m < list2.Count; m++)
                    {
                        list2[m].customData["startNoteLineLayer"] = m;
                    }
                }

                // Process flip data
                notesToSetFlip.ForEach(c => c.customData["flipYSide"] = 0);
            }
        }

19 Source : HeckPatch.cs
with MIT License
from Aeroluna

public static void TogglePatches(Harmony id, bool value)
        {
            if (_heckPatches.TryGetValue(id, out HeckData heck))
            {
                if (value != heck.Enabled)
                {
                    heck.Enabled = value;
                    if (value)
                    {
                        heck._heckPatchDatas.ForEach(n =>
                        {
                            try
                            {
                                id.Patch(
                                n.OriginalMethod,
                                n.Prefix != null ? new HarmonyMethod(n.Prefix) : null,
                                n.Postfix != null ? new HarmonyMethod(n.Postfix) : null,
                                n.Transpiler != null ? new HarmonyMethod(n.Transpiler) : null);
                            }
                            catch
                            {
                                Plugin.Logger.Log($"[{id.Id}] Exception while patching [{n.OriginalMethod}] of [{n.OriginalMethod.DeclaringType}].", IPA.Logging.Logger.Level.Critical);
                                throw;
                            }
                        });
                    }
                    else
                    {
                        id.UnpatchAll(id.Id);
                    }
                }
            }
            else
            {
                Plugin.Logger.Log($"Could not find Heck patch data for {id}.", IPA.Logging.Logger.Level.Critical);
            }
        }

19 Source : ConsoleManager.cs
with MIT License
from afucher

public int[] Render(string[] content, string[] bottomContent)
        {
            content.ToList().ForEach(message => console.WriteLine(message));
            Newline();
            bottomContent.ToList().ForEach(message => console.WriteLine(message));
            console.CursorTop = console.CursorTop - (bottomContent.Length + 1);
            return new [] { content.Length, bottomContent.Length };
        }

19 Source : ConsoleManager.cs
with MIT License
from afucher

public int[,] RenderMultipleMessages(string[] mensagens)
        {
            var pos = new int[2,2];
            pos[0,0] = console.CursorLeft;
            pos[0,1] = console.CursorTop;
            mensagens.ToList().ForEach(mensagem => console.WriteLine(mensagem));
            pos[1, 0] = console.CursorLeft;
            pos[1, 1] = pos[0,1] + mensagens.Length;
            return pos;
        }

19 Source : Inquirer.cs
with MIT License
from afucher

public void Ask()
        {
            Questions.ForEach(q => q.Ask());
        }

19 Source : CommonExtend.cs
with Mozilla Public License 2.0
from agebullhu

public static Dictionary<int, string> GetEnumValAndDescList(this Enum enumObj)
        {
            var enumDic = new Dictionary<int, string>();
            var enumType = enumObj.GetType();
            var enumValues = enumType.GetEnumValues().Cast<int>().ToList();

            enumValues.ForEach(item =>
            {
                var key = (int)item;
                var text = enumType.GetEnumName(key);
                var descText = enumType.GetField(text).GetCustomAttributes(typeof(DescriptionAttribute),
                    false).Cast<DescriptionAttribute>().FirstOrDefault()?.Description;

                text = string.IsNullOrWhiteSpace(descText) ? text : descText;

                enumDic.Add(key, text);
            });

            return enumDic;
        }

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

private static bool Validate(List<RegistrationContext> registrations, ContainerRegistrationOption containerRegistrationOption)
        {
            bool isValid = true;
            registrations.ForEach(reg =>
            {
                if (!reg.Validation.IsValid)
                {
                    isValid = false;
                    containerRegistrationOption
                        .OnRegistrationContextException?
                        .Invoke(new RegistrationContextException(reg, reg.Validation.ErrorMessage));
                }
            });
            return isValid;
        }

19 Source : exerciseUserControl.cs
with MIT License
from ahm3tcelik

private void setUI()
        {
            panelHeader.BackColor = colors[new Random().Next(0, colors.Length - 1)];
            lblDay.Text = exercises[0].ExerciseDay.ToString() + ".GÜN";

            exercises.ForEach(e => AddItem(e));
        }

See More Examples