System.Collections.Generic.IEnumerable.AsEnumerable()

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

1130 Examples 7

19 Source : ExpressionResolverTests.cs
with MIT License
from 17MKH

[Fact]
        public void ResolveExpressionTest21()
        {
            var ids = new List<int> { 10, 15 };

            Expression<Func<ArticleEnreplacedy, bool>> exp = m => ids.AsEnumerable().Contains(m.Id);

            var parameters = new QueryParameters();
            var sql = ExpressionResolver.Resolve(_queryBody, exp, parameters);

            replacedert.Equal("`Id` IN (10,15)", sql);
        }

19 Source : MultiTableExpressionResolverTests.cs
with MIT License
from 17MKH

[Fact]
        public void ResolveExpressionTest21()
        {
            var ids = new List<int> { 10, 15 };

            Expression<Func<IQueryableJoins<ArticleEnreplacedy, CategoryEnreplacedy>, bool>> exp = m => ids.AsEnumerable().Contains(m.T1.Id);

            var parameters = new QueryParameters();
            var sql = ExpressionResolver.Resolve(_queryBody, exp, parameters);

            replacedert.Equal("T1.`Id` IN (10,15)", sql);
        }

19 Source : ExpressionResolverTests.cs
with MIT License
from 17MKH

[Fact]
        public void ResolveExpressionTest21()
        {
            var ids = new List<int> { 10, 15 };

            Expression<Func<ArticleEnreplacedy, bool>> exp = m => ids.AsEnumerable().Contains(m.Id);

            var parameters = new QueryParameters();
            var sql = ExpressionResolver.Resolve(_queryBody, exp, parameters);

            replacedert.Equal("[Id] IN (10,15)", sql);
        }

19 Source : MultiTableExpressionResolverTests.cs
with MIT License
from 17MKH

[Fact]
        public void ResolveExpressionTest21()
        {
            var ids = new List<int> { 10, 15 };

            Expression<Func<IQueryableJoins<ArticleEnreplacedy, CategoryEnreplacedy>, bool>> exp = m => ids.AsEnumerable().Contains(m.T1.Id);

            var parameters = new QueryParameters();
            var sql = ExpressionResolver.Resolve(_queryBody, exp, parameters);

            replacedert.Equal("T1.[Id] IN (10,15)", sql);
        }

19 Source : SolutionFolderTest.cs
with MIT License
from 3F

[Fact]
        public void CtorTest2()
        {
            var f = new SolutionFolder("MyFolder4", (new RawText[] { ".gnt\\gnt.core" }).AsEnumerable());

            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder4",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        pGuid       = f.header.pGuid,
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },

                    items = new List<RawText>()
                    {
                        ".gnt\\gnt.core"
                    }
                },
                f
            );

            replacedert.Single(f.items);
            replacedert.Equal((RawText)".gnt\\gnt.core", f.items.ElementAt(0));
        }

19 Source : SolutionFolderTest.cs
with MIT License
from 3F

[Fact]
        public void CtorTest4()
        {
            var f0  = new SolutionFolder("dir1");
            var f   = new SolutionFolder("MyFolder1", f0, ".gnt\\gnt.core", ".gnt\\packages.config");

            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder1",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        parent      = f0,
                        pGuid       = f.header.pGuid,
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },

                    items = new List<RawText>()
                    {
                        ".gnt\\gnt.core", ".gnt\\packages.config"
                    }
                },
                f
            );
            replacedert.Equal(2, f.items.Count());
            replacedert.Equal((RawText)".gnt\\gnt.core", f.items.ElementAt(0));
            replacedert.Equal((RawText)".gnt\\packages.config", f.items.ElementAt(1));


            f = new SolutionFolder("MyFolder2", f0, ".gnt\\gnt.core");
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder2",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        parent      = f0,
                        pGuid       = f.header.pGuid,
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },

                    items = new List<RawText>()
                    {
                        ".gnt\\gnt.core"
                    }
                },
                f
            );
            replacedert.Single(f.items);
            replacedert.Equal((RawText)".gnt\\gnt.core", f.items.ElementAt(0));


            f = new SolutionFolder("MyFolder3", f0);
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder3",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        parent      = f0,
                        pGuid       = f.header.pGuid,
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },
                    items = new List<RawText>() { }
                },
                f
            );
            replacedert.Empty(f.items);


            f = new SolutionFolder("MyFolder4", f0, (new RawText[] { ".gnt\\gnt.core" }).AsEnumerable());
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder4",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        parent      = f0,
                        pGuid       = f.header.pGuid,
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },

                    items = new List<RawText>()
                    {
                        ".gnt\\gnt.core"
                    }
                },
                f
            );
            replacedert.Single(f.items);
            replacedert.Equal((RawText)".gnt\\gnt.core", f.items.ElementAt(0));
        }

19 Source : SolutionFolderTest.cs
with MIT License
from 3F

[Fact]
        public void CtorTest6()
        {
            var f = new SolutionFolder
            (
                "{EE7DD6B7-56F4-478D-8745-3D204D915473}", "MyFolder1", 
                new RawText[] { ".gnt\\gnt.core" }
            );
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder1",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        pGuid       = "{EE7DD6B7-56F4-478D-8745-3D204D915473}",
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },

                    items = new List<RawText>()
                    {
                        ".gnt\\gnt.core"
                    }
                },
                f
            );
            replacedert.Single(f.items);
            replacedert.Equal((RawText)".gnt\\gnt.core", f.items.ElementAt(0));


            f = new SolutionFolder("{EE7DD6B7-56F4-478D-8745-3D204D915473}", "MyFolder1", new RawText[] { });
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder1",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        pGuid       = "{EE7DD6B7-56F4-478D-8745-3D204D915473}",
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },
                    items = new List<RawText>() { }
                },
                f
            );
            replacedert.Empty(f.items);


            f = new SolutionFolder
            (
                "{EE7DD6B7-56F4-478D-8745-3D204D915473}", "MyFolder1", 
                (new RawText[] { ".gnt\\gnt.core" }).AsEnumerable()
            );
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder1",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        pGuid       = "{EE7DD6B7-56F4-478D-8745-3D204D915473}",
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },

                    items = new List<RawText>()
                    {
                        ".gnt\\gnt.core"
                    }
                },
                f
            );
            replacedert.Single(f.items);
            replacedert.Equal((RawText)".gnt\\gnt.core", f.items.ElementAt(0));
        }

19 Source : SolutionFolderTest.cs
with MIT License
from 3F

[Fact]
        public void CtorTest7()
        {
            var f0 = new SolutionFolder("dir1");

            var f = new SolutionFolder
            (
                "{EE7DD6B7-56F4-478D-8745-3D204D915473}", "MyFolder4", f0, 
                (new RawText[] { ".gnt\\gnt.core" }).AsEnumerable()
            );
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder4",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        pGuid       = "{EE7DD6B7-56F4-478D-8745-3D204D915473}",
                        parent      = f0,
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },

                    items = new List<RawText>()
                    {
                        ".gnt\\gnt.core"
                    }
                },
                f
            );
            replacedert.Single(f.items);
            replacedert.Equal((RawText)".gnt\\gnt.core", f.items.ElementAt(0));


            f = new SolutionFolder
            (
                "{EE7DD6B7-56F4-478D-8745-3D204D915473}", "MyFolder1", f0, 
                ".gnt\\gnt.core", ".gnt\\packages.config"
            );
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder1",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        pGuid       = "{EE7DD6B7-56F4-478D-8745-3D204D915473}",
                        parent      = f0,
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },

                    items = new List<RawText>()
                    {
                        ".gnt\\gnt.core", ".gnt\\packages.config"
                    }
                },
                f
            );
            replacedert.Equal(2, f.items.Count());
            replacedert.Equal((RawText)".gnt\\gnt.core", f.items.ElementAt(0));
            replacedert.Equal((RawText)".gnt\\packages.config", f.items.ElementAt(1));


            f = new SolutionFolder("{EE7DD6B7-56F4-478D-8745-3D204D915473}", "MyFolder2", f0, ".gnt\\gnt.core");
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder2",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        pGuid       = "{EE7DD6B7-56F4-478D-8745-3D204D915473}",
                        parent      = f0,
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },

                    items = new List<RawText>()
                    {
                        ".gnt\\gnt.core"
                    }
                },
                f
            );
            replacedert.Single(f.items);
            replacedert.Equal((RawText)".gnt\\gnt.core", f.items.ElementAt(0));


            f = new SolutionFolder("{5D5C7878-22BE-4E5B-BD96-6CBBAC614AD3}", "MyFolder3", f0);
            replacedert.Equal
            (
                new SolutionFolder()
                {
                    header = new Projecreplacedem()
                    {
                        name        = "MyFolder3",
                        EpType      = ProjectType.SlnFolder,
                        pType       = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}",
                        pGuid       = "{5D5C7878-22BE-4E5B-BD96-6CBBAC614AD3}",
                        parent      = f0,
                        path        = f.header.path,
                        fullPath    = f.header.fullPath,
                    },
                    items = new List<RawText>() { }
                },
                f
            );
            replacedert.Empty(f.items);
        }

19 Source : HttpContextExtension.cs
with GNU Lesser General Public License v3.0
from 8720826

private static List<string> SplitCsv(this string csvList, bool nullOrWhitespaceInputReturnsNull = false)
        {
            if (string.IsNullOrWhiteSpace(csvList))
                return nullOrWhitespaceInputReturnsNull ? null : new List<string>();

            return csvList
                .TrimEnd(',')
                .Split(',')
                .AsEnumerable<string>()
                .Select(s => s.Trim())
                .ToList();
        }

19 Source : PointCloudGHParameter - Copy (2).cs
with GNU Lesser General Public License v3.0
from 9and3

public GH_GetterResult LoadFromSelection(out PointCloud pc) {
            var go = new GetObject();
            go.GeometryFilter = Rhino.DocObjects.ObjectType.Point | Rhino.DocObjects.ObjectType.PointSet;
            if (go.GetMultiple(1, 0) == Rhino.Input.GetResult.Cancel) {
                pc = null;
                return GH_GetterResult.cancel;
            }
            pc = new PointCloud();

            for (int i = 0; i < go.ObjectCount; i++) {
                var obj = go.Object(i);
                var rhObj = obj.Object();
                if (rhObj.ObjectType == ObjectType.Point) {
                    var pt = obj.Point().Location;
                    var col = rhObj.Attributes.ObjectColor;
                    pc.Add(pt, col);
                } else if (rhObj.ObjectType == ObjectType.PointSet) {
                    using (PointCloud cloud = obj.PointCloud()) {
                        foreach (var item in cloud.AsEnumerable()) {
                            pc.Add(item.Location, item.Normal, item.Color);
                        }
                    }
                }
            }
            return GH_GetterResult.success;
        }

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

public static async Task<SyndicationFeed> BuildSyndication(this IBlogService service, string baseAddress)
        {
            ClientUriGenerator generator = new ClientUriGenerator
            {
                BaseAddress = baseAddress
            };
            BlogOptions blogOptions = await service.GetOptions();
            SyndicationFeed feed = new SyndicationFeed(blogOptions.Name, blogOptions.Description, new Uri(baseAddress));
            SyndicationPerson author = new SyndicationPerson("", blogOptions.Onwer, baseAddress);
            feed.Authors.Add(author);
            Dictionary<string, SyndicationCategory> categoryMap = new Dictionary<string, SyndicationCategory>();
            {
                var cates = await service.PostService.GetCategories();
                foreach (var p in cates.AsCategoryList())
                {
                    var cate = new SyndicationCategory(p.ToString());
                    categoryMap.Add(p.ToString(), cate);
                    feed.Categories.Add(cate);
                }
            }
            {
                var posts = service.PostService.GetAllItems().IgnoreNull();
                List<SyndicationItem> items = new List<SyndicationItem>();
                await foreach (var p in posts)
                {
                    if (p is null)
                        continue;
                    var s = new SyndicationItem(p.replacedle,
                        SyndicationContent.CreateHtmlContent(Markdown.ToHtml(p.Content.Raw, Pipeline)),
                        new Uri(generator.Post(p)), p.Id, p.ModificationTime);
                    s.Authors.Add(author);

                    string summary;
                    if (await service.PostService.Protector.IsProtected(p.Content))
                    {
                        summary = "Protected Post";
                    }
                    else
                    {
                        summary = Markdown.ToPlainText(p.Content.Raw, Pipeline);
                    }
                    s.Summary = SyndicationContent.CreatePlaintextContent(summary.Length <= 100 ? summary : summary.Substring(0, 100));
                    s.Categories.Add(new SyndicationCategory(p.Category.ToString()));
                    if (categoryMap.TryGetValue(p.Category.ToString(), out var cate))
                        s.Categories.Add(cate);
                    s.PublishDate = p.CreationTime;
                    items.Add(s);
                }
                feed.Items = items.AsEnumerable();
            }

            return feed;
        }

19 Source : FileDownloaderBuilder.cs
with MIT License
from Accelerider

public IDownloader Build(DownloadContext context, IEnumerable<BlockTransferContext> blockContexts)
        {
            Guards.ThrowIfNull(context);

            if (context.RemotePathProvider == null)
            {
                context.RemotePathProvider = _remotePathProvider ?? throw new ArgumentException("The Context.RemotePathProvider cannot be null");
            }

            context.RemotePathProvider = _remotePathProviderInterceptor(context.RemotePathProvider);

            var blockContextsArray = blockContexts?.ToArray();
            return blockContextsArray != null && blockContextsArray.Any()
                ? InternalBuild(context, ctx => token =>
                {
                    blockContextsArray.ForEach(item =>
                    {
                        item.LocalPath = ctx.LocalPath;
                        item.RemotePathGetter = ctx.RemotePathProvider.GetAsync;
                    });
                    return Task.FromResult(blockContextsArray.AsEnumerable());
                })
                : InternalBuild(context, GetBlockTransferContextGenerator);
        }

19 Source : Constructor.cs
with GNU General Public License v3.0
from Adam-Wilkinson

public static INodeComponentList NodeComponentList(params INodeComponent[] components) => NodeComponentList(components.AsEnumerable());

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

public static List<FactorPair> FindPolynomialRootsInRange(CancellationToken cancelToken, Polynomial polynomial, IEnumerable<BigInteger> primes, BigInteger rangeFrom, BigInteger rangeTo, int totalFactorPairs)
        {
            List<FactorPair> result = new List<FactorPair>();

            BigInteger r = rangeFrom;
            IEnumerable<BigInteger> modList = primes.AsEnumerable();
            while (!cancelToken.IsCancellationRequested && r < rangeTo && result.Count < totalFactorPairs)
            {
                // Finds p such that ƒ(r) ≡ 0 (mod p)
                List<BigInteger> roots = GetRootsMod(polynomial, r, modList);
                if (roots.Any())
                {
                    result.AddRange(roots.Select(p => new FactorPair(p, r)));
                }
                r++;
            }

            return result.OrderBy(tup => tup.P).ToList();
        }

19 Source : ContentMapProvider.cs
with MIT License
from Adoxio

protected virtual IEnumerable<Enreplacedy> GetEnreplacedies(CrmDbContext context, SolutionDefinition solution, IDictionary<string, object> parameters)
		{
			ConcurrentBag<Enreplacedy> result = new ConcurrentBag<Enreplacedy>();
			var queries = solution.GetQueries(parameters).Where(query => query != null);

			Parallel.ForEach(queries, query =>
			{
				// Add content map enreplacedies explicitly to the Portalused enreplacedies list. 
				// Since we are skipping cache for content map enreplacedies and hence these enreplacedies won't be added in this list via Dependency calucaltion.
				ADXTrace.Instance.TraceVerbose(TraceCategory.Application, $"Enreplacedy {query.Enreplacedy.Name} is added to Enabled Enreplacedy List for Portal Cache ");
				WebAppConfigurationProvider.PortalUsedEnreplacedies.TryAdd(query.Enreplacedy.Name, true);
				Fetch(context.Service, query, result);
			});

			return result.AsEnumerable();
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from 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 Source : OrganizationServiceContextExtensions.cs
with MIT License
from 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 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

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

			return context.CreateQuery("adx_caseaccess")
				.Where(ca => ca.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact)
				.AsEnumerable();
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

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

			var accounts = from account in context.CreateQuery("account")
				join caseaccess in context.CreateQuery("adx_caseaccess")
				on account.GetAttributeValue<Guid>("accountid") equals caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid").Id
				where caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && 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
				select account;

			return accounts.Distinct().AsEnumerable();
		}

19 Source : KnowledgeArticleDataAdapter.cs
with MIT License
from Adoxio

public IEnumerable<EnreplacedyCollection> GetRelatedProductsAndArticles(IKnowledgeArticle article)
		{
			var serviceContext = this.Dependencies.GetServiceContext();
			Fetch fetchRelatedProducts = null;
			Fetch fetchRelatedArticles = null;

			var articleConnectionRole = GetArticleConnectionRole(serviceContext, this.KnowledgeArticleConnectionRoleId);
			var relatedProductConnectionRole = GetArticleConnectionRole(serviceContext, this.RelatedProductConnectionRoleId);

			if (articleConnectionRole != null && relatedProductConnectionRole != null)
			{
				var relatedProductsFetchXml = string.Format(RelatedProductsFetchXmlFormat, 
					article.Id,
					relatedProductConnectionRole.Id, 
					articleConnectionRole.Id);

				fetchRelatedProducts = Fetch.Parse(relatedProductsFetchXml);
			}

			var languageCondition = string.Empty;
			if (!string.IsNullOrWhiteSpace(this.LanguageCode))
			{
				languageCondition = "<condition enreplacedyname='language_locale' attribute='code' operator='eq' value = '" + this.LanguageCode + "' />";
			}

			var primaryArticleConnectionRole = GetArticleConnectionRole(serviceContext, this.PrimaryArticleConnectionRoleId);
			var relatedArticleConnectionRole = GetArticleConnectionRole(serviceContext, this.RelatedArticleConnectionRoleId);

			if (primaryArticleConnectionRole != null && relatedArticleConnectionRole != null)
			{
				var id = article.RootArticle == null ? article.Id : article.RootArticle.Id;
				var relatedArticlesFetchXml = string.Format(RelatedArticlesFetchXmlFormat, 
					id, 
					primaryArticleConnectionRole.Id,
					relatedArticleConnectionRole.Id, 
					languageCondition);

				fetchRelatedArticles = Fetch.Parse(relatedArticlesFetchXml);
			}

			var products = new EnreplacedyCollection();
			if (fetchRelatedProducts != null)
			{
				products = serviceContext.RetrieveMultiple(fetchRelatedProducts, RequestFlag.AllowStaleData);
			}

			var articles = new EnreplacedyCollection();
			if (fetchRelatedArticles != null)
			{
				articles = serviceContext.RetrieveMultiple(fetchRelatedArticles, RequestFlag.AllowStaleData);
			}

			return new List<EnreplacedyCollection> { products, articles }.AsEnumerable();
		}

19 Source : OrganizationServiceContextExtensions.cs
with MIT License
from 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 Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

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

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

			var contactAccess = context.GetContactAccessByContact(contact).Where(ca => ca.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false)
				&& ca.GetAttributeValue<OptionSetValue>("adx_scope") != null && ca.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)ContactAccessScope.Account
				&& ca.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && ca.GetAttributeValue<EnreplacedyReference>("adx_accountid").Equals(new EnreplacedyReference("account", accountid)));

			var returnSet = new List<Enreplacedy>();

			foreach (Enreplacedy access in contactAccess)
			{
				var accountcontacts =
					context.CreateQuery("contact").Where(
						c => c.GetAttributeValue<EnreplacedyReference>("parentcustomerid") == access.GetAttributeValue<EnreplacedyReference>("adx_accountid"));

				returnSet.AddRange(accountcontacts);

			}

			return returnSet.AsEnumerable();
		}

19 Source : EnumerableFilters.cs
with MIT License
from Adoxio

public static IEnumerable GroupBy(IEnumerable input, string key)
		{
			return input.Cast<object>().GroupBy(e => Get(e, key)).Select(group => new Hash
			{
				{ "key", @group.Key },
				{ "items", @group.AsEnumerable() }
			});
		}

19 Source : CmsParentController.cs
with MIT License
from Adoxio

private static JObject GetWebPageReferenceJson(Tuple<DirectoryTreeNode, string[]> node, Guid portalScopeId)
		{
			var enreplacedy = node.Item1.Enreplacedy;
			var name = enreplacedy.GetAttributeValue<string>("adx_name");

			var json = new JObject
			{
				{
					"__metadata", new JObject
					{
						{ "uri", new JValue(VirtualPathUtility.ToAbsolute(CmsEnreplacedyRouteHandler.GetAppRelativePath(portalScopeId, enreplacedy.ToEnreplacedyReference()))) },
						{ "type", new JValue(enreplacedy.GetType().FullName) },
					}
					},
				{ "Id", new JValue(enreplacedy.Id.ToString()) },
				{ "LogicalName", new JValue(enreplacedy.LogicalName) },
				{ "Name", new JValue(name) },
				{ "Path", new JArray(node.Item2.AsEnumerable()) },
				{ "adx_name", new JValue(name) },
				{ "adx_webpageid", new JValue(enreplacedy.Id.ToString()) }
			};

			return json;
		}

19 Source : SubgridControlTemplate.cs
with MIT License
from Adoxio

protected override void InstantiateControlIn(HtmlControl container)
		{
			if (string.IsNullOrWhiteSpace(Metadata.ViewID)) return;

			var context = CrmConfigurationManager.CreateContext(ContextName);
			var portal = PortalCrmConfigurationManager.CreatePortalContext(ContextName);
			var user = portal == null ? null : portal.User;

			EnreplacedyMetadata = GetEnreplacedyMetadata(context);

			var viewId = new Guid(Metadata.ViewID);

			if (viewId == Guid.Empty) return;

			var viewGuids = new[] { viewId };

			if (Metadata.ViewEnableViewPicker && !string.IsNullOrWhiteSpace(Metadata.ViewIds))
			{
				var viewids = Metadata.ViewIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
				if (viewids.Length >= 1)
				{
					viewGuids = Array.ConvertAll(viewids, Guid.Parse).AsEnumerable().OrderBy(o => o != viewId).ThenBy(o => o).ToArray();
				}
			}

			Bindings[Metadata.ControlID + "CrmEnreplacedyId"] = new CellBinding
			{
				Get = () => null,
				Set = obj =>
					{
						var id = obj.ToString();
						Guid enreplacedyId;

						if (!Guid.TryParse(id, out enreplacedyId)) return;

						var subgridHtml = BuildGrid(container, context, viewGuids, viewId, enreplacedyId, user);
						var subgrid = new HtmlGenericControl("div") { ID = Metadata.ControlID, InnerHtml = subgridHtml.ToString() };
						subgrid.Attributes.Add("clreplaced", "subgrid");
						container.Controls.Add(subgrid);
					}
			};

			if (!container.Page.IsPostBack) return;

			// On PostBack no databinding occurs so get the id from the viewstate stored on the CrmEnreplacedyFormView control.
			var crmEnreplacedyId = Metadata.FormView.CrmEnreplacedyId;

			if (crmEnreplacedyId == null) return;

			var gridHtml = BuildGrid(container, context, viewGuids, viewId, (Guid)crmEnreplacedyId, user);
			var subgridControl = new HtmlGenericControl("div") { ID = Metadata.ControlID, InnerHtml = gridHtml.ToString() };
			subgridControl.Attributes.Add("clreplaced", "subgrid");
			container.Controls.Add(subgridControl);
		}

19 Source : ModalLookupControlTemplate.cs
with MIT License
from Adoxio

protected virtual IHtmlString BuildLookupModal(Control container)
		{
			var html = Mvc.Html.EnreplacedyExtensions.GetHtmlHelper(Metadata.FormView.ContextName, container.Page.Request.RequestContext, container.Page.Response); //new HtmlHelper(new ViewContext(), new ViewPage());
			var context = CrmConfigurationManager.CreateContext(Metadata.FormView.ContextName);
			var portal = PortalCrmConfigurationManager.CreatePortalContext(Metadata.FormView.ContextName);
			var user = portal == null ? null : portal.User;
			var viewConfigurations = new List<ViewConfiguration>();
			var defaultViewId = Metadata.LookupViewID;
			var modalGridSearchPlaceholderText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/Search/PlaceholderText");
			var modalGridSearchTooltipText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/Search/TooltipText");
			var modalGridPageSize = html.IntegerSetting("Portal/Lookup/Modal/Grid/PageSize") ?? 10;
			var modalSizeSetting = html.Setting("Portal/Lookup/Modal/Size");
			var modalSize = BootstrapExtensions.BootstrapModalSize.Large;
			if (modalSizeSetting != null && modalSizeSetting.ToLower() == "default") modalSize = BootstrapExtensions.BootstrapModalSize.Default;
			if (modalSizeSetting != null && modalSizeSetting.ToLower() == "small") modalSize = BootstrapExtensions.BootstrapModalSize.Small;

			var formEnreplacedyReferenceInfo = GetFormEnreplacedyReferenceInfo(container.Page.Request);
			
			if (defaultViewId == Guid.Empty)
			{
				// By default a lookup field cell defined in the form XML does not contain view parameters unless the user has specified a view that is not the default for that enreplacedy and we must query to find the default view.  Saved Query enreplacedy's QueryType code 64 indicates a lookup view.

				viewConfigurations.AddRange(
					Metadata.LookupTargets.Select(
						target => new ViewConfiguration(new SavedQueryView(context, target, 64, true, Metadata.LanguageCode), modalGridPageSize)
						{
							Search = new ViewSearch(!Metadata.LookupDisableQuickFind) { PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText },
							EnableEnreplacedyPermissions = Metadata.FormView.EnableEnreplacedyPermissions,
							PortalName = Metadata.FormView.ContextName,
							LanguageCode = Metadata.LanguageCode,
							ModalLookupAttributeLogicalName = Metadata.DataFieldName,
							ModalLookupEnreplacedyLogicalName = Metadata.TargetEnreplacedyName,
							ModalLookupFormReferenceEnreplacedyId = formEnreplacedyReferenceInfo.Item2,
							ModalLookupFormReferenceEnreplacedyLogicalName = formEnreplacedyReferenceInfo.Item1,
							ModalLookupFormReferenceRelationshipName = formEnreplacedyReferenceInfo.Item3,
							ModalLookupFormReferenceRelationshipRole = formEnreplacedyReferenceInfo.Item4
						}));
			}
			else
			{
				viewConfigurations.Add(new ViewConfiguration(new SavedQueryView(context, defaultViewId, Metadata.LanguageCode), modalGridPageSize)
				{
					Search = new ViewSearch(!Metadata.LookupDisableQuickFind) { PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText },
					EnableEnreplacedyPermissions = Metadata.FormView.EnableEnreplacedyPermissions,
					PortalName = Metadata.FormView.ContextName,
					LanguageCode = Metadata.LanguageCode,
					ModalLookupAttributeLogicalName = Metadata.DataFieldName,
					ModalLookupEnreplacedyLogicalName = Metadata.TargetEnreplacedyName,
					ModalLookupFormReferenceEnreplacedyId = formEnreplacedyReferenceInfo.Item2,
					ModalLookupFormReferenceEnreplacedyLogicalName = formEnreplacedyReferenceInfo.Item1,
					ModalLookupFormReferenceRelationshipName = formEnreplacedyReferenceInfo.Item3,
					ModalLookupFormReferenceRelationshipRole = formEnreplacedyReferenceInfo.Item4
				});
			}

			if (!Metadata.LookupDisableViewPicker && !string.IsNullOrWhiteSpace(Metadata.LookupAvailableViewIds))
			{
				var addViewConfigurations = new List<ViewConfiguration>();
				var viewids = Metadata.LookupAvailableViewIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
				if (viewids.Length >= 1)
				{
					var viewGuids = Array.ConvertAll(viewids, Guid.Parse).AsEnumerable().OrderBy(o => o != defaultViewId).ThenBy(o => o).ToArray();
					addViewConfigurations.AddRange(from viewGuid in viewGuids
						from viewConfiguration in viewConfigurations
						where viewConfiguration.ViewId != viewGuid
						select new ViewConfiguration(new SavedQueryView(context, viewGuid, Metadata.LanguageCode), modalGridPageSize)
						{
							Search = new ViewSearch(!Metadata.LookupDisableQuickFind) { PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText },
							EnableEnreplacedyPermissions = Metadata.FormView.EnableEnreplacedyPermissions,
							PortalName = Metadata.FormView.ContextName,
							LanguageCode = Metadata.LanguageCode,
							ModalLookupAttributeLogicalName = Metadata.DataFieldName,
							ModalLookupEnreplacedyLogicalName = Metadata.TargetEnreplacedyName,
							ModalLookupFormReferenceEnreplacedyId = formEnreplacedyReferenceInfo.Item2,
							ModalLookupFormReferenceEnreplacedyLogicalName = formEnreplacedyReferenceInfo.Item1,
							ModalLookupFormReferenceRelationshipName = formEnreplacedyReferenceInfo.Item3,
							ModalLookupFormReferenceRelationshipRole = formEnreplacedyReferenceInfo.Item4
						});
				}
				viewConfigurations.AddRange(addViewConfigurations);
			}
			
			var applyRelatedRecordFilter = !string.IsNullOrWhiteSpace(Metadata.LookupFilterRelationshipName);
			string filterFieldName = null;
			if (!string.IsNullOrWhiteSpace(Metadata.LookupDependentAttributeName)) // enreplacedy.attribute (i.e. contact.adx_subject)
			{
				var pos = Metadata.LookupDependentAttributeName.IndexOf(".", StringComparison.InvariantCulture);
				filterFieldName = pos >= 0
					? Metadata.LookupDependentAttributeName.Substring(pos + 1)
					: Metadata.LookupDependentAttributeName;
			}
			
			var modalreplacedle = html.SnippetLiteral("Portal/Lookup/Modal/replacedle");
			var modalPrimaryButtonText = html.SnippetLiteral("Portal/Lookup/Modal/PrimaryButtonText");
			var modalCancelButtonText = html.SnippetLiteral("Portal/Lookup/Modal/CancelButtonText");
			var modalDismissButtonSrText = html.SnippetLiteral("Portal/Lookup/Modal/DismissButtonSrText");
			var modalRemoveValueButtonText = html.SnippetLiteral("Portal/Lookup/Modal/RemoveValueButtonText");
			var modalNewValueButtonText = html.SnippetLiteral("Portal/Lookup/Modal/NewValueButtonText");
			var modalDefaultErrorMessage = html.SnippetLiteral("Portal/Lookup/Modal/DefaultErrorMessage");
			var modalGridLoadingMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/LoadingMessage");
			var modalGridErrorMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/ErrorMessage");
			var modalGridAccessDeniedMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/AccessDeniedMessage");
			var modalGridEmptyMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/EmptyMessage");
			var modalGridToggleFilterText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/ToggleFilterText");
			
			return html.LookupModal(ControlID, viewConfigurations,
				BuildControllerActionUrl("GetLookupGridData", "EnreplacedyGrid", new { area = "Portal", __portalScopeId__ = portal == null ? Guid.Empty : portal.Website.Id }), user, applyRelatedRecordFilter,
				Metadata.LookupAllowFilterOff, Metadata.LookupFilterRelationshipName, Metadata.LookupDependentAttributeType,
				filterFieldName, null, null, modalreplacedle, modalPrimaryButtonText, modalCancelButtonText, modalDismissButtonSrText,
				modalRemoveValueButtonText, modalNewValueButtonText, null, null, modalGridLoadingMessage, modalGridErrorMessage, modalGridAccessDeniedMessage,
				modalGridEmptyMessage, modalGridToggleFilterText, modalDefaultErrorMessage, null, null, null, Metadata.FormView.ContextName,
				Metadata.LanguageCode, null, modalSize, Metadata.LookupReferenceEnreplacedyFormId, EvaluateCreatePrivilege(portal.ServiceContext),
				ControlID == "enreplacedlementid" ? BuildControllerActionUrl("GetDefaultEnreplacedlements", "Enreplacedlements", new { area = "CaseManagement", __portalScopeId__ = portal == null ? Guid.Empty : portal.Website.Id }) : null);
		}

19 Source : NameWebsiteSelector.cs
with MIT License
from Adoxio

private static IEnumerable<Enreplacedy> GetWebsitesByName(OrganizationServiceContext context, string name)
		{
			return context.CreateQuery("adx_website")
				.Where(website => website.GetAttributeValue<string>("adx_name") == name)
				.AsEnumerable();
		}

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private static IEnumerable<CodeInstruction> MineShaft_populateLevel_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            bool start = false;
            for (int i = 0; i < codes.Count; i++)
            {
                if (start && codes[i].opcode == OpCodes.Ldc_R8 && (double)codes[i].operand == 0.005)
                {
                    context.Monitor.Log("got 0.005 opcode");
                    codes[i].operand = Config.ResourceClumpChance; 
                    break;
                }
                else if (!start && codes[i].opcode == OpCodes.Call && (codes[i].operand as MethodInfo)?.Name == nameof(MineShaft.getRandomItemForThisLevel))
                {
                    context.Monitor.Log($"got call: {codes[i].operand}");
                    start = true;
                }
            }

            return codes.AsEnumerable();
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

private static IEnumerable<CodeInstruction> MineShaft_tryToAddAreaUniques_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            for (int i = 0; i < codes.Count; i++)
            {
                if (codes[i].opcode == OpCodes.Ldc_R8 && (double)codes[i].operand == 0.1)
                {
                    context.Monitor.Log("got Ldc_R8 opcode try");
                    codes[i].operand = Config.WeedsChance;
                }
                else if (codes[i].opcode == OpCodes.Ldc_I4_7)
                {
                    context.Monitor.Log("got Ldc_I4_7 opcode try");
                    codes[i] = new CodeInstruction(OpCodes.Ldc_I4, (int)Math.Round(7 * Config.WeedsMultiplier));
                    codes[i + 1] = new CodeInstruction(OpCodes.Ldc_I4, (int)Math.Round(24 * Config.WeedsMultiplier));
                    break;
                }
            }

            return codes.AsEnumerable();
        }

19 Source : UIPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> SocialPage_drawSlot_transpiler(IEnumerable<CodeInstruction> instructions)
        {
            List<CodeInstruction> codes = instructions.ToList();
            if (Helper.ModRegistry.IsLoaded("SG.Partners"))
            {
                Monitor.Log("Keep Your Partners mod is loaded, not patching social page.");
                return codes.AsEnumerable();
            }
            try
            {
                MethodInfo m_IsMarried = AccessTools.Method(typeof(Farmer), "isMarried", null, null);
                int index = codes.FindIndex((CodeInstruction c) => c.operand != null && c.operand is MethodInfo && (MethodInfo)c.operand == m_IsMarried);
                if(index > -1)
                {
                    codes[index - 1].opcode = OpCodes.Nop;
                    codes[index].opcode = OpCodes.Nop;
                    codes[index + 1].opcode = OpCodes.Nop;
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(SocialPage_drawSlot_transpiler)}:\n{ex}", LogLevel.Error);
            }
            return codes.AsEnumerable();
        }

19 Source : MyPatches.cs
with GNU General Public License v3.0
from aedenthorn

private static IEnumerable<CodeInstruction> CollectionsPage_draw_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            var newCodes = new List<CodeInstruction>();
            bool skipping = false;
            for (int i = 0; i < codes.Count; i++)
            {
                if (skipping)
                {
                    if (codes[i].opcode == OpCodes.Ldc_R4 && codes[i-1].opcode == OpCodes.Ldc_I4_0)
                    {
                        skipping = false;
                        i++;
                        newCodes.Add(new CodeInstruction(OpCodes.Ldarg_1, null));
                        newCodes.Add(new CodeInstruction(OpCodes.Ldloc_3, null));
                        newCodes.Add(new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(MyPatches), "DrawFace")));
                    }
                    continue;
                }
                newCodes.Add(codes[i]);
                if (codes[i].opcode == OpCodes.Stloc_S && ((LocalBuilder)codes[i].operand).LocalType == typeof(int))
                {
                    skipping = true;
                }
            }

            return newCodes.AsEnumerable();
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> Layer_DrawNormal_Transpiler(IEnumerable<CodeInstruction> instructions)
        {
            PMonitor.Log("Transpiling Layer_DrawNormal");
            List<CodeInstruction> codes = new List<CodeInstruction>(instructions);
            for (int i = 0; i < codes.Count; i++)
            {
                if (codes[i].opcode == OpCodes.Callvirt && (MethodInfo)codes[i].operand == AccessTools.Method("String:Equals", new Type[]{typeof(string)}) && i > 0 && codes[i - 1].opcode == OpCodes.Ldstr && (string)codes[i - 1].operand == "Front")
                {
                    PMonitor.Log("switching equals to starts with");
                    codes[i].operand = AccessTools.Method("String:StartsWith", new Type[] { typeof(string) }, null);
                }
            }
            return codes.AsEnumerable();
        }

19 Source : NPCPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> NPC_tryToReceiveActiveObject_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            bool startLooking = false;
            for (int i = 0; i < codes.Count; i++)
            {
                if (startLooking)
                {
                    if(codes[i].opcode == OpCodes.Ldc_I4_S && int.Parse(codes[i].operand.ToString()) < -10)
                    {
                        Monitor.Log($"got int!");
                        codes[i] = new CodeInstruction(OpCodes.Ldc_I4_S, 30);
                        break;
                    }
                }
                else if ((codes[i].operand as string) == "Strings\\StringsFromCSFiles:NPC.cs.3981")
                {
                    Monitor.Log($"got string!");
                    startLooking = true;
                }
            }

            return codes.AsEnumerable();
        }

19 Source : BillboardPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> Billboard_draw_Transpiler(IEnumerable<CodeInstruction> instructions)
        {
            SMonitor.Log($"Transpiling Billboard.draw");

            var codes = new List<CodeInstruction>(instructions);
            for (int i = 0; i < codes.Count; i++)
            {
                if (codes[i].opcode == OpCodes.Ldsfld && (FieldInfo)codes[i].operand == typeof(Game1).GetField(nameof(Game1.dayOfMonth), BindingFlags.Public | BindingFlags.Static) && codes[i + 1].opcode == OpCodes.Ldloc_2 && codes[i + 2].opcode == OpCodes.Ldc_I4_1 && codes[i + 3].opcode == OpCodes.Add && codes[i + 4].opcode == OpCodes.Ble_S)
                {
                    SMonitor.Log("Removing greyed out date covering");
                    codes[i + 2] = new CodeInstruction(OpCodes.Ldc_I4, 29);
                }
            }

            return codes.AsEnumerable();
        }

19 Source : SDatePatches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> SDate_Transpiler(IEnumerable<CodeInstruction> instructions)
        {
            SMonitor.Log($"Transpiling SDate()");

            var codes = new List<CodeInstruction>(instructions);
            var outCodes = new List<CodeInstruction>();
            for (int i = 0; i < codes.Count; i++)
            {
                if (codes[i].opcode == OpCodes.Ldarg_1 && codes[i+1].opcode == OpCodes.Ldarg_0 && codes[i+2].opcode == OpCodes.Ldfld && ((FieldInfo)codes[i + 2].operand).Name == "DaysInSeason")
                {
                    SMonitor.Log($"Avoiding SMAPI {((FieldInfo)codes[i + 2].operand).Name} {Config.DaysPerMonth}");
                    codes[i + 1] = new CodeInstruction(OpCodes.Ldc_I4, Config.DaysPerMonth);
                    outCodes.Add(codes[i++]);
                    outCodes.Add(codes[i++]);
                    i++;
                }
                outCodes.Add(codes[i]);
            }

            return outCodes.AsEnumerable();
        }

19 Source : UtilityPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> Utility_getDateStringFor_Transpiler(IEnumerable<CodeInstruction> instructions)
        {
            SMonitor.Log($"Transpiling Utility.getDateStringFor");

            var codes = new List<CodeInstruction>(instructions);
            for (int i = 0; i < codes.Count; i++)
            {
                if (codes[i].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i].operand == 28)
                {
                    SMonitor.Log($"Changing days per month to {Config.DaysPerMonth}");
                    codes[i] = new CodeInstruction(OpCodes.Ldc_I4, Config.DaysPerMonth);
                }
            }

            return codes.AsEnumerable();
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> damageMonster_Transpiler(IEnumerable<CodeInstruction> instructions)
        {
            SMonitor.Log($"Transpiling GameLocation.damageMonster!");

            var codes = new List<CodeInstruction>(instructions);
            var newCodes = new List<CodeInstruction>();
            bool startLooking = false;
            bool startSkipping = false;
            bool stopLooking = false;
            for (int i = 0; i < codes.Count; i++)
            {
                if (startLooking && !stopLooking)
                {
                    if (startSkipping && codes[i].opcode == OpCodes.Pop)
                    {
                        SMonitor.Log($"popped!");
                        newCodes.Add(codes[i]);
                        stopLooking = true;
                    }
                    else if (!startSkipping && codes[i].opcode == OpCodes.Ldarg_0)
                    {
                        SMonitor.Log($"start skipping!");
                        startSkipping = true;
                    }
                    if (startSkipping)
                    {
                        codes[i].opcode = OpCodes.Nop;
                        codes[i].operand = null;
                        SMonitor.Log($"nullifying {codes[i].opcode}");
                    }
                }
                else if (!stopLooking && codes[i].opcode == OpCodes.Ldstr && (codes[i].operand as string) == "hardModeMonstersKilled")
                {
                    SMonitor.Log($"got hardModeMonstersKilled!");
                    startLooking = true;
                }
                newCodes.Add(codes[i]);
            }

            return newCodes.AsEnumerable();
        }

19 Source : SwimPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> Farmer_updateCommon_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            try
            {
                bool startLooking = false;
                int start = -1;
                int end = -1;
                for (int i = 0; i < codes.Count; i++)
                {
                    if (startLooking)
                    {
                        if(start == -1 && codes[i].opcode == OpCodes.Ldfld && codes[i].operand as FieldInfo == typeof(Farmer).GetField("timerSinceLastMovement"))
                        {
                            start = i - 1;
                            Monitor.Log($"start at {start}");
                        }
                        if (codes[i].opcode == OpCodes.Stfld && codes[i].operand as FieldInfo == typeof(Farmer).GetField("health"))
                        {
                            end = i + 1;
                            Monitor.Log($"end at {end}");
                        }
                    }
                    else if (codes[i].operand as string == "slosh")
                    {
                        startLooking = true;
                    }
                }
                if(start > -1 && end > start)
                {
                    codes.RemoveRange(start, end - start);
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(Farmer_updateCommon_Transpiler)}:\n{ex}", LogLevel.Error);
            }

            return codes.AsEnumerable();
        }

19 Source : SwimPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> Wand_DoFunction_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            try
            {
                int start = 0;
                for (int i = 0; i < codes.Count; i++)
                {
                    if (codes[i].opcode == OpCodes.Ret)
                    {
                        start = i + 1;
                        return codes.Skip(start).AsEnumerable();
                    }
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(Wand_DoFunction_Transpiler)}:\n{ex}", LogLevel.Error);
            }

            return codes.AsEnumerable();
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> AbigailGame_updateBullets_Transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            for (int i = 0; i < codes.Count; i++)
            {
                if (codes[i].opcode == OpCodes.Stloc_S)
                {
                    SMonitor.Log(""+codes[i].operand);

                }
                if (codes[i].opcode == OpCodes.Stloc_S && codes[i].operand.ToString() == "System.Int32 (4)"  && codes[i-1].opcode == OpCodes.Ldc_I4_M1)
                {
                    SMonitor.Log($"got loot opcode!");
                    codes[i - 1] = codes[i];
                }
            }

            return codes.AsEnumerable();
        }

19 Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> Town_checkAction_transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions); 
            bool startLooking = false;
            bool stopLooking = false;
            int emote = Config.LinusEmote;
            int points = Config.LinusPoints;
            for (int i = 0; i < codes.Count; i++)
            {
                if (startLooking)
                {
                    if (codes[i].opcode == OpCodes.Ldloc_S && codes[i+2].opcode == OpCodes.Ldc_I4_1 && codes[i+3].opcode == OpCodes.Callvirt)
                    {
                        PMonitor.Log($"changing emote from {codes[i + 1].opcode}:{codes[i + 1].operand} to {emote}");
                        codes[i+1] = new CodeInstruction(OpCodes.Ldc_I4_S, emote);
                    }
                    else if (codes[i].opcode == OpCodes.Ldarg_3 && codes[i+2].opcode == OpCodes.Ldloc_S && codes[i+3].opcode == OpCodes.Isinst)
                    {
                        PMonitor.Log($"changing friendship from {codes[i+1].opcode}:{codes[i + 1].operand} to {points}");
                        codes[i+1] = new CodeInstruction(OpCodes.Ldc_I4, points);
                        if (stopLooking)
                            break;
                    }
                    else if (codes[i].operand as string == "Data\\ExtraDialogue:Town_DumpsterDiveComment_Linus")
                    {
                        PMonitor.Log($"got dialogue string {codes[i].operand}!");
                        codes[i].operand = Config.LinusDialogue;
                        emote = Config.ChildEmote;
                        points = Config.ChildPoints;
                    }
                    else if (codes[i].operand as string == "Data\\ExtraDialogue:Town_DumpsterDiveComment_Child")
                    {
                        PMonitor.Log($"got dialogue string {codes[i].operand}!");
                        codes[i].operand = Config.ChildDialogue;
                        emote = Config.TeenEmote;
                        points = Config.TeenPoints;
                    }
                    else if (codes[i].operand as string == "Data\\ExtraDialogue:Town_DumpsterDiveComment_Teen")
                    {
                        PMonitor.Log($"got dialogue string {codes[i].operand}!");
                        codes[i].operand = Config.TeenDialogue;
                        emote = Config.AdultEmote;
                        points = Config.AdultPoints;
                    }
                    else if (codes[i].operand as string == "Data\\ExtraDialogue:Town_DumpsterDiveComment_Adult")
                    {
                        PMonitor.Log($"got dialogue string {codes[i].operand}!");
                        codes[i].operand = Config.AdultDialogue;
                        stopLooking = true;
                    }
                }
                else if ((codes[i].operand as string) == "TrashCan")
                {
                    PMonitor.Log($"got string 'TrashCan'!");
                    startLooking = true;
                }
            }

            return codes.AsEnumerable();
        }

19 Source : Game1Patches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> Game1__newDayAfterFade_Transpiler(IEnumerable<CodeInstruction> instructions)
        {
            SMonitor.Log($"Transpiling Game1._newDayAfterFade");

            var codes = new List<CodeInstruction>(instructions);
            for (int i = 0; i < codes.Count; i++)
            {
                if (codes[i].opcode == OpCodes.Ldsfld && (FieldInfo)codes[i].operand == typeof(Game1).GetField(nameof(Game1.dayOfMonth), BindingFlags.Public | BindingFlags.Static) && codes[i + 1].opcode == OpCodes.Ldc_I4_S && (sbyte)codes[i + 1].operand == 29)
                {
                    SMonitor.Log($"Changing days per month to {Config.DaysPerMonth}");
                    codes[i + 1].operand = Config.DaysPerMonth + 1;
                    codes[i + 2].opcode = OpCodes.Blt_Un_S;
                    break;
                }
            }

            return codes.AsEnumerable();
        }

19 Source : UndergroundPatches.cs
with GNU General Public License v3.0
from aedenthorn

public static IEnumerable<CodeInstruction> MineShaft_populateLevel_transpiler(IEnumerable<CodeInstruction> instructions)
        {

            var codes = new List<CodeInstruction>(instructions);
            try
            {
                bool start = false;
                for (int i = 0; i < codes.Count; i++)
                {
                    if (codes[i].opcode == OpCodes.Ldarg_0)
                    {
                        if (start)
                        {
                            codes.RemoveRange(i, 3);
                            break;
                        }
                        else
                            start = true;
                    }
                }
            }
            catch (Exception ex)
            {
                monitor.Log($"Failed in {nameof(MineShaft_populateLevel_transpiler)}:\n{ex}", LogLevel.Error);
            }

            return codes.AsEnumerable();
        }

19 Source : DeleteDataFromStateDbPostExecutionPlugin.cs
with MIT License
from AElfProject

public Task<IEnumerable<Transaction>> GetPostTransactionsAsync(IReadOnlyList<ServiceDescriptor> descriptors, ITransactionContext transactionContext)
        {
            if (!descriptors.Any(service => service.File.Name == "test_basic_function_with_parallel_contract.proto"))
            {
                return Task.FromResult(new List<Transaction>().AsEnumerable());
            }

            if (transactionContext.Transaction.To == ParallelTestHelper.BasicFunctionWithParallelContractAddress &&
                !transactionContext.Transaction.MethodName.EndsWith("Plugin"))
            {
                return Task.FromResult(new List<Transaction>().AsEnumerable());
            }

            var context = _contextService.Create();
            context.TransactionContext = transactionContext;
            
            var transactions = new List<Transaction>();
            switch (transactionContext.Transaction.MethodName)
            {
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueFromInlineWithPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueFromPrePlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueWithPlugin):
                {
                    var input = RemoveValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                    transactions.Add(new Transaction
                    {
                        From = transactionContext.Transaction.From,
                        To = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = new IncreaseValueInput
                        {
                            Key = input.Key,
                            Memo = Guid.NewGuid().ToString()
                        }.ToByteString(),
                        MethodName = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValue),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                    break;
                }

                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueFromPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueParallelFromPostPlugin):
                {
                    var input = RemoveValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                    transactions.Add(new Transaction
                    {
                        From = transactionContext.Transaction.From,
                        To = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = input.ToByteString(),
                        MethodName = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValue),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                    break;
                }
                
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueParallelWithInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithInlineAndPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedParallelWithInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedInlineAndPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueParallelWithFailedInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedPrePluginAndPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndFailedPrePluginAndPostPlugin):
                {
                    var input = IncreaseValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                    transactions.Add(new Transaction
                    {
                        From = transactionContext.Transaction.From,
                        To = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = new IncreaseValueInput
                        {
                            Key = input.Key,
                            Memo = Guid.NewGuid().ToString()
                        }.ToByteString(),
                        MethodName = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValue),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                    break;
                }
                
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndFailedPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithPrePluginAndFailedPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndPrePluginAndFailedPostPlugin):
                {
                    var input = IncreaseValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                    transactions.Add(new Transaction
                    {
                        From = transactionContext.Transaction.From,
                        To = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = new IncreaseValueInput
                        {
                            Key = input.Key,
                            Memo = Guid.NewGuid().ToString()
                        }.ToByteString(),
                        MethodName = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailed),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                    break;
                }
            }
            
            return Task.FromResult(transactions.AsEnumerable());
        
        }

19 Source : DeleteDataFromStateDbPreExecutionAcsPlugin.cs
with MIT License
from AElfProject

public Task<IEnumerable<Transaction>> GetPreTransactionsAsync(IReadOnlyList<ServiceDescriptor> descriptors, ITransactionContext transactionContext)
        {
            if (!descriptors.Any(service => service.File.Name == "test_basic_function_with_parallel_contract.proto"))
            {
                return Task.FromResult(new List<Transaction>().AsEnumerable());
            }
            
            if (transactionContext.Transaction.To == ParallelTestHelper.BasicFunctionWithParallelContractAddress &&
                !transactionContext.Transaction.MethodName.EndsWith("Plugin"))
            {
                return Task.FromResult(new List<Transaction>().AsEnumerable());
            }
            
            var context = _contextService.Create();
            context.TransactionContext = transactionContext;
            
            var transactions = new List<Transaction>();

            switch (transactionContext.Transaction.MethodName)
            {
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueFromInlineWithPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueFromPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueWithPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueParallelFromPostPlugin):
                {
                    var input = RemoveValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                    transactions.Add(new Transaction
                    {
                        From = transactionContext.Transaction.From,
                        To = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = new IncreaseValueInput
                        {
                            Key = input.Key,
                            Memo = Guid.NewGuid().ToString()
                        }.ToByteString(),
                        MethodName = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValue),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                    break;
                }

                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValueFromPrePlugin):
                {
                    var input = RemoveValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                    transactions.Add(new Transaction
                    {
                        From = transactionContext.Transaction.From,
                        To = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = input.ToByteString(),
                        MethodName = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.RemoveValue),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                    break;
                }
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithPrePlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndPrePlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueParallelWithInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithPlugin): 
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithPrePlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedParallelWithInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailedWithInlineAndPrePlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedInlineAndPrePlugin): 
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueParallelWithFailedInlineAndPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithPrePluginAndFailedPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndPrePluginAndFailedPostPlugin):
                {
                    var input = IncreaseValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                    transactions.Add(new Transaction
                    {
                        From = transactionContext.Transaction.From,
                        To = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = new IncreaseValueInput
                        {
                            Key = input.Key,
                            Memo = Guid.NewGuid().ToString()
                        }.ToByteString(),
                        MethodName = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValue),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                    break;
                }

                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedPrePlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndFailedPrePlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithFailedPrePluginAndPostPlugin):
                case nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueWithInlineAndFailedPrePluginAndPostPlugin):
                {
                    var input = IncreaseValueInput.Parser.ParseFrom(transactionContext.Transaction.Params);
                    transactions.Add(new Transaction
                    {
                        From = transactionContext.Transaction.From,
                        To = ParallelTestHelper.BasicFunctionWithParallelContractAddress,
                        Params = new IncreaseValueInput
                        {
                            Key = input.Key,
                            Memo = Guid.NewGuid().ToString()
                        }.ToByteString(),
                        MethodName = nameof(BasicFunctionWithParallelContractContainer.BasicFunctionWithParallelContractStub.IncreaseValueFailed),
                        RefBlockNumber = transactionContext.BlockHeight - 1,
                        RefBlockPrefix =
                            BlockHelper.GetRefBlockPrefix(transactionContext.PreviousBlockHash)
                    });
                    break;
                }
            }
            
            return Task.FromResult(transactions.AsEnumerable());
        }

19 Source : ObstacleController.cs
with MIT License
from Aeroluna

private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
        {
            List<CodeInstruction> instructionList = instructions.ToList();
            bool foundTime = false;
            for (int i = 0; i < instructionList.Count; i++)
            {
                if (!foundTime &&
                    instructionList[i].opcode == OpCodes.Stloc_0)
                {
                    foundTime = true;
                    instructionList.Insert(i, new CodeInstruction(OpCodes.Ldarg_0));
                    instructionList.Insert(i + 1, new CodeInstruction(OpCodes.Ldfld, _obstacleDataField));
                    instructionList.Insert(i + 2, new CodeInstruction(OpCodes.Ldarg_0));
                    instructionList.Insert(i + 3, new CodeInstruction(OpCodes.Ldfld, _move1DurationField));
                    instructionList.Insert(i + 4, new CodeInstruction(OpCodes.Ldarg_0));
                    instructionList.Insert(i + 5, new CodeInstruction(OpCodes.Ldfld, _finishMovementTime));
                    instructionList.Insert(i + 6, new CodeInstruction(OpCodes.Call, _obstacleTimeAdjust));
                }
            }

            if (!foundTime)
            {
                Plugin.Logger.Log("Failed to find stloc.0!", IPA.Logging.Logger.Level.Error);
            }

            return instructionList.AsEnumerable();
        }

19 Source : LogManager.cs
with MIT License
from aguang-xyz

public Task<IEnumerable<string>> GetLogFileNamesAsync()
        {
            try
            {
                var directoryInfo = new DirectoryInfo(PathUtils.LogFolder);
                var fileNames = directoryInfo
                    .GetFiles("*.log")
                    .Select(file => file.Name)
                    .OrderByDescending(fileName => fileName)
                    .AsEnumerable();
                
                return Task.FromResult(fileNames);
            }
            catch (Exception)
            {
                return Task.FromResult(Array.Empty<string>().AsEnumerable());
            }
        }

19 Source : RingBuffer.cs
with MIT License
from Aiko-IT-Systems

public IEnumerator<T> GetEnumerator()
        {
            return !this._reached_end
                ? this.InternalBuffer.AsEnumerable().GetEnumerator()
                : this.InternalBuffer.Skip(this.CurrentIndex)
                .Concat(this.InternalBuffer.Take(this.CurrentIndex))
                .GetEnumerator();
        }

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

private async Task Main_Load(object sender, EventArgs e)
        {
            IoC.Notif.ShowStatus("Loading config...");

            IoC.Bind(new Archiver());
            IoC.Bind(new Localization(ELanguage.English));

            Settings = new SettingsControl();
            Plugins = (
                from plugin in PluginManager.LoadAll<IInteractivePlugin>()
                let idx = IoC.Config.PluginLoadOrder.IndexOf(plugin.PluginName)
                let order = idx < 0 ? int.MaxValue : idx
                orderby order, plugin.PluginName
                select plugin).ToList();

            IoC.Notif.ShowStatus("Loading Plugins...");
            foreach (var module in Plugins.AsEnumerable().Concat(new[] { Settings }).Reverse())
            {
                var tab = new TabItem();
                
                tab.Header = module.PluginName;
                tab.Content = module.PluginControl;

                tcMain.Items.Insert(0, tab);
            }

            await Settings.Initialize();
            Settings.SettingsOkay += Settings_SettingsOkayCommand;

            IoC.Notif.ShowUnknownProgress();

            await RunCompatibility();

            tcMain.SelectedIndex = 0;
            if (!await InitializePlugins())
            {
                tcMain.SelectedIndex = tcMain.Items.Count - 1;
            }

            IoC.Notif.HideProgress();
            IoC.Notif.ShowStatus("Loading complete");

            await TryApplyCommands();
            await TryPatchAndExit();
        }

19 Source : ClickHouseStorage.cs
with MIT License
from akpaevj

public async Task WriteEventLogDataAsync(List<EventLogItem> enreplacedies,
            CancellationToken cancellationToken = default)
        {
            await CreateConnectionAsync(cancellationToken);

            using var copy = new ClickHouseBulkCopy(_connection)
            {
                DestinationTableName = TableName,
                BatchSize = enreplacedies.Count
            };

            var data = enreplacedies.Select(item => new object[]
            {
                item.FileName ?? "",
                item.EndPosition,
                item.LgfEndPosition,
                item.Id,
                item.DateTime,
                item.TransactionStatus ?? "",
                item.TransactionDateTime == DateTime.MinValue ? new DateTime(1970, 1, 1) : item.TransactionDateTime,
                item.TransactionNumber,
                item.UserUuid ?? "",
                item.User ?? "",
                item.Computer ?? "",
                item.Application ?? "",
                item.Connection,
                item.Event ?? "",
                item.Severity ?? "",
                item.Comment ?? "",
                item.MetadataUuid ?? "",
                item.Metadata ?? "",
                item.Data ?? "",
                item.DataPresentation ?? "",
                item.Server ?? "",
                item.MainPort,
                item.AddPort,
                item.Session
            }).AsEnumerable();

            try
            {
                await copy.WriteToServerAsync(data, cancellationToken);
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, $"Failed to write data to {_databaseName}");
                throw;
            }

            _logger?.LogDebug($"{enreplacedies.Count} items were being written to {_databaseName}");
        }

See More Examples