System.Collections.Generic.IEnumerable.Distinct()

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

2908 Examples 7

19 View Source File : Ribbon.cs
License : GNU General Public License v3.0
Project Creator : 0dteam

public String GetURLsAndAttachmentsInfo(MailItem mailItem)
        {
            string urls_and_attachments = "---------- URLs and Attachments ----------";

            var domainsInEmail = new List<string>();

            var emailHTML = mailItem.HTMLBody;
            var doc = new HtmlAgilityPack.HtmlDoreplacedent();
            doc.LoadHtml(emailHTML);

            // extracting all links
            var urlsText = "";
            var urlNodes = doc.DoreplacedentNode.SelectNodes("//a[@href]");
            if(urlNodes != null)
            {
                urlsText = "\n\n # of URLs: " + doc.DoreplacedentNode.SelectNodes("//a[@href]").Count;
                foreach (HtmlNode link in doc.DoreplacedentNode.SelectNodes("//a[@href]"))
                {
                    HtmlAttribute att = link.Attributes["href"];
                    if (att.Value.Contains("a"))
                    {
                        urlsText += "\n --> URL: " + att.Value.Replace(":", "[:]");
                        // Domain Extraction
                        try
                        {
                            domainsInEmail.Add(new Uri(att.Value).Host);
                        }
                        catch (UriFormatException)
                        {
                            // Try to process URL as email address. Example -> <a href="mailto:[email protected]">...etc
                            String emailAtChar = "@";
                            int ix = att.Value.IndexOf(emailAtChar);
                            if (ix != -1)
                            {
                                string emailDomain = att.Value.Substring(ix + emailAtChar.Length);
                                try
                                {
                                    domainsInEmail.Add(new Uri(emailDomain).Host);
                                }
                                catch (UriFormatException)
                                {
                                    // if it fails again, ignore domain extraction
                                    Console.WriteLine("Bad url: {0}", emailDomain);
                                }
                            }
                        }
                    }
                }
            }
            else
                urlsText = "\n\n # of URLs: 0";

            // Get domains
            domainsInEmail = domainsInEmail.Distinct().ToList();
            urls_and_attachments += "\n # of unique Domains: " + domainsInEmail.Count;
            foreach (string item in domainsInEmail)
            {
                urls_and_attachments += "\n --> Domain: " + item.Replace(":", "[:]");
            }

            // Add Urls
            urls_and_attachments += urlsText;

            urls_and_attachments += "\n\n # of Attachments: " + mailItem.Attachments.Count;
            foreach (Attachment a in mailItem.Attachments)
            {
                // Save attachment as txt file temporarily to get its hashes (saves under User's Temp folder)
                var filePath = Environment.ExpandEnvironmentVariables(@"%TEMP%\Outlook-Phishaddin-" + a.DisplayName + ".txt");
                a.SaveAsFile(filePath);

                string fileHash_md5 = "";
                string fileHash_sha256 = "";
                if (File.Exists(filePath))
                {
                    fileHash_md5 = CalculateMD5(filePath);
                    fileHash_sha256 = GetHashSha256(filePath);
                    // Delete file after getting the hashes
                    File.Delete(filePath);
                }
                urls_and_attachments += "\n --> Attachment: " + a.FileName + " (" + a.Size + " bytes)\n\t\tMD5: " + fileHash_md5 + "\n\t\tSha256: " + fileHash_sha256 + "\n";
            }
            return urls_and_attachments;
        }

19 View Source File : IsoHeaderParser.cs
License : MIT License
Project Creator : 13xforever

public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
        {
            var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
            var nextLevel = new List<string>();
            var filePaths = new List<string>();
            var dirPaths = new List<string>();
            while (fsObjects.Any())
            {
                foreach (var path in fsObjects)
                {
                    if (reader.FileExists(path))
                        filePaths.Add(path);
                    else if (reader.DirectoryExists(path))
                    {
                        dirPaths.Add(path);
                        nextLevel.AddRange(reader.GetFileSystemEntries(path));
                    }
                    else
                        Log.Warn($"Unknown filesystem object: {path}");
                }
                (fsObjects, nextLevel) = (nextLevel, fsObjects);
                nextLevel.Clear();
            }
            
            var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
            var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
            var deepestDirnames = new List<string>();
            foreach (var dirname in dirnames)
            {
                var tmp = dirname + "\\";
                if (deepestDirnames.Any(n => n.StartsWith(tmp)))
                    continue;
                
                deepestDirnames.Add(dirname);
            }
            dirnames = deepestDirnames.OrderBy(n => n).ToList();
            var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
            var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();

            var fileList = new List<FileRecord>();
            foreach (var filename in filenames)
            {
                var clusterRange = reader.PathToClusters(filename);
                if (clusterRange.Length != 1)
                    Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
                if (filename.EndsWith("."))
                    Log.Warn($"Fixing potential mastering error in {filename}");
                fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
            }
            fileList = fileList.OrderBy(r => r.StartSector).ToList();
            return (files: fileList, dirs: emptydirs);
        }

19 View Source File : ProxyGenerator.cs
License : MIT License
Project Creator : 1100100

private static SyntaxTree GenerateProxyTree(Type @interface)
        {
            var namespaces = FindAllNamespace(@interface).Distinct().Select(p => SyntaxFactory.UsingDirective(GenerateQualifiedNameSyntax(p))).ToList();
            namespaces.Add(SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName("System")));

            var syntax = SyntaxFactory.CompilationUnit()
                .WithUsings(SyntaxFactory.List(namespaces))
                .WithMembers(GenerateNamespace(@interface));

            return syntax.NormalizeWhitespace().SyntaxTree;
        }

19 View Source File : ConsistentHash.cs
License : MIT License
Project Creator : 1100100

public List<T> GetAllNodes()
        {
            return Ring.Select(p => p.Value).Distinct().ToList();
        }

19 View Source File : JcApiHelper.cs
License : MIT License
Project Creator : 279328316

private static void InitAllControllerNote()
        {
            List<replacedemblyNoteModel> noteList = new List<replacedemblyNoteModel>();

            #region 处理replacedemblyNote
            List<string> moduleList = controllerList.Select(controller => controller.ModuleName).Distinct().ToList();

            string baseDir = AppDomain.CurrentDomain.BaseDirectory;
            DirectoryInfo dirInfo = new DirectoryInfo(baseDir);
            for (int i = 0; i < moduleList.Count; i++)
            {
                string xmlNoteFileName = moduleList[i].Replace(".dll", ".xml");

                FileInfo fileInfo = dirInfo.GetFiles(xmlNoteFileName, SearchOption.AllDirectories).FirstOrDefault();
                if (fileInfo != null)
                {
                    replacedemblyNoteModel noteModel = replacedemblyHelper.GetreplacedemblyNote(fileInfo.FullName);
                    noteList.Add(noteModel);
                }
            }
            #endregion

            for (int i = 0; i < controllerList.Count; i++)
            {
                ControllerModel controller = controllerList[i];
                replacedemblyNoteModel noteModel = noteList.FirstOrDefault(note => note.ModuleName == controller.ModuleName);
                if (noteModel == null)
                {
                    continue;
                }
                //Controller 注释
                controller.NoteModel = noteModel.MemberList.FirstOrDefault(member => member.Name == controller.Id);
                foreach (ActionModel action in controller.ActionList)
                {   //Action注释
                    action.NoteModel = noteModel.MemberList.FirstOrDefault(member => member.Name == action.Id);

                    if (action.NoteModel != null)
                    {
                        foreach (ParamModel param in action.InputParameters)
                        {   //输入参数注释
                            if (action.NoteModel.ParamList.Keys.Contains(param.Name))
                            {
                                param.Summary = action.NoteModel.ParamList[param.Name];
                            }
                        }
                        //返回参数注释
                        action.ReturnParameter.Summary = action.NoteModel.Returns;
                    }
                }
            }
        }

19 View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099

internal void UnSubscribe(bool punsub, string[] channels)
            {
                channels = channels?.Distinct().Select(a => punsub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
                if (channels.Any() != true) return;
                var ids = channels.Select(a => _registers.TryGetValue(a, out var tryval) ? tryval : null).Where(a => a != null).SelectMany(a => a.Keys).Distinct().ToArray();
                Cancel(ids);
            }

19 View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099

internal IDisposable Subscribe(bool psub, string[] channels, Action<string, string, object> handler)
            {
                if (_stoped) return new PubSubSubscribeDisposable(this, null);
                channels = channels?.Distinct().Where(a => !string.IsNullOrEmpty(a)).ToArray(); //In case of external modification
                if (channels?.Any() != true) return new PubSubSubscribeDisposable(this, null);

                var id = Guid.NewGuid();
                var time = DateTime.Now;
                var regkeys = channels.Select(a => psub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
                for (var a = 0; a < regkeys.Length; a++)
                {
                    ConcurrentDictionary<Guid, RegisterInfo> dict = null;
                    lock (_lock) dict = _registers.GetOrAdd(regkeys[a], k1 => new ConcurrentDictionary<Guid, RegisterInfo>());
                    dict.TryAdd(id, new RegisterInfo(id, handler, time));
                }
                lock (_lock)
                    _cancels.TryAdd(id, regkeys);
                var isnew = false;
                if (IsSubscribed == false)
                {
                    lock (_lock)
                    {
                        if (IsSubscribed == false)
                        {
                            _redisSocket = _topOwner.Adapter.GetRedisSocket(null);
                            IsSubscribed = isnew = true;
                        }
                    }
                }
                if (isnew)
                {
                    new Thread(() =>
                    {
                        _redisSocketReceiveTimeoutOld = _redisSocket.ReceiveTimeout;
                        _redisSocket.ReceiveTimeout = TimeSpan.Zero;
                        var timer = new Timer(state =>
                        {
                            _topOwner.Adapter.Refersh(_redisSocket); //防止 IdleBus 超时回收
                            try { _redisSocket.Write("PING"); } catch { }
                        }, null, 10000, 10000);
                        var readCmd = "PubSubRead".SubCommand(null).FlagReadbytes(false);
                        while (_stoped == false)
                        {
                            RedisResult rt = null;
                            try
                            {
                                rt = _redisSocket.Read(readCmd);
                            }
                            catch
                            {
                                Thread.CurrentThread.Join(100);
                                if (_cancels.Any()) continue;
                                break;
                            }
                            var val = rt.Value as object[];
                            if (val == null) continue; //special case

                            var val1 = val[0].ConvertTo<string>();
                            switch (val1)
                            {
                                case "pong":
                                case "punsubscribe":
                                case "unsubscribe":
                                    continue;
                                case "pmessage":
                                    OnData(val[1].ConvertTo<string>(), val[2].ConvertTo<string>(), val[3]);
                                    continue;
                                case "message":
                                    OnData(null, val[1].ConvertTo<string>(), val[2]);
                                    continue;
                            }
                        }
                        timer.Dispose();
                        lock (_lock)
                        {
                            IsSubscribed = false;
                            _redisSocket.ReceiveTimeout = _redisSocketReceiveTimeoutOld;
                            _redisSocket.ReleaseSocket();
                            _redisSocket.Dispose();
                            _redisSocket = null;
                        }
                    }).Start();
                }
                Call((psub ? "PSUBSCRIBE" : "SUBSCRIBE").Input(channels));
                return new PubSubSubscribeDisposable(this, () => Cancel(id));
            }

19 View Source File : CommandFlagsTests.cs
License : MIT License
Project Creator : 2881099

[Fact]
        public void Command()
        {
			string UFString(string text)
			{
				if (text.Length <= 1) return text.ToUpper();
				else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
			}

			var rt = cli.Command();
			//var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename");
			var flags = new List<string>();
			var flags7 = new List<string>();
			var diccmd = new Dictionary<string, (string[], string[])>();

			var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 =>
			{
				var a = a1 as object[];
				var cmd = a[0].ToString();
				var plen = int.Parse(a[1].ToString());
				var firstKey = int.Parse(a[3].ToString());
				var lastKey = int.Parse(a[4].ToString());
				var stepCount = int.Parse(a[5].ToString());

				var aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray();
				var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray();
				flags.AddRange(aflags);
				flags7.AddRange(fopts);

				diccmd.Add(cmd.ToUpper(), (aflags, fopts));

				var parms = "";
				if (plen > 1)
				{
					for (var x = 1; x < plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += $"string arg{x}, ";
					}
					parms = parms.Remove(parms.Length - 2);
				}
				if (plen < 0)
				{
					for (var x = 1; x < -plen; x++)
					{
						if (x == firstKey)
						{
							if (firstKey != lastKey) parms += "string[] keys, ";
							else parms += "string key, ";
						}
						else
						{
							if (firstKey != lastKey) parms += $"string[] arg{x}, ";
							else parms += $"string arg{x}, ";
						}
					}
					if (parms.Length > 0)
						parms = parms.Remove(parms.Length - 2);
				}

				return [email protected]"
//{string.Join(", ", a[2] as object[])}
//{string.Join(", ", a[6] as object[])}
public void {UFString(cmd)}({parms}) {{ }}";
			}));
			flags = flags.Distinct().ToList();
			flags7 = flags7.Distinct().ToList();


			var sboptions = new StringBuilder();
            foreach (var cmd in CommandSets._allCommands)
            {
                if (diccmd.TryGetValue(cmd, out var tryv))
                {
                    sboptions.Append([email protected]"
[""{cmd}""] = new CommandSets(");

                    for (var x = 0; x < tryv.Item1.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}");
                    }

                    sboptions.Append(", ");
                    for (var x = 0; x < tryv.Item2.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}");
                    }

                    sboptions.Append(", LocalStatus.none),");
                }
                else
                {
                    sboptions.Append([email protected]"
[""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), ");
                }
            }

            var optioncode = sboptions.ToString();
		}

19 View Source File : ImClient.cs
License : MIT License
Project Creator : 2881099

public void SendMessage(Guid senderClientId, IEnumerable<Guid> receiveClientId, object message, bool receipt = false)
    {
        receiveClientId = receiveClientId.Distinct().ToArray();
        Dictionary<string, ImSendEventArgs> redata = new Dictionary<string, ImSendEventArgs>();

        foreach (var uid in receiveClientId)
        {
            string server = SelectServer(uid);
            if (redata.ContainsKey(server) == false) redata.Add(server, new ImSendEventArgs(server, senderClientId, message, receipt));
            redata[server].ReceiveClientId.Add(uid);
        }
        var messageJson = JsonConvert.SerializeObject(message);
        foreach (var sendArgs in redata.Values)
        {
            OnSend?.Invoke(this, sendArgs);
            _redis.Publish($"{_redisPrefix}Server{sendArgs.Server}",
                JsonConvert.SerializeObject((senderClientId, sendArgs.ReceiveClientId, messageJson, sendArgs.Receipt)));
        }
    }

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

public static IEnumerable<string> FindConfigs(ISlnResult sln, SlnItems items)
            => FindAllConfigs(sln, items).Distinct();

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

public static void BuildLink()
        {
            List<replacedembly> replacedemblieList = new List<replacedembly>();
            replacedemblieList.Add(typeof(Object).replacedembly);
            replacedemblieList.Add(typeof(UnityEngine.Object).replacedembly);
            replacedemblieList.Add(typeof(Transform).replacedembly);
            replacedemblieList.Add(typeof(GameObject).replacedembly);
            replacedemblieList.Add(typeof(Image).replacedembly);
            replacedemblieList.Add(typeof(Init).replacedembly);
            string[] filePaths = Directory.GetFiles("replacedets", "*.dll", SearchOption.AllDirectories);
            foreach (string item in filePaths)
            {
                if (item.ToLower().Contains("editor") || item.ToLower().Contains("plugins"))
                {
                    continue;
                }
                replacedemblieList.Add(replacedembly.LoadFrom(item));
            }
            replacedemblieList = replacedemblieList.Distinct().ToList();
            XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
            XmlElement linkerElement = xmlDoreplacedent.CreateElement("linker");
            foreach (replacedembly item in replacedemblieList)
            {
                XmlElement replacedemblyElement = xmlDoreplacedent.CreateElement("replacedembly");
                replacedemblyElement.SetAttribute("fullname", item.GetName().Name);
                foreach (Type typeItem in item.GetTypes())
                {
                    if (typeItem.FullName == "Win32")
                    {
                        continue;
                    }
                    XmlElement typeElement = xmlDoreplacedent.CreateElement("type");
                    typeElement.SetAttribute("fullname", typeItem.FullName);
                    typeElement.SetAttribute("preserve", "all");
                    //增加子节点
                    replacedemblyElement.AppendChild(typeElement);
                }
                linkerElement.AppendChild(replacedemblyElement);
            }
            xmlDoreplacedent.AppendChild(linkerElement);
            string path = "replacedets/link.xml";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            xmlDoreplacedent.Save(path);
        }

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

public static List<string> ReadCSPROJ(string path, ref List<string> defineList, ref List<string> dllFilePathList)
        {
            List<string> csFilePathList = new List<string>();
            List<string> csprojPathList = new List<string>();
            XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
            xmlDoreplacedent.Load(path);
            XmlNode xmlNode = null;
            foreach (XmlNode item in xmlDoreplacedent.ChildNodes)
            {
                if (item.Name == "Project")
                {
                    xmlNode = item;
                    break;
                }
            }
            foreach (XmlNode item in xmlNode.ChildNodes)
            {
                if (item.Name == "PropertyGroup")
                {
                    foreach (XmlNode childItem in item.ChildNodes)
                    {
                        if (childItem.Name == "DefineConstants")
                        {
                            //宏引用
                            string define = childItem.InnerText;
                            defineList.AddRange(define.Split(';'));
                        }
                    }
                }
                if (item.Name == "ItemGroup")
                {
                    foreach (XmlNode childItem in item.ChildNodes)
                    {
                        if (childItem.Name == "Reference")
                        {
                            //dll引用
                            string dllFilePath = childItem.FirstChild.InnerText.Replace("\\", "/");
                            dllFilePathList.Add(dllFilePath);
                        }
                        if (childItem.Name == "Compile")
                        {
                            //cs引用
                            string csFilePath = childItem.Attributes[0].Value.Replace("\\", "/");
                            csFilePathList.Add(csFilePath);
                        }
                        if (childItem.Name == "ProjectReference")
                        {
                            //工程引用
                            string csprojFilePath = childItem.Attributes[0].Value;
                            csprojPathList.Add(csprojFilePath);
                        }
                    }
                }
            }
            //遍历工程引用
            foreach (string item in csprojPathList)
            {
                if (item.ToLower().Contains("editor"))
                {
                    continue;
                }
                ReadCSPROJ(item, ref defineList, ref dllFilePathList);
                string dllFilePath = "Library/Scriptreplacedemblies/" + item.Replace(".csproj", ".dll");
                if (File.Exists(dllFilePath))
                {
                    dllFilePathList.Add(dllFilePath);
                }
            }
            defineList = defineList.Distinct().ToList();
            //移除相关宏
            for (int i = defineList.Count - 1; i >= 0; i--)
            {
                if (defineList[i].Contains("UNITY_EDITOR"))
                {
                    defineList.RemoveAt(i);
                }
            }
            dllFilePathList = dllFilePathList.Distinct().ToList();
            return csFilePathList;
        }

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

public string[] ComputeUpdatereplacedets()
        {
            List<string> keyList = new List<string>();
            foreach (KeyValuePair<string, replacedetBundleData> item in serverreplacedetBundleConfig.replacedetBundleDataDict)
            {
                if (!localreplacedetBundleConfig.replacedetBundleDataDict.ContainsKey(item.Key))
                {
                    keyList.Add(item.Key);
                }
                if (item.Value.replacedetBundleHash != localreplacedetBundleConfig.replacedetBundleDataDict[item.Key].replacedetBundleHash)
                {
                    keyList.Add(item.Key);
                }
                if (item.Value.replacedetBundleCRC != localreplacedetBundleConfig.replacedetBundleDataDict[item.Key].replacedetBundleCRC)
                {
                    keyList.Add(item.Key);
                }
            }
            return keyList.Distinct().ToArray();
        }

19 View Source File : LastNames.cs
License : Apache License 2.0
Project Creator : 42skillz

private static IDictionary<Continent, string[]> RemoveDuplicates(Dictionary<Continent, string[]> perContinent)
        {
            var result = new Dictionary<Continent, string[]>();

            foreach (var continent in perContinent.Keys)
            {
                result[continent] = perContinent[continent].Distinct().ToArray();
            }

            return result;
        }

19 View Source File : PersonFuzzerWithPasswordShould.cs
License : Apache License 2.0
Project Creator : 42skillz

[TestCase(500)]
        public void GeneratePreplacedwords_of_various_sizes(int attempts)
        {
            var fuzzer = new Fuzzer();

            var generatedPreplacedwords = new List<string>();
            for (var i = 0; i < attempts; i++)
            {
                generatedPreplacedwords.Add(fuzzer.GeneratePreplacedword());
            }

            var generatedSizes = generatedPreplacedwords.Select(p => p.Length).Distinct();
            Check.That(generatedSizes.Count()).IsStrictlyGreaterThan(2);
        }

19 View Source File : GeographyExpert.cs
License : Apache License 2.0
Project Creator : 42skillz

public static string[] GiveMeCitiesOf(Country country)
        {
            return CitiesOfTheWorld
                .Where(cw => cw.Country == country)
                .Select(x => x.CityName)
                .Distinct()
                .ToArray();
        }

19 View Source File : GeographyExpert.cs
License : Apache License 2.0
Project Creator : 42skillz

public static StateProvinceArea[] GiveMeStateProvinceAreaOf(Country country)
        {
            return CitiesOfTheWorld
                .Where(cw => cw.Country == country)
                .Select(x => x.StateProvinceArea)
                .Distinct()
                .ToArray();
        }

19 View Source File : HierarchicalResolver.cs
License : MIT License
Project Creator : Abc-Arbitrage

private static void AddNode(Node root, LoggerDefinition logger, IAppender[] appenders)
        {
            var parts = logger.Name?.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>();
            var node = root;
            var path = "";

            foreach (var part in parts)
            {
                path = (path + "." + part).Trim('.');

                if (!node.Children.ContainsKey(part))
                {
                    node.Children[part] = new Node
                    {
                        Appenders = node.Appenders,
                        Level = node.Level,
                        LogEventPoolExhaustionStrategy = node.LogEventPoolExhaustionStrategy,
                        LogEventArgumentExhaustionStrategy = node.LogEventArgumentExhaustionStrategy
                    };
                }

                node = node.Children[part];
            }

            node.Appenders = (logger.IncludeParentAppenders ? appenders.Union(node.Appenders) : appenders).Distinct();
            node.LogEventPoolExhaustionStrategy = logger.LogEventPoolExhaustionStrategy;
            node.LogEventArgumentExhaustionStrategy = logger.LogEventArgumentExhaustionStrategy;
            node.Level = logger.Level;
        }

19 View Source File : SpeechInputHandlerInspector.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private static string[] GetDistinctRegisteredKeywords()
        {
            if (!MixedRealityToolkit.IsInitialized ||
                !MixedRealityToolkit.Instance.HasActiveProfile ||
                !MixedRealityToolkit.Instance.ActiveProfile.IsInputSystemEnabled ||
                MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile == null ||
                MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile.SpeechCommands.Length == 0)
            {
                return null;
            }

            List<string> keywords = new List<string>();
            var speechCommands = MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.SpeechCommandsProfile.SpeechCommands;
            for (var i = 0; i < speechCommands.Length; i++)
            {
                keywords.Add(speechCommands[i].Keyword);
            }

            return keywords.Distinct().ToArray();
        }

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

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

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

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

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

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

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

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

19 View Source File : BuilderEntityMetadata.cs
License : MIT License
Project Creator : abvogel

public void AppendM2MDataToEnreplacedy(String relationshipName, Dictionary<Guid, List<Guid>> relatedEnreplacedies)
        {
            if (!RelatedEnreplacedies.ContainsKey(relationshipName))
                this.RelatedEnreplacedies[relationshipName] = new Dictionary<Guid, List<Guid>>();

            foreach (var id in relatedEnreplacedies.Keys)
            {
                if (!RelatedEnreplacedies[relationshipName].ContainsKey(id))
                    this.RelatedEnreplacedies[relationshipName][id] = new List<Guid>();

                this.RelatedEnreplacedies[relationshipName][id].AddRange(relatedEnreplacedies[id]);
                this.RelatedEnreplacedies[relationshipName][id] = RelatedEnreplacedies[relationshipName][id].Distinct().ToList();
            }
        }

19 View Source File : HighlightTextBlock.cs
License : MIT License
Project Creator : Accelerider

private void RefreshInlines()
        {
            Inlines.Clear();

            if (string.IsNullOrEmpty(SourceText)) return;
            if (string.IsNullOrEmpty(QueriesText))
            {
                Inlines.Add(SourceText);
                return;
            }

            var sourceText = SourceText;
            var queries = QueriesText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            var intervals = from query in queries.Distinct()
                            from interval in GetQueryIntervals(sourceText, query)
                            select interval;
            var mergedIntervals = MergeIntervals(intervals.ToList());
            var fragments = SplitTextByOrderedDisjointIntervals(sourceText, mergedIntervals);

            Inlines.AddRange(GenerateRunElement(fragments));
        }

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

[OnSerializing]
        private void OnSerializing(StreamingContext context)
        {
            if (m_environmentVariables?.Count == 0)
            {
                m_environmentVariables = null;
            }

            if (m_defaults?.Count == 0)
            {
                m_defaults = null;
            }

            if (m_fileTable?.Count == 0)
            {
                m_fileTable = null;
            }

            if (m_maskHints?.Count == 0)
            {
                m_maskHints = null;
            }
            else if (m_maskHints != null)
            {
                m_maskHints = new List<MaskHint>(this.m_maskHints.Distinct());
            }

            if (m_variables?.Count == 0)
            {
                m_variables = null;
            }

            // todo: remove after feature-flag DistributedTask.EvaluateContainerOnRunner is enabled everywhere
            if (!string.IsNullOrEmpty(m_jobContainerResourceAlias))
            {
                JobContainer = new StringToken(null, null, null, m_jobContainerResourceAlias);
            }
        }

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

private static void CheckForFieldTypeAttributes(DacPropertyInfo property, SymbolreplacedysisContext symbolContext, PXContext pxContext,
														List<(AttributeInfo Attribute, List<FieldTypeAttributeInfo> Infos)> attributesWithInfos)
		{
			var (typeAttributesDeclaredOnDacProperty, typeAttributesWithConflictingAggregatorDeclarations) = FilterTypeAttributes();

			if (typeAttributesDeclaredOnDacProperty.Count == 0)
				return;

			if (typeAttributesWithConflictingAggregatorDeclarations.Count > 0)
			{
				RegisterDiagnosticForAttributes(symbolContext, pxContext, typeAttributesWithConflictingAggregatorDeclarations,
												Descriptors.PX1023_MultipleTypeAttributesOnAggregators);
			}

			if (typeAttributesDeclaredOnDacProperty.Count > 1)					
			{
				RegisterDiagnosticForAttributes(symbolContext, pxContext, typeAttributesDeclaredOnDacProperty,
												Descriptors.PX1023_MultipleTypeAttributesOnProperty);
			} 
			else if (typeAttributesWithConflictingAggregatorDeclarations.Count == 0)
			{
				var typeAttribute = typeAttributesDeclaredOnDacProperty[0];
				var fieldType = attributesWithInfos.First(attrWithInfo => attrWithInfo.Attribute.Equals(typeAttribute))
												   .Infos
												   .Where(info => info.IsFieldAttribute)
												   .Select(info => info.FieldType)
												   .Distinct()
												   .SingleOrDefault();
		
				CheckAttributeAndPropertyTypesForCompatibility(property, typeAttribute, fieldType, pxContext, symbolContext);
			}

			//-----------------------------------------------Local Functions---------------------------------------
			(List<AttributeInfo>, List<AttributeInfo>) FilterTypeAttributes()
			{
				List<AttributeInfo> typeAttributesOnDacProperty = new List<AttributeInfo>(2);
				List<AttributeInfo> typeAttributesWithInvalidAggregatorDeclarations = new List<AttributeInfo>(2);

				foreach (var (attribute, infos) in attributesWithInfos)
				{
					int countOfTypeAttributeInfos = infos.Count(info => info.IsFieldAttribute);

					if (countOfTypeAttributeInfos == 0)
						continue;

					typeAttributesOnDacProperty.Add(attribute);

					if (countOfTypeAttributeInfos == 1)
						continue;

					int countOfDeclaredFieldTypes = infos.Select(info => info.FieldType)
														 .Distinct()
														 .Count();
					if (countOfDeclaredFieldTypes > 1)
					{
						typeAttributesWithInvalidAggregatorDeclarations.Add(attribute);
					}
				}

				return (typeAttributesOnDacProperty, typeAttributesWithInvalidAggregatorDeclarations);
			}
		}

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

private static IEnumerable<ITypeSymbol> GetExtensionInAscendingOrder(ITypeSymbol dacType, ITypeSymbol dacExtension,
																			 INamedTypeSymbol extensionBaseType, PXContext pxContext, bool includeDac)
		{
			int dacIndex = extensionBaseType.TypeArguments.Length - 1;
			var extensions = new List<ITypeSymbol>(capacity: extensionBaseType.TypeArguments.Length);

			if (includeDac)
			{
				extensions.AddRange(dacType.GetDacWithBaseTypes().Reverse());
			}

			for (int i = dacIndex - 1; i >= 0; i--)
			{
				var baseExtension = extensionBaseType.TypeArguments[i];

				if (!baseExtension.IsDacExtension(pxContext))
					return Enumerable.Empty<ITypeSymbol>();

				extensions.Add(baseExtension);      //According to Platform team we shouldn't consider case when the extensions chaining mixes with .Net inheritance
			}

			extensions.AddRange(dacExtension.GetDacExtensionWithBaseTypes().Reverse());
			return extensions.Distinct();
		}

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

private static IEnumerable<ITypeSymbol> GetExtensionInAscendingOrder(ITypeSymbol graphType, ITypeSymbol graphExtension, 
																			 INamedTypeSymbol extensionBaseType, PXContext pxContext, bool includeGraph)
		{
			int graphIndex = extensionBaseType.TypeArguments.Length - 1;
			var extensions = new List<ITypeSymbol>(capacity: extensionBaseType.TypeArguments.Length);

			if (includeGraph)
			{
				extensions.AddRange(graphType.GetGraphWithBaseTypes().Reverse());
			}

			for (int i = graphIndex - 1; i >= 0; i--)
			{
				var baseExtension = extensionBaseType.TypeArguments[i];

				if (!baseExtension.IsPXGraphExtension(pxContext))
					return Enumerable.Empty<ITypeSymbol>();

				extensions.Add(baseExtension);		//According to Platform team we shouldn't consider case when the graph extensions chaining mixes with .Net inheritance
			}

			extensions.AddRange(graphExtension.GetExtensionWithBaseTypes().Reverse());
			return extensions.Distinct();
		}

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

private static IEnumerable<ITypeSymbol> GetExtensionInDescendingOrder(ITypeSymbol graphType, ITypeSymbol graphExtension, 
																			  INamedTypeSymbol extensionBaseType, PXContext pxContext, bool includeGraph)
		{
			int graphIndex = extensionBaseType.TypeArguments.Length - 1;
			var extensions = new List<ITypeSymbol>(capacity: extensionBaseType.TypeArguments.Length);
			extensions.AddRange(graphExtension.GetExtensionWithBaseTypes());

			for (int i = 0; i <= graphIndex - 1; i++)
			{
				var baseExtension = extensionBaseType.TypeArguments[i];

				if (!baseExtension.IsPXGraphExtension(pxContext))
					return Enumerable.Empty<ITypeSymbol>();

				extensions.Add(baseExtension);		//According to Platform team we shouldn't consider case when the graph extensions chaining mixes with .Net inheritance
			}

			if (includeGraph)
			{
				extensions.AddRange(graphType.GetGraphWithBaseTypes());
			}

			return extensions.Distinct();
		}

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

private ITypeSymbol ApplyRule(PrimaryDacRuleBase rule)
		{
			IEnumerable<ITypeSymbol> dacCandidates = null;
			IEnumerable<ISymbol> viewCandidates = null;

			switch (rule.RuleKind)
			{
				case PrimaryDacRuleKind.Graph:
					dacCandidates = (rule as GraphRuleBase)?.GetCandidatesFromGraphRule(this);
					break;
				case PrimaryDacRuleKind.View:
					var viewWithTypeCandidates = GetViewCandidatesFromViewRule(rule as ViewRuleBase);
					viewCandidates = viewWithTypeCandidates?.Select(view => view.Symbol);
					dacCandidates = viewWithTypeCandidates?.Select(view => view.Type.GetDacFromView(PxContext));
					break;
				case PrimaryDacRuleKind.Dac:
					var dacWithViewCandidates = GetCandidatesFromDacRule(rule as DacRuleBase);
					dacCandidates = dacWithViewCandidates?.Select(group => group.Key);
					viewCandidates = dacWithViewCandidates?.SelectMany(group => group);
					break;
				case PrimaryDacRuleKind.Action:
					dacCandidates = GetCandidatesFromActionRule(rule as ActionRuleBase);
					break;
			}

			if (dacCandidates.IsNullOrEmpty())
				return null;

			var dacCandidatesList = dacCandidates.Where(dac => dac != null).Distinct().ToList();
			ITypeSymbol primaryDac = null;

			if (rule.IsAbsolute && dacCandidatesList.Count == 1)
				primaryDac = dacCandidatesList[0];

			viewCandidates = viewCandidates ?? dacCandidatesList.SelectMany(dac => _dacWithViewsLookup[dac]);
			ScoreRuleForViewCandidates(viewCandidates, rule);
			return primaryDac;
		}

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

private static IEnumerable<ITypeSymbol> GetExtensionInDescendingOrder(ITypeSymbol dacType, ITypeSymbol dacExtension,
																			  INamedTypeSymbol extensionBaseType, PXContext pxContext, bool includeDac)
		{
			int dacIndex = extensionBaseType.TypeArguments.Length - 1;
			var extensions = new List<ITypeSymbol>(capacity: extensionBaseType.TypeArguments.Length);
			extensions.AddRange(dacExtension.GetDacExtensionWithBaseTypes());

			for (int i = 0; i <= dacIndex - 1; i++)
			{
				var baseExtension = extensionBaseType.TypeArguments[i];

				if (!baseExtension.IsDacExtension(pxContext))
					return Enumerable.Empty<ITypeSymbol>();

				extensions.Add(baseExtension);      //According to Platform team we shouldn't consider case when the extensions chaining mixes with .Net inheritance
			}

			if (includeDac)
			{
				extensions.AddRange(dacType.GetDacWithBaseTypes());
			}

			return extensions.Distinct();
		}

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

public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol type)
		{
			type.ThrowOnNull(nameof(type));

			if (type is ITypeParameterSymbol typeParameter)
			{
				IEnumerable<ITypeSymbol> constraintTypes = typeParameter.GetAllConstraintTypes(includeInterfaces: false)
																	    .SelectMany(GetBaseTypesImplementation)
																	    .Distinct();
				return typeParameter.ToEnumerable()
									.Concat(constraintTypes);
			}
			else
			{
				return type.GetBaseTypesAndThisImplementation();
			}		
		}

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

public static IEnumerable<INamedTypeSymbol> GetBaseTypes(this ITypeSymbol type)
		{
			type.ThrowOnNull(nameof(type));

			if (type is ITypeParameterSymbol typeParameter)
			{
				return typeParameter.GetAllConstraintTypes(includeInterfaces: false)
									.SelectMany(GetBaseTypesImplementation)
									.Distinct();
			}

			return type.GetBaseTypesImplementation();			
		}

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

public override void Dispose()
        {
            _taggersByType.Values.Distinct()
                                .ForEach(tagger => tagger.Dispose());
            base.Dispose();
        }

19 View Source File : TypeFinder.cs
License : MIT License
Project Creator : ad313

private List<replacedembly> GetreplacedembliesFromCurrentAppDomain()
        {
            var result = new List<replacedembly>();
            foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
            {
                if (Match(replacedembly))
                    result.Add(replacedembly);
            }
            return result.Distinct().ToList();
        }

19 View Source File : CSharpStyler.cs
License : GNU General Public License v3.0
Project Creator : adam8797

public override void SetKeywords(ScintillaNET.Scintilla scintilla)
        {
            scintilla.SetKeywords(0, "abstract partial as base break case catch checked continue default" +
                                     " delegate do else event explicit extern false finally fixed for foreach" +
                                     " goto if implicit in interface internal is lock namespace new null" +
                                     " operator out override params private protected public readonly ref return" +
                                     " sealed sizeof stackalloc switch this throw true try typeof unchecked unsafe" +
                                     " using virtual while volatile yield var async await" +
                                     " object bool byte char clreplaced const decimal double enum float int long sbyte short" +
                                     " static string struct uint ulong ushort void dynamic ");


            var builtInTypeNames = typeof(string).replacedembly.GetTypes()
                .Where(t => t.IsPublic && t.IsVisible)
                .Select(t => new {t.Name, Length = t.Name.IndexOf('`')}) // remove generic type from "List`1"
                .Select(x => x.Length == -1 ? x.Name : x.Name.Substring(0, x.Length))
                .Distinct();

            scintilla.SetKeywords(1, string.Join(" ", builtInTypeNames));
        }

19 View Source File : Grammar.cs
License : MIT License
Project Creator : adamant

public IEnumerable<GrammarRule> AncestorRules(GrammarRule rule)
        {
            var parents = ParentRules(rule).ToList();
            return parents.Concat(parents.SelectMany(AncestorRules)).Distinct();
        }

19 View Source File : TreeCodeTemplate.custom.cs
License : MIT License
Project Creator : adamant

private IEnumerable<string> OrderedNamespaces()
        {
            return grammar.UsingNamespaces
                          .Append("System.Diagnostics.Codereplacedysis")
                          .Append("ExhaustiveMatching")
                          .Distinct()
                          .OrderBy(v => v, NamespaceComparer.Instance);
        }

19 View Source File : Parser.cs
License : MIT License
Project Creator : adamant

private static IEnumerable<GrammarRule> GetRules(List<string> lines)
        {
            var ruleLines = lines.Select(l => l.Trim())
                                 .Where(l => !l.StartsWith(Program.DirectiveMarker, StringComparison.InvariantCulture)
                                            && !l.StartsWith("//", StringComparison.InvariantCulture)
                                            && !string.IsNullOrWhiteSpace(l))
                                 .Select(l => l.TrimEnd(';')) // TODO error if no semicolon
                                 .ToList()!;
            foreach (var ruleLine in ruleLines)
            {
                var equalSplit = ruleLine.Split('=');
                if (equalSplit.Length > 2)
                    throw new FormatException($"Too many equal signs on line: '{ruleLine}'");
                var declaration = equalSplit[0];
                var (nonterminal, parents) = ParseDeclaration(declaration);
                var definition = equalSplit.Length == 2 ? equalSplit[1].Trim() : null;
                var properties = ParseDefinition(definition).ToList();
                if (properties.Select(p => p.Name).Distinct().Count() != properties.Count)
                    throw new FormatException($"Rule for {nonterminal} contains duplicate property definitions");

                yield return new GrammarRule(nonterminal, parents, properties);
            }
        }

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

private static PositiveRulesCollectValues CalculatePositiveRulesCollectCountValue(
            IEnumerable<DmnDecisionTableRule> positiveRules,
            DmnDecisionTableRuleExecutionResults results)
        {
            var count = positiveRules.ToList()
                 .Select(r => results.GetResult(r, r.Outputs[0])?.Value?.ToString())
                 .Where(v => v != null)
                 .Distinct()
                 .ToList()
                 .Count;

            return new PositiveRulesCollectValues(0, 0, 0, count);
        }

19 View Source File : MessageHandlerContainer.cs
License : MIT License
Project Creator : AdemCatamak

private static List<Type> GetPayloadTypes(Type messageHandlerType)
        {
            List<Type> payloadTypes = new List<Type>();
            foreach (Type interfaceType in messageHandlerType.GetInterfaces())
            {
                if (interfaceType.IsGenericType
                 && interfaceType.GetGenericTypeDefinition() == typeof(IMessageHandler<>))
                {
                    payloadTypes.Add(interfaceType.GetGenericArguments()[0]);
                }
            }

            return payloadTypes.Distinct().ToList();
        }

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

private static CacheEntryChangeMonitor GetChangeMonitor(ObjectCache cache, string[] monitorKeys, string regionName)
		{
			if (!monitorKeys.Any()) return null;

			// Only take the dependencies that currently exist in the cache, some may have been invalidated in the interim.
			// Also filter out output cache secondary dependencies.
			var filteredKeys = monitorKeys.Where(key => cache.Contains(key, regionName) && !key.StartsWith(_outputCacheSecondaryDependencyPrefix)).Distinct();
			if (!filteredKeys.Any())
			{
				return null;
			}

			// For each output cache dependency, create a secondary dependency, this allows callers to invalidate just the output cache without also invalidating
			// other cache items which could be in dirty state.
			var includingSecondaryKeys = new List<string>();
			foreach (var filteredKey in filteredKeys)
			{
				// Each secondary dependency should be dependent on the primary dependency.
				var policy = new CacheItemPolicy();
				policy.ChangeMonitors.Add(cache.CreateCacheEntryChangeMonitor(new[] { filteredKey }, regionName));
				var secondaryDependencyKey = GetSecondaryDependencyKey(filteredKey);
				cache.AddOrGetExisting(secondaryDependencyKey, string.Empty, policy, regionName);
				includingSecondaryKeys.Add(secondaryDependencyKey);
			}
			includingSecondaryKeys.AddRange(filteredKeys);

			return cache.CreateCacheEntryChangeMonitor(includingSecondaryKeys, regionName);
		}

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

public static IEnumerable<Enreplacedy> GetActiveCasesForContactByAccountId(this OrganizationServiceContext context, EnreplacedyReference contact, Guid accountid)
		{
			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			// Get cases where the customer is the account of replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
			var accountcases = from incident in context.CreateQuery("incident")
				join caseaccess in context.CreateQuery("adx_caseaccess")
				on incident.GetAttributeValue<EnreplacedyReference>("customerid") equals caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid")
				where caseaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
					&& caseaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Account
					&& caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
				where incident.GetAttributeValue<OptionSetValue>("statecode") != null && incident.GetAttributeValue<OptionSetValue>("statecode").Value == (int)IncidentState.Active
				select incident;

			// Get cases where the customer is a contact and where the parent customer of the contact is an account replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
			var parentaccountcases = from incident in context.CreateQuery("incident")
				join c in context.CreateQuery("contact") on incident.GetAttributeValue<EnreplacedyReference>("customerid").Id equals c.GetAttributeValue<Guid>("contactid")
				join account in context.CreateQuery("account") on c.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id equals account.GetAttributeValue<Guid>("accountid")
				join caseaccess in context.CreateQuery("adx_caseaccess") on account.GetAttributeValue<Guid>("accountid") equals caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid").Id
				where caseaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
					&& caseaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Account
					&& caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
				where incident.GetAttributeValue<OptionSetValue>("statecode") != null && incident.GetAttributeValue<OptionSetValue>("statecode").Value == (int)IncidentState.Active
				select incident;

			var cases = accountcases.AsEnumerable().Union(parentaccountcases.AsEnumerable()).Distinct();

			return cases;
		}

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

public static IEnumerable<Enreplacedy> GetClosedCasesForContactByAccountId(this OrganizationServiceContext context, EnreplacedyReference contact, Guid accountid)
		{
			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			// Get cases where the customer is the account of replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
			var accountcases = from incident in context.CreateQuery("incident")
				join caseaccess in context.CreateQuery("adx_caseaccess")
				on incident.GetAttributeValue<Guid>("customerid") equals caseaccess.GetAttributeValue<Guid>("adx_accountid")
				where caseaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
					&& caseaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Account
					&& caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
				where incident.GetAttributeValue<OptionSetValue>("statecode") != null && incident.GetAttributeValue<OptionSetValue>("statecode").Value != (int)IncidentState.Active
				select incident;

			// Get cases where the customer is a contact and where the parent customer of the contact is an account replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
			var parentaccountcases = from incident in context.CreateQuery("incident")
				join c in context.CreateQuery("contact") on incident.GetAttributeValue<EnreplacedyReference>("customerid").Id equals c.GetAttributeValue<Guid>("contactid")
				join account in context.CreateQuery("account") on c.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id equals account.GetAttributeValue<Guid>("accountid")
				join caseaccess in context.CreateQuery("adx_caseaccess") on account.GetAttributeValue<Guid>("accountid") equals caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid").Id
				where caseaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
					&& caseaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Account
					&& caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
				where incident.GetAttributeValue<OptionSetValue>("statecode") != null && incident.GetAttributeValue<OptionSetValue>("statecode").Value != (int)IncidentState.Active
				select incident;

			var cases = accountcases.AsEnumerable().Union(parentaccountcases.AsEnumerable()).Distinct();

			return cases;
		}

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

public static DiscountCodeValidationResult ValidateDiscountCode(OrganizationServiceContext context, Guid quoteId, string code)
		{
			var errorCode = DiscountErrorCode.Unknown;
			var isValid = false;
			var discountableQuoteProductIds = new List<Guid>();
			if (string.IsNullOrWhiteSpace(code))
			{
				var result = new DiscountCodeValidationResult
								{
									ErrorCode = DiscountErrorCode.CodeNotSpecified
								};
				return result;
			}

			var quote = context.CreateQuery("quote").FirstOrDefault(q => q.GetAttributeValue<Guid>("quoteid") == quoteId);

			if (quote == null)
			{
				var result = new DiscountCodeValidationResult
								{
									ErrorCode = DiscountErrorCode.QuoteNotFound,
								};
				return result;
			}

			var existingDiscountCodes = quote.GetAttributeValue<string>("adx_discountcodes") ?? string.Empty;

			if (existingDiscountCodes.Contains(code))
			{
				var result = new DiscountCodeValidationResult
								{
									ErrorCode = DiscountErrorCode.AlreadyApplied,
								};
				return result;
			}

			var prefreightAmount = GetDecimalFromMoney(quote, "totalamountlessfreight");

			if (prefreightAmount <= 0)
			{
				var result = new DiscountCodeValidationResult
								{
									ErrorCode = DiscountErrorCode.ZeroAmount,
								};
				return result;
			}

			var discountErrors = new List<DiscountError>();

			var orderScopedDiscounts =
				context.CreateQuery("adx_discount")
					.Where(
						d =>
							d.GetAttributeValue<OptionSetValue>("statecode").Value == 0 &&
							(d.GetAttributeValue<OptionSetValue>("adx_scope") != null &&
							 d.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)DiscountScope.Order) &&
							((d.GetAttributeValue<DateTime?>("adx_startdate") == null ||
							  d.GetAttributeValue<DateTime?>("adx_startdate") <= DateTime.UtcNow) &&
							 (d.GetAttributeValue<DateTime?>("adx_enddate") == null ||
							  d.GetAttributeValue<DateTime?>("adx_enddate") >= DateTime.UtcNow)) &&
							d.GetAttributeValue<string>("adx_code") == code)
					.ToList();

			if (orderScopedDiscounts.Any())
			{
				var discountPercentage = quote.GetAttributeValue<decimal?>("discountpercentage") ?? 0;
				var discountAmount = GetDecimalFromMoney(quote, "discountamount");
				var newDiscountPercentage = discountPercentage;
				var newDiscountAmount = discountAmount;
				var appliedDiscounts = (from d in context.CreateQuery("adx_discount")
										join dq in context.CreateQuery("adx_discount_quote") on
											d.GetAttributeValue<Guid>("adx_discountid") equals dq.GetAttributeValue<Guid>("adx_discountid")
										where dq.GetAttributeValue<Guid>("quoteid") == quote.Id
										select d).ToList();
				var newDiscounts = new List<Enreplacedy>();

				foreach (var discount in orderScopedDiscounts)
				{
					var applied = appliedDiscounts.Any(d => d.GetAttributeValue<Guid>("adx_discountid") == discount.Id);

					if (applied)
					{
						discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.AlreadyApplied });
						continue;
					}

					var minimumPurchaseAmount = GetDecimalFromMoney(discount, "adx_minimumpurchaseamount");
					var maximumRedemptions = discount.GetAttributeValue<int?>("adx_maximumredemptions").GetValueOrDefault(0);
					var redemptions = discount.GetAttributeValue<int?>("adx_redemptions").GetValueOrDefault(0);
					var typeOption = discount.GetAttributeValue<OptionSetValue>("adx_type");
					decimal percentage = 0;
					decimal amount = 0;

					if (typeOption == null)
					{
						discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
						continue;
					}

					switch (typeOption.Value)
					{
						case (int)DiscountType.Percentage:
							percentage = discount.GetAttributeValue<decimal?>("adx_percentage") ?? 0;
							break;
						case (int)DiscountType.Amount:
							amount = GetDecimalFromMoney(discount, "adx_amount");
							break;
						default:
							discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
							continue;
					}

					if (minimumPurchaseAmount > 0 && prefreightAmount < minimumPurchaseAmount)
					{
						discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MinimumAmountNotMet });
					}
					else if (maximumRedemptions > 0 && redemptions >= maximumRedemptions)
					{
						discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MaximumRedemptions });
					}
					else
					{
						newDiscountPercentage += percentage;
						newDiscountAmount += amount;
						appliedDiscounts.Add(discount);
						newDiscounts.Add(discount);
					}
				}

				if (newDiscountPercentage != discountPercentage || newDiscountAmount != discountAmount)
				{
					isValid = true;
				}
			}

			if (!isValid)
			{
				// Check for valid quotedetail items

				var quoteDetails =
					context.CreateQuery("quotedetail")
							.Where(q => q.GetAttributeValue<EnreplacedyReference>("quoteid").Equals(quote.ToEnreplacedyReference()))
							.ToList();

				if (quoteDetails.Any())
				{
					var priceList = quote.GetAttributeValue<EnreplacedyReference>("pricelevelid");

					var productScopeDiscounts =
						context.CreateQuery("adx_discount")
							.Where(
								d =>
									d.GetAttributeValue<OptionSetValue>("statecode").Value == 0 &&
									(d.GetAttributeValue<OptionSetValue>("adx_scope") != null &&
									 d.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)DiscountScope.Product) &&
									((d.GetAttributeValue<DateTime?>("adx_startdate") == null ||
									  d.GetAttributeValue<DateTime?>("adx_startdate") <= DateTime.UtcNow) &&
									 (d.GetAttributeValue<DateTime?>("adx_enddate") == null ||
									  d.GetAttributeValue<DateTime?>("adx_enddate") >= DateTime.UtcNow)) &&
									d.GetAttributeValue<string>("adx_code") == code)
							.ToList();

					if (!productScopeDiscounts.Any())
					{
						var result = new DiscountCodeValidationResult
										{
											ErrorCode = DiscountErrorCode.DoesNotExist,
											DiscountErrors = discountErrors
										};
						return result;
					}

					foreach (var quotedetail in quoteDetails)
					{
						var baseAmount = GetDecimalFromMoney(quotedetail, "baseamount");

						if (baseAmount <= 0)
						{
							discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.ZeroAmount });
							continue;
						}

						var appliedDiscounts = (from d in context.CreateQuery("adx_discount")
												join i in context.CreateQuery("adx_discount_quotedetail") on
													d.GetAttributeValue<Guid>("adx_discountid") equals i.GetAttributeValue<Guid>("adx_discountid")
												where i.GetAttributeValue<Guid>("quotedetailid") == quotedetail.Id
												select d).ToList();
						var newDiscounts = new List<Enreplacedy>();
						var discountAmount = GetDecimalFromMoney(quotedetail, "manualdiscountamount");
						var newDiscountAmount = discountAmount;

						foreach (var discount in productScopeDiscounts)
						{
							var applied = appliedDiscounts.Any(d => d.GetAttributeValue<Guid>("adx_discountid") == discount.Id);

							if (applied)
							{
								discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.AlreadyApplied });
								continue;
							}

							var discountProductPriceLevel = (from pl in context.CreateQuery("productpricelevel")
															join dp in context.CreateQuery("adx_discount_productpricelevel") on
																pl.GetAttributeValue<Guid>("productpricelevelid") equals dp.GetAttributeValue<Guid>("productpricelevelid")
															where dp.GetAttributeValue<Guid>("adx_discountid") == discount.Id
															where pl.GetAttributeValue<EnreplacedyReference>("pricelevelid").Equals(priceList)
															select pl).ToList();

							if (!discountProductPriceLevel.Any())
							{
								continue;
							}

							var quotedetailid = quotedetail.Id;
							var quoteProductDiscounts = (from d in discountProductPriceLevel
														join q in
															context.CreateQuery("quotedetail")
																	.Where(q => q.GetAttributeValue<Guid>("quotedetailid") == quotedetailid)
															on
															new
																{
																	productid = d.GetAttributeValue<EnreplacedyReference>("productid"),
																	uomid = d.GetAttributeValue<EnreplacedyReference>("uomid")
																} equals
															new
																{
																	productid = q.GetAttributeValue<EnreplacedyReference>("productid"),
																	uomid = q.GetAttributeValue<EnreplacedyReference>("uomid")
																}
														select q).ToList();

							if (!quoteProductDiscounts.Any())
							{
								continue;
							}

							var maximumRedemptions = discount.GetAttributeValue<int?>("adx_maximumredemptions").GetValueOrDefault(0);
							var redemptions = discount.GetAttributeValue<int?>("adx_redemptions").GetValueOrDefault(0);
							var typeOption = discount.GetAttributeValue<OptionSetValue>("adx_type");
							decimal amount = 0;

							if (typeOption == null)
							{
								discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
								continue;
							}

							switch (typeOption.Value)
							{
								case (int)DiscountType.Percentage:
									var percentage = discount.GetAttributeValue<decimal?>("adx_percentage") ?? 0;
									if (percentage > 0 && baseAmount > 0)
									{
										amount = baseAmount * percentage / 100;
									}
									break;
								case (int)DiscountType.Amount:
									amount = GetDecimalFromMoney(discount, "adx_amount");
									break;
								default:
									discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.InvalidDiscountConfiguration });
									continue;
							}

							if (maximumRedemptions > 0 && redemptions >= maximumRedemptions)
							{
								discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.MaximumRedemptions });
								continue;
							}

							newDiscountAmount += amount;
							appliedDiscounts.Add(discount);
							newDiscounts.Add(discount);
							discountableQuoteProductIds.Add(quotedetail.Id);
						}

						if (newDiscountAmount == discountAmount)
						{
							continue;
						}

						isValid = true;

						break;
					}
				}
			}

			if (!isValid && !discountErrors.Any())
			{
				discountErrors.Add(new DiscountError { ErrorCode = DiscountErrorCode.NotApplicable });
				errorCode = DiscountErrorCode.NotApplicable;
			}

			return new DiscountCodeValidationResult(isValid)
						{
							ErrorCode = errorCode,
							ExistingDiscountCodes = existingDiscountCodes,
							DiscountableQuoteProductIds = discountableQuoteProductIds.Distinct(),
							DiscountErrors = discountErrors
						};
		}

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

public static Dictionary<Guid, Tuple<int, int>> FetchIdeaVoteCountsForUser(this OrganizationServiceContext serviceContext, IEnumerable<Enreplacedy> ideaEnreplacedies, HttpContextBase httpContext, EnreplacedyReference portalUser)
		{
			if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
			{
				return new Dictionary<Guid, Tuple<int, int>>();
			}

			var ideas = ideaEnreplacedies.ToArray();

			var fetchXml = XDoreplacedent.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<enreplacedy name=""feedback"">
						<attribute name=""rating"" alias=""votesum"" aggregate=""sum"" />
						<attribute name=""rating"" alias=""value"" groupby=""true"" />
						<filter type=""or"" />
						<filter type=""and"">
							<condition attribute=""statecode"" operator=""eq"" value=""0"" />
							<condition attribute=""rating"" operator=""not-null"" />
					    </filter>
						<link-enreplacedy name=""adx_idea"" from=""adx_ideaid"" to=""regardingobjectid"">
							<attribute name=""adx_ideaforumid"" alias=""ideaforumid"" groupby=""true"" />
							<attribute name=""adx_ideaid"" alias=""ideaid"" groupby=""true"" />
							<attribute name=""statuscode"" alias=""statuscode"" groupby=""true"" />
							<filter type=""or"" />
							<filter type=""and"">
								<condition attribute=""statecode"" operator=""eq"" value=""0"" />
							</filter>
						</link-enreplacedy>
					</enreplacedy>
				</fetch>");

			var enreplacedy = fetchXml.Descendants("enreplacedy").First();

			var orFilter = enreplacedy.Descendants("filter").First();

			if (!string.IsNullOrEmpty(httpContext.Request.AnonymousID))
			{
				orFilter.AddFetchXmlFilterCondition("createdbycontact", "eq", httpContext.Request.AnonymousID);
			}

			if (portalUser != null)
			{
				orFilter.AddFetchXmlFilterCondition("createdbycontact", "eq", portalUser.Id.ToString());
			}
			else
			{
				// author_url?
				//orFilter.AddFetchXmlFilterCondition("adx_createdbyipaddress", "eq", httpContext.Request.UserHostAddress);
			}

			var ideaForumFilter = enreplacedy.Descendants("link-enreplacedy").First().Descendants("filter").First();

			foreach (var id in ideas.Where(idea => idea.GetAttributeValue<EnreplacedyReference>("adx_ideaforumid") != null).Select(idea => idea.GetAttributeValue<EnreplacedyReference>("adx_ideaforumid").Id).Distinct())
			{
				ideaForumFilter.AddFetchXmlFilterCondition("adx_ideaforumid", "eq", id.ToString());
			}

			var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));

			var ideaForumActiveVoteCounts = response.Enreplacedies
				.Where(result => result.GetAttributeAliasedValue<int>("statuscode") == 1)
				.GroupBy(
					result => result.GetAttributeAliasedValue<Guid>("ideaforumid"),
					result => Math.Abs(result.GetAttributeAliasedValue<int>("votesum")))
				.ToDictionary(g => g.Key, ints => ints.Sum());

			var results = ideas.ToDictionary(
				idea => idea.Id,
				idea =>
				{
					int ideaForumActiveVoteCountValue;
					var ideaForumActiveVoteCount = idea.GetAttributeValue<EnreplacedyReference>("adx_ideaforumid") == null ? 0 : ideaForumActiveVoteCounts.TryGetValue(idea.GetAttributeValue<EnreplacedyReference>("adx_ideaforumid").Id, out ideaForumActiveVoteCountValue)
						? ideaForumActiveVoteCountValue
						: 0;

					var ideaVoteCount = response.Enreplacedies
						.Where(result => result.GetAttributeAliasedValue<Guid>("ideaid") == idea.Id)
						.Sum(result => Math.Abs(result.GetAttributeAliasedValue<int>("votesum")));

					return new Tuple<int, int>(ideaForumActiveVoteCount, ideaVoteCount);
				});

			return results;
		}

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

private static IEnumerable<Enreplacedy> CreateIdeaEnreplacediesFromAliasedValues(IEnumerable<Enreplacedy> results)
		{
			var ideas = results
				.Select(result =>
				{
					var idea = new Enreplacedy("adx_idea");

					foreach (var attribute in result.Attributes.Where(attribute => attribute.Value is AliasedValue && attribute.Key.StartsWith("idea.")))
					{
						idea[attribute.Key.Substring(5)] = ((AliasedValue)attribute.Value).Value;
					}

					idea.Id = idea.GetAttributeValue<Guid>("adx_ideaid");

					return idea;
				}).ToArray();

			var distinctIdeaIds = ideas.Select(e => e.Id).Distinct();
			var distinctIdeas = distinctIdeaIds.Select(id => ideas.First(idea => idea.Id == id));

			return distinctIdeas;
		}

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

private IEnumerable<IMarketingList> Unsubscribe(string emailAddress, IEnumerable<string> listIds = null)
		{
			var context = Dependencies.GetServiceContextForWrite();

			var lists = GetMarketingLists(emailAddress).Where(l => listIds == null || listIds.Select(Guid.Parse).Contains(l.Id));

			var unsubscribedLists = new List<IMarketingList>();

			foreach (var list in lists)
			{
				unsubscribedLists.Add(list);
				foreach (var subscriber in list.Subscribers)
				{
					context.RemoveMemberList(list.Id, subscriber.Id);
				}
			}

			return unsubscribedLists.Distinct();
		}

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

public static IEnumerable<Enreplacedy> GetOpportunitiesForContactByAccountId(this OrganizationServiceContext context, Enreplacedy contact, Guid accountid)
		{
			contact.replacedertEnreplacedyName("contact");

			if (contact == null)
			{
				return Enumerable.Empty<Enreplacedy>();
			}

			// Get opportunities where the Partner is the account of replacedigned to any opportunity access rule for the current contact that allows read and scoped to account
			var accountopportunities = from opportunity in context.CreateQuery("opportunity")
									   join opportunityaccess in context.CreateQuery("adx_opportunitypermissions")
									   on opportunity.GetAttributeValue<EnreplacedyReference>("msa_partnerid") equals opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid")
									   where opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference()
									   && opportunityaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && opportunityaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && opportunityaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)OpportunityAccessScope.Account
									   && opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
									   select opportunity;

			// Get cases where the partner contact is not null and where the parent customer of the contact is an account replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
			var parentaccountopportunities = from opportunity in context.CreateQuery("opportunity")
											 join c in context.CreateQuery("contact") on opportunity.GetAttributeValue<EnreplacedyReference>("msa_partneroppid").Id equals c.GetAttributeValue<Guid>("contactid")
											 join account in context.CreateQuery("account") on c.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id equals account.GetAttributeValue<Guid>("accountid")
											 join opportunityaccess in context.CreateQuery("adx_opportunitypermissions") on account.GetAttributeValue<Guid>("accountid") equals opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid").Id
											 where opportunity.GetAttributeValue<EnreplacedyReference>("msa_partneroppid") != null
											 where c.GetAttributeValue<EnreplacedyReference>("parentcustomerid") != null
											 where opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference()
											 && opportunityaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && opportunityaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && opportunityaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)OpportunityAccessScope.Account
											 && opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
											 select opportunity;

			var opportunities = accountopportunities.AsEnumerable().Union(parentaccountopportunities.AsEnumerable()).Distinct();

			return opportunities;
		}

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

private static IEnumerable<string> SelectAllForumsWebRoles(Guid enreplacedyId, ContentMap contentMap)
		{
			EnreplacedyNode enreplacedy;

			// Get the Forums from the content map
			if (!contentMap.TryGetValue(new EnreplacedyReference("adx_communityforum", enreplacedyId), out enreplacedy))
			{
				return Enumerable.Empty<string>();
			}

			var forum = enreplacedy as ForumNode;
			if (forum == null)
			{
				return Enumerable.Empty<string>();
			}

			var changeRules =
				forum.ForumAccessPermissions.Where(fa => fa.Right == ForumAccessPermissionNode.RightOption.GrantChange)
					.SelectMany(fa => fa.WebRoles.Select(wr => wr.Name));

			var readRules =
				forum.ForumAccessPermissions.Where(fa => fa.Right == ForumAccessPermissionNode.RightOption.RestrictRead)
					.SelectMany(fa => fa.WebRoles.Select(wr => wr.Name)).ToList();

			bool anyInheritedReadRestrictRules = false;

			// If it has a parent page we will need to inspect to see if they have different read rules.
			if (forum.ParentPage != null)
			{
				var parentPageWebRoles = GetRulesForPage(forum.ParentPage).Distinct().ToList();
				anyInheritedReadRestrictRules =
				parentPageWebRoles.Any(
					rule =>
					{
						if (rule.Right == null)
						{
							return false;
						}
						return rule.Right.Value.ToEnum<ForumAccessPermissionProvider.RightOption>()
						   == ForumAccessPermissionProvider.RightOption.RestrictRead;
					});

				// If Both the webpage tree do not have read restrict rules then give access to all.  
				var parentPageWebRoleNames = anyInheritedReadRestrictRules || readRules.Any()
						? parentPageWebRoles.SelectMany(
							webPageAccessControlRuleNode => webPageAccessControlRuleNode.WebRoles,
								(webPageAccessControlRuleNode, webRole) => webRole.Name).Distinct()
						: new[] { AllowAccessDefaultValue };

				// If there are no read restrict rules then we just follow the parents roles and change roles
				if (!readRules.Any() && !anyInheritedReadRestrictRules)
				{
					return changeRules.Concat(parentPageWebRoleNames).Distinct();
				}

				readRules = parentPageWebRoleNames.Union(readRules).ToList();
			}

			// Since it didn't have a parent page make sure there isn't a read restrict rule if no then give access to all. 
			return readRules.Any() || anyInheritedReadRestrictRules ? changeRules.Concat(readRules).Distinct() : new[] { AllowAccessDefaultValue };
		}

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

public static IEnumerable<Enreplacedy> GetOpportunitiesForContact(this OrganizationServiceContext context, Enreplacedy contact)
		{
			var accounts = context.GetAccountsRelatedToOpportunityAccessForContact(contact).OrderBy(a => a.GetAttributeValue<string>("name"));

			var opportunities = context.GetOpportunitiesSpecificToContact(contact);

			return accounts.Aggregate(opportunities, (current, account) => current.Union(context.GetOpportunitiesForContactByAccountId(contact, (Guid)account.GetAttributeValue<Guid>("accountid"))).Distinct());
		}

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

protected virtual Dictionary<Guid, T> GetEnreplacedyFieldValueByGuids<T>(IEnumerable<Guid> enreplacedyGuids, string enreplacedyName, string enreplacedyFieldName, string enreplacedyFieldNameForGuid)
		{
			var enreplacedyFieldsFetch = new Fetch
			{
				Distinct = true,
				Enreplacedy = new FetchEnreplacedy
				{
					Name = enreplacedyName,
					Attributes = new List<FetchAttribute>
					{
						new FetchAttribute(enreplacedyFieldNameForGuid),
						new FetchAttribute(enreplacedyFieldName)
					},
					Filters = new List<Xrm.Services.Query.Filter>()
					{
						new Xrm.Services.Query.Filter()
						{
							Type = LogicalOperator.And,
							Conditions = new List<Condition>()
							{
								new Condition
								{
									Attribute = enreplacedyFieldNameForGuid,
									Operator = ConditionOperator.In,
									Values = enreplacedyGuids.Distinct().Cast<object>().ToList()
								}
							}
						}
					}
				}
			};
			var portalContext = PortalCrmConfigurationManager.CreatePortalContext();
			using (var serviceContext = portalContext.ServiceContext)
			{
				var enreplacedyCollection = enreplacedyFieldsFetch.Execute(serviceContext as IOrganizationService);
				return enreplacedyCollection.Enreplacedies.ToDictionary(enreplacedy => enreplacedy.GetAttributeValue<Guid>(enreplacedyFieldNameForGuid), enreplacedy => enreplacedy.GetAttributeValue<T>(enreplacedyFieldName));
			}
		}

See More Examples