System.Collections.Generic.IEnumerable.AsQueryable()

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

1226 Examples 7

19 Source : UserStatsGetterTests.cs
with MIT License
from Abdulrhman5

[TestMethod]
        public async Task UsersCountOverToday_ThereIsDescreteData_ShouldReturn24Element()
        {
            var userRepo = new Mock<IRepository<string, AppUser>>();
            var getter = new UserStatsGetter(userRepo.Object);
            var users = new List<AppUser>
            {
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddHours(-2),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddHours(-2),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddHours(-1),
                },
            };

            userRepo.Setup(u => u.Table).Returns(users.AsQueryable());

            var result = await getter.GetUsersCountOverToday();

            replacedert.IsTrue(result.Count == 24);
        }

19 Source : UserStatsGetterTests.cs
with MIT License
from Abdulrhman5

[TestMethod]
        public async Task UsersCountOverMonth_ThereIsDescreteData_ShouldReturn31Element()
        {
            var userRepo = new Mock<IRepository<string, AppUser>>();
            var getter = new UserStatsGetter(userRepo.Object);
            var users = new List<AppUser>
            {
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-2),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-2),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-2),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-5),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-30),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-30),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-31),
                },
                new AppUser
                {
                    CreatedAt= DateTime.UtcNow.AddDays(-40),
                },
            };

            userRepo.Setup(u => u.Table).Returns(users.AsQueryable());

            var result = await getter.GetUsersCountOverMonth();

            replacedert.IsTrue(result.Count == 31 && result[0].Count == 2 && result[25].Count == 1 && result[28].Count == 3);
        }

19 Source : UserStatsGetterTests.cs
with MIT License
from Abdulrhman5

[TestMethod]
        public async Task UsersCountOverTwoYears_HaveValues_ShouldReturnCorrectCounts()
        {
            var userRepo = new Mock<IRepository<string, AppUser>>();
            var getter = new UserStatsGetter(userRepo.Object);
            var users = new List<AppUser>
            {
                new AppUser
                {
                    CreatedAt= new DateTime(DateTime.Now.Year, 4, 1),
                },
                new AppUser
                {
                    CreatedAt= new DateTime(DateTime.Now.Year, 4, 1),
                },
                new AppUser
                {
                    CreatedAt= new DateTime(DateTime.Now.Year-1, 4, 1),
                },
                new AppUser
                {
                    CreatedAt= new DateTime(DateTime.Now.Year, 5, 1),
                },
                new AppUser
                {
                    CreatedAt= new DateTime(DateTime.Now.Year, 6, 1),
                },
                new AppUser
                {
                    CreatedAt= new DateTime(DateTime.Now.Year, 7, 1),
                },
                new AppUser
                {
                    CreatedAt= new DateTime(DateTime.Now.Year-1, 8, 1),
                },
                new AppUser
                {
                    CreatedAt= new DateTime(DateTime.Now.Year-1, 8, 1),
                },
            };

            userRepo.Setup(u => u.Table).Returns(users.AsQueryable());

            var result = await getter.GetUsersCountOverTwoYears();

            replacedert.IsTrue(result.CurrentYear[3] == 2 &&
                result.CurrentYear[4] == 1 &&
                result.CurrentYear[5] == 1 &&
                result.CurrentYear[6] == 1 &&
                result.PreviousYear[3] == 1 &&
                result.PreviousYear[7] == 2 
                );
        }

19 Source : EnumerableExtensions.cs
with MIT License
from Adoxio

public static IQueryable<T> WhereIn<T, TValue>(this IQueryable<T> queryable, Expression<Func<T, TValue>> selector, IEnumerable<TValue> values)
		{
			return values.Any() ? queryable.Where(In(selector, values)) : Enumerable.Empty<T>().AsQueryable();
		}

19 Source : ShoppingCartDataAdapter.cs
with MIT License
from Adoxio

protected IQueryable<Enreplacedy> SelectCarts(OrganizationServiceContext serviceContext, EnreplacedyReference website, EnreplacedyReference user)
		{
			if (user != null && user.LogicalName == "contact")
			{
				return SelectCartsByContact(serviceContext, website, user);
			}

			if (!string.IsNullOrEmpty(VistorId))
			{
				return SelectCartsByVisitorId(serviceContext, website, VistorId);
			}

			return Enumerable.Empty<Enreplacedy>().AsQueryable();
		}

19 Source : MultipleWebsiteCmsDataServiceQueryInterceptor.cs
with MIT License
from Adoxio

private IQueryable<TEnreplacedy> FilterBySecurity<TEnreplacedy>(OrganizationServiceContext context, IQueryable<TEnreplacedy> queryable, CrmEnreplacedyRight right) where TEnreplacedy : Enreplacedy
		{
			return queryable.ToList().Where(e => HasRight(context, e, right)).AsQueryable();
		}

19 Source : SingleWebsiteCmsDataServiceQueryInterceptor.cs
with MIT License
from Adoxio

private IQueryable<TEnreplacedy> FilterByWebsiteAndSecurity<TEnreplacedy>(OrganizationServiceContext context, IQueryable<TEnreplacedy> queryable, CrmEnreplacedyRight right) where TEnreplacedy : Enreplacedy
		{
			var query = from e in queryable
				where e.GetAttributeValue<EnreplacedyReference>("adx_websiteid") == _website
				select e;

			return query.ToList().Where(e => HasRight(context, e, right)).AsQueryable();
		}

19 Source : SingleWebsiteCmsDataServiceQueryInterceptor.cs
with MIT License
from Adoxio

private IQueryable<TEnreplacedy> FilterByTransitionalRulesAllowed<TEnreplacedy>(OrganizationServiceContext context, IQueryable<TEnreplacedy> queryable, CrmEnreplacedyRight right, Guid fromStateID) where TEnreplacedy : Enreplacedy
		{
			var transitionProvider =
					PortalCrmConfigurationManager.CreateDependencyProvider().GetDependency<IPublishingStateTransitionSecurityProvider>();

			var website = context.CreateQuery("adx_website").First(ws => ws.GetAttributeValue<Guid?>("adx_websiteid") == _website.Id);

			var query = queryable.ToList().Where(e => transitionProvider.Tryreplacedert(context, website, fromStateID,
				e.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid") == null ? Guid.Empty : e.GetAttributeValue<EnreplacedyReference>("adx_publishingstateid").Id)).AsQueryable();

			return FilterByWebsiteAndSecurity(context, query, CrmEnreplacedyRight.Read);
		}

19 Source : LookupControlTemplate.cs
with MIT License
from Adoxio

private IQueryable<Enreplacedy> GetLookupRecords(string fetchXml, OrganizationServiceContext context)
		{
			var fetch = Fetch.Parse(fetchXml);

			var crmEnreplacedyPermissionProvider = new CrmEnreplacedyPermissionProvider();

			crmEnreplacedyPermissionProvider.TryApplyRecordLevelFiltersToFetch(context, CrmEnreplacedyPermissionRight.Read, fetch);

			crmEnreplacedyPermissionProvider.TryApplyRecordLevelFiltersToFetch(context, CrmEnreplacedyPermissionRight.Append, fetch);

            // Apply Content Access Level filtering
            var contentAccessLevelProvider = new ContentAccessLevelProvider();
            contentAccessLevelProvider.TryApplyRecordLevelFiltersToFetch(CrmEnreplacedyPermissionRight.Read, fetch);

            // Apply Product filtering
            var productAccessProvider = new ProductAccessProvider();
            productAccessProvider.TryApplyRecordLevelFiltersToFetch(CrmEnreplacedyPermissionRight.Read, fetch);

            var response = (RetrieveMultipleResponse)context.Execute(fetch.ToRetrieveMultipleRequest());

			var data = response.EnreplacedyCollection;

			if (data == null || data.Enreplacedies == null) return null;

			return data.Enreplacedies.AsQueryable();
		}

19 Source : XrmQueryExtensions.cs
with MIT License
from Adoxio

public static IQueryable<Enreplacedy> FilterByNames(this IQueryable<Enreplacedy> query, List<Tuple<string, string>> values)
		{
			return !values.Any()
				? new List<Enreplacedy>().AsQueryable()
				: query.Where(ContainsPropertyValueEqual<Enreplacedy>("returnedtypecode", "name", values));
		}

19 Source : SingleWebsiteCmsDataServiceQueryInterceptor.cs
with MIT License
from Adoxio

private IQueryable<TEnreplacedy> FilterByWebsiteAndSecurity<TEnreplacedy>(OrganizationServiceContext context, IQueryable<TEnreplacedy> queryable) where TEnreplacedy : Enreplacedy
		{
			var query =
				from e in queryable
				where e.GetAttributeValue<Guid?>("adx_websiteid") == _websiteID
				select e;

			return query.ToList().Where(e => HasReadAccess(context, e)).AsQueryable();
		}

19 Source : SingleWebsiteCmsDataServiceQueryInterceptor.cs
with MIT License
from Adoxio

private IQueryable<TEnreplacedy> FilterWebLinks<TEnreplacedy>(OrganizationServiceContext context, IQueryable<TEnreplacedy> queryable) where TEnreplacedy : Enreplacedy
		{
			var webLinkSets = FilterByWebsiteAndSecurity(context, context.CreateQuery("adx_weblinkset"))
				.ToLookup(e => e.GetAttributeValue<Guid>("adx_weblinksetid"));

			var webLinks = queryable.ToList().Where(e =>
			{
				var webLinkSetID = e.GetAttributeValue<Guid?>("adx_weblinksetid");

				return webLinkSetID.HasValue && webLinkSets.Contains(webLinkSetID.Value);
			});

			return webLinks.Where(wl => HasReadAccess(context, wl)).AsQueryable();
		}

19 Source : ServiceRequest.aspx.cs
with MIT License
from Adoxio

protected void Page_Load(object sender, EventArgs e)
		{
			Thumbnail.ImageUrl = GetThumbnailUrl(Enreplacedy);

			CreateRequestLink.NavigateUrl = GetFirstChildUrl();

			var maxLatestArticlesSetting = ServiceContext.GetSiteSettingValueByName(Website, "service_request_max_kb_articles");

			int maxLatestArticles;

			maxLatestArticles = int.TryParse(maxLatestArticlesSetting, out maxLatestArticles) ? maxLatestArticles : 3;

			var latestArticles = Enumerable.Empty<Enreplacedy>().AsQueryable();

			var subject = Enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_subjectid");

			if (subject != null)
			{
				latestArticles = XrmContext.CreateQuery("kbarticle")
					.Where(k => k.GetAttributeValue<OptionSetValue>("statecode") != null
						&& k.GetAttributeValue<OptionSetValue>("statecode").Value == (int)Enums.KbArticleState.Published
						&& k.GetAttributeValue<bool?>("msa_publishtoweb").GetValueOrDefault(false)
						&& k.GetAttributeValue<EnreplacedyReference>("subjectid").Id == subject.Id)
					.OrderByDescending(k => k.GetAttributeValue<DateTime>("createdon"))
					.Take(maxLatestArticles);
			}

			LatestArticlesList.DataSource = latestArticles;
			LatestArticlesList.DataBind();
		}

19 Source : EntitesGridModel.cs
with Apache License 2.0
from Aguafrommars

protected virtual void OnStort(SortEventArgs arg)
        {
            Collection = Collection.AsQueryable().Sort(arg.OrderBy).ToList();
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Theory]
        [InlineData(DbTypes.InMemory)]
        [InlineData(DbTypes.MySql)]
        [InlineData(DbTypes.Oracle)]
        [InlineData(DbTypes.PostgreSQL)]
        [InlineData(DbTypes.Sqlite)]
        [InlineData(DbTypes.SqlServer)]
        public void UseDatabaseFromConfiguration_should_configure_context_per_db_type(DbTypes dbTypes)
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["ConnectionStrings:DefaultConnection"] = "invalid",
                ["DbType"] = dbTypes.ToString(),
                ["Migrate"] = "true",
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            if (dbTypes != DbTypes.InMemory)
            {
                replacedert.ThrowsAny<Exception>(() => host.Start());
            }            
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_redis_storage()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.Redis.ToString(),
                ["DataProtectionOptions:StorageConnectionString"] = "localhost:6379"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_registry_storage()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.Registry.ToString(),
                ["DataProtectionOptions:StorageConnectionString"] = @"SOFTWARE\Microsoft"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_storage_azure_protection()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.None.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.AzureKeyVault.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:AzureKeyVaultKeyId"] = "http://test",
                ["DataProtectionOptions:KeyProtectionOptions:AzureKeyVaultClientId"] = "test",
                ["DataProtectionOptions:KeyProtectionOptions:AzureKeyVaultClientSecret"] = "test",
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_storage_dpapi_protection()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.None.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.WindowsDpApi.ToString()
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_storage_dpaping_protection()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.None.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.WindowsDpApiNg.ToString()
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_storage_cert_protection()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.None.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.X509.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:X509CertificateThumbprint"] = "test"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            replacedert.Throws<InvalidOperationException>(() => WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_storage_cert_file_protection()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.None.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.X509.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:X509CertificatePath"] = "theidserver.pfx",
                ["DataProtectionOptions:KeyProtectionOptions:X509CertificatePreplacedword"] = "YourSecurePreplacedword"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_algorithms()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:AuthenticatedEncryptorConfiguration:EncryptionAlgorithm"] = EncryptionAlgorithm.AES_128_CBC.ToString(),
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_keys_rotation_azure_storage()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = KeyKinds.KeysRotation.ToString(),
                ["IdenreplacedyServer:Key:StorageKind"] = StorageKind.AzureStorage.ToString(),
                ["IdenreplacedyServer:Key:StorageConnectionString"] = "https://azure.com?sv=test"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_keys_rotation_ef_storage()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = KeyKinds.KeysRotation.ToString(),
                ["IdenreplacedyServer:Key:StorageKind"] = StorageKind.EnreplacedyFramework.ToString()
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_keys_rotation_fs_storage()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = KeyKinds.KeysRotation.ToString(),
                ["IdenreplacedyServer:Key:StorageKind"] = StorageKind.FileSystem.ToString(),
                ["IdenreplacedyServer:Key:StorageConnectionString"] = @"C:\test"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_keys_rotation_redis_storage()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = KeyKinds.KeysRotation.ToString(),
                ["IdenreplacedyServer:Key:StorageKind"] = StorageKind.Redis.ToString(),
                ["IdenreplacedyServer:Key:StorageConnectionString"] = "localhost:6379"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_keys_rotation_storage_azure_protection()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = KeyKinds.KeysRotation.ToString(),
                ["IdenreplacedyServer:Key:StorageKind"] = StorageKind.None.ToString(),
                ["IdenreplacedyServer:Key:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.AzureKeyVault.ToString(),
                ["IdenreplacedyServer:Key:KeyProtectionOptions:AzureKeyVaultKeyId"] = "test",
                ["IdenreplacedyServer:Key:KeyProtectionOptions:AzureKeyVaultClientId"] = "test",
                ["IdenreplacedyServer:Key:KeyProtectionOptions:AzureKeyVaultClientSecret"] = "test",
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_keys_rotation_storage_cert_protection()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = KeyKinds.KeysRotation.ToString(),
                ["IdenreplacedyServer:Key:StorageKind"] = StorageKind.None.ToString(),
                ["IdenreplacedyServer:Key:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.X509.ToString(),
                ["IdenreplacedyServer:Key:KeyProtectionOptions:X509CertificateThumbprint"] = "test"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            replacedert.Throws<InvalidOperationException>(() => WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_keys_rotation_storage_cert_file_protection()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["IdenreplacedyServer:Key:Type"] = KeyKinds.KeysRotation.ToString(),
                ["IdenreplacedyServer:Key:StorageKind"] = StorageKind.None.ToString(),
                ["IdenreplacedyServer:Key:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.X509.ToString(),
                ["IdenreplacedyServer:Key:KeyProtectionOptions:X509CertificatePath"] = "theidserver.pfx",
                ["IdenreplacedyServer:Key:KeyProtectionOptions:X509CertificatePreplacedword"] = "YourSecurePreplacedword"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_initial_data()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["ConnectionStrings:DefaultConnection"] = "Data source=./db.sql",
                ["DbType"] = "Sqlite",
                ["Migrate"] = "true",
                ["Seed"] = "true",
                ["SeedProvider"] = "true"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            host.Start();

            storeMock.Verify();
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_load_provider_configuration()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["PrivateServerAuthentication:ApiUrl"] = "https://localhost:7443/api",
                ["Proxy"] = "true"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<Auth.SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<Auth.SchemeDefinition>().AsQueryable()).Verifiable();
            var culturestoreMock = new Mock<IAdminStore<Culture>>();
            culturestoreMock.Setup(m => m.GetAsync(It.IsAny<PageRequest>(), default)).ReturnsAsync(new PageResponse<Culture>
            {
                Items = Array.Empty<Culture>()
            });
            var sut = new Startup(configuration, environementMock.Object);
            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services => 
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                    services.AddTransient(p => culturestoreMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            host.Start();

            storeMock.Verify();
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_azure_storage()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.AzureStorage.ToString(),
                ["DataProtectionOptions:StorageConnectionString"] = "https://md-3r0d4kzc5jhz.blob.core.windows.net/s3vffgdlczdj/abcd?sv=2017-04-17&sr=b&si=e931bb4b-8a79-4119-b4bb-8b2c1b763369&sig=SIGNATURE_WILL_BE_HERE"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_ef_storage()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.EnreplacedyFramework.ToString()
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_fs_storage()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.FileSystem.ToString(),
                ["DataProtectionOptions:StorageConnectionString"] = @"C:\test"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_storage_dpaping_protection_with_cert()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.None.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.WindowsDpApiNg.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:WindowsDpApiNgCerticate"] = "test"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : StartupTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public void Configure_should_configure_data_protection_storage_dpaping_protection_with_sid()
        {
            var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string, string>
            {
                ["DataProtectionOptions:StorageKind"] = StorageKind.None.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:KeyProtectionKind"] = KeyProtectionKind.WindowsDpApiNg.ToString(),
                ["DataProtectionOptions:KeyProtectionOptions:WindowsDpApiNgSid"] = "test"
            }).Build();
            var environementMock = new Mock<IWebHostEnvironment>();
            var storeMock = new Mock<IDynamicProviderStore<SchemeDefinition>>();
            storeMock.SetupGet(m => m.SchemeDefinitions).Returns(Array.Empty<SchemeDefinition>().AsQueryable()).Verifiable();

            var sut = new Startup(configuration, environementMock.Object);

            using var host = WebHost.CreateDefaultBuilder()
                .ConfigureServices(services =>
                {
                    sut.ConfigureServices(services);
                    services.AddTransient(p => storeMock.Object);
                })
                .Configure(builder => sut.Configure(builder))
                .UseSerilog((hostingContext, configuration) =>
                        configuration.ReadFrom.Configuration(hostingContext.Configuration))
                .Build();

            replacedert.Null(host.Services.GetService<IXmlRepository>());
        }

19 Source : RepositoryPattern.cs
with The Unlicense
from ahotko

public IEnumerable<T> List(Expression<Func<T, bool>> predicate)
        {
            return _enreplacedyRepository.AsQueryable().Where<T>(predicate).OrderBy(o => o.Id);
        }

19 Source : RepositoryPattern.cs
with The Unlicense
from ahotko

public IEnumerable<Enreplacedy> Find(Expression<Func<Enreplacedy, bool>> predicate)
        {
            return _enreplacedyRepository.AsQueryable().Where(predicate).OrderBy(o => o.Id);
        }

19 Source : Extensions.cs
with MIT License
from aletc1

public static IQueryable ApplyTo<TEnreplacedy>(this HttpRequest request, IQueryable<TEnreplacedy> query)
            where TEnreplacedy : clreplaced
        {
            // Parte 1 - Se registran los componentes requeridos por la implementación de 
            // Microsoft ASP.NET Core OData y se memorizan en una variable estática
            if (_provider == null)
            {
                var collection = new ServiceCollection();
                collection.AddMvcCore(options =>
                {
                    options.EnableEndpointRouting = false;
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

                collection.AddOData();
                collection.AddTransient<ODataUriResolver>();
                collection.AddTransient<ODataQueryValidator>();
                collection.AddTransient<TopQueryValidator>();
                collection.AddTransient<FilterQueryValidator>();
                collection.AddTransient<SkipQueryValidator>();
                collection.AddTransient<OrderByQueryValidator>();
                _provider = collection.BuildServiceProvider();
            }

            // Parte 2 - Se configura la ruta de ASP.NET Core OData
            if (_routeBuilder == null)
            {
                _routeBuilder = new RouteBuilder(new ApplicationBuilder(_provider));
                _routeBuilder.EnableDependencyInjection();
            }

            // Parte 3 - Se simula un pedido HTTP como si viniese desde ASP.NET Core
            var modelBuilder = new ODataConventionModelBuilder(_provider);
            modelBuilder.AddEnreplacedyType(typeof(TEnreplacedy));
            var edmModel = modelBuilder.GetEdmModel();

            var httpContext = new DefaultHttpContext
            {
                RequestServices = _provider
            };
            HttpRequest req = new DefaultHttpRequest(httpContext)
            {
                Method = "GET",
                Host = request.Host,
                Path = request.Path,
                QueryString = request.QueryString
            };

            var oDataQueryContext = new ODataQueryContext(edmModel, typeof(TEnreplacedy), new Microsoft.AspNet.OData.Routing.ODataPath());
            var odataQuery = new ODataQueryOptions<TEnreplacedy>(oDataQueryContext, req);

            // Parte 4 - Se aplica la consulta OData al queryable que nos pasan por parámetro
            return odataQuery.ApplyTo(query.AsQueryable());
        }

19 Source : FunctionODataExample.cs
with MIT License
from aletc1

[FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "products")] HttpRequest req,
            ILogger log)
        {
            // Inicializamos una lista de productos (Puede ser una tabla de SQL o CosmosDB a trav�s de Enreplacedy Framework Core)
            var data = new List<Product>() {
                new Product() { replacedle = "Mountain Bike SERIOUS ROCKVILLE", Category = "Mountain Bicycle" },
                new Product() { replacedle = "Mountain Bike el�ctrica HAIBIKE SDURO HARD SEVEN", Category = "Mountain Bicycle" },
                new Product() { replacedle = "Sill�n BROOKS CAMBIUM C15 CARVED ALL WEATHER", Category = "Sillin" },
                new Product() { replacedle = "Poncho VAUDE COVERO II Amarillo", Category = "Chaquetas" },
            };

            // Aplicamos la consulta OData al IQueryable<Product> a la fuente de datos anterior
            var result = req.ApplyTo<Product>(data.AsQueryable());

            // Se retorna el resultado
            return new OkObjectResult(result);
        }

19 Source : CacheManager.cs
with GNU General Public License v3.0
from alexdillon

public IQueryable<Message> GetMessagesForGroup(IMessageContainer group)
            {
                if (group is Group g)
                {
                    return this.Messages
                        .AsNoTracking()
                        .Where(m => m.GroupId == g.Id);
                }
                else if (group is Chat c)
                {
                    // Chat.Id returns the Id of the other user
                    // Conversation IDs are user1+user2.
                    return this.Messages
                        .AsNoTracking()
                        .Where(m => m.ConversationId == c.ConversationId);
                }
                else
                {
                    return Enumerable.Empty<Message>().AsQueryable();
                }
            }

19 Source : PersistManager.cs
with GNU General Public License v3.0
from alexdillon

public static IQueryable<StarredMessage> GetStarredMessagesForGroup(IMessageContainer group, PersistContext persistContext)
        {
            if (group is Group g)
            {
                return persistContext.StarredMessages
                    .AsNoTracking()
                    .Where(m => m.ConversationId == g.Id);
            }
            else if (group is Chat c)
            {
                // Chat.Id returns the Id of the other user
                // However, GroupMe messages are natively returned with a Conversation Id instead
                // Conversation IDs are user1+user2.
                var conversationId = c.LatestMessage.ConversationId;

                return persistContext.StarredMessages
                    .AsNoTracking()
                    .Where(m => m.ConversationId == conversationId);
            }
            else
            {
                return Enumerable.Empty<StarredMessage>().AsQueryable();
            }
        }

19 Source : PersistManager.cs
with GNU General Public License v3.0
from alexdillon

public static IQueryable<HiddenMessage> GetHiddenMessagesForGroup(IMessageContainer group, PersistContext persistContext)
        {
            if (group is Group g)
            {
                return persistContext.HiddenMessages
                    .AsNoTracking()
                    .Where(m => m.ConversationId == g.Id);
            }
            else if (group is Chat c)
            {
                // Chat.Id returns the Id of the other user
                // However, GroupMe messages are natively returned with a Conversation Id instead
                // Conversation IDs are user1+user2.
                var conversationId = c.LatestMessage.ConversationId;

                return persistContext.HiddenMessages
                    .AsNoTracking()
                    .Where(m => m.ConversationId == conversationId);
            }
            else
            {
                return Enumerable.Empty<HiddenMessage>().AsQueryable();
            }
        }

19 Source : SearchViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void UpdateSearchResults()
        {
            if (this.DeferSearchUpdating)
            {
                return;
            }

            this.ResultsView.Messages = null;

            var messagesForGroupChat = this.GetMessagesForGroup(this.SelectedGroupChat);

            var startDate = this.FilterStartDate;
            var endDate = (this.FilterEndDate == DateTime.MinValue) ? DateTime.Now : this.FilterEndDate.AddDays(1);

            var startDateUnix = ((DateTimeOffset)startDate).ToUnixTimeSeconds();
            var endDateUnix = ((DateTimeOffset)endDate).ToUnixTimeSeconds();

            var results = messagesForGroupChat
                .Where(m => m.Text.ToLower().Contains(this.SearchTerm.ToLower()))
                .Where(m => m.CreatedAtUnixTime >= startDateUnix)
                .Where(m => m.CreatedAtUnixTime <= endDateUnix);

            var filteredMessages = Enumerable.Empty<Message>().AsQueryable();
            var filtersApplied = false;

            if (this.FilterHasAttachedImage)
            {
                var messagesWithImages = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<ImageAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithImages);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedLinkedImage)
            {
                var messagesWithLinkedImages = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<LinkedImageAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithLinkedImages);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedVideo)
            {
                var messagesWithVideos = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<VideoAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithVideos);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedMentions)
            {
                var messagesWithMentions = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<MentionsAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithMentions.AsEnumerable());
                filtersApplied = true;
            }

            if (!filtersApplied)
            {
                // No attachment filters were selected, so show all messages
                filteredMessages = results;
            }

            var orderedMessages = filteredMessages
                .OrderByDescending(m => m.Id);

            this.ResultsView.replacedociateWith = this.SelectedGroupChat;

            // TODO: Can we disable Client Side evaluation? Breaking change in Enreplacedy Framework Core 3
            // Enabling filters will be a lot faster if we can.
            this.ResultsView.Messages = orderedMessages;
            this.ResultsView.ChangePage(0);
        }

19 Source : SearchViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void UpdateSearchResults()
        {
            if (this.DeferSearchUpdating)
            {
                return;
            }

            this.ResultsView.DisplayMessages(null, null);

            var cacheContext = this.CacheManager.OpenNewContext();
            var messagesForGroupChat = cacheContext.GetMessagesForGroup(this.SelectedGroupChat);

            var startDate = this.FilterStartDate;
            var endDate = (this.FilterEndDate == DateTime.MinValue) ? DateTime.Now : this.FilterEndDate.AddDays(1);

            var startDateUnix = ((DateTimeOffset)startDate).ToUnixTimeSeconds();
            var endDateUnix = ((DateTimeOffset)endDate).ToUnixTimeSeconds();

            IQueryable<Message> messagesFromMemberForGroupChat;
            if (this.FilterMessagesFrom == null)
            {
                // Show messages from all chat members
                messagesFromMemberForGroupChat = messagesForGroupChat;
            }
            else
            {
                var userId = this.FilterMessagesFrom.UserId;
                if (string.IsNullOrEmpty(userId) && this.SelectedGroupChat is Chat chat)
                {
                    // In Chats, the OtherUser field doesn't have the UserId set from GroupMe's API...
                    userId = chat.Id;
                }

                messagesFromMemberForGroupChat = messagesForGroupChat
                    .Where(m => m.UserId == userId);
            }

            var results = messagesFromMemberForGroupChat;

            // Apply query terms
            if (this.FilterIsExact)
            {
                results = results.Where(m => m.Text.ToLower().Contains(this.SearchTerm.ToLower()));
            }
            else if (this.FilterIsANDTerm)
            {
                foreach (var keyword in this.SearchTerm.ToLower().Split(' '))
                {
                    results = results.Where(m => m.Text.ToLower().Contains(keyword));
                }
            }

            // Apply time range filter
            results = results
                .Where(m => m.CreatedAtUnixTime >= startDateUnix)
                .Where(m => m.CreatedAtUnixTime <= endDateUnix);

            var filteredMessages = Enumerable.Empty<Message>().AsQueryable();
            var filtersApplied = false;

            // TODO: Can we disable Client Side evaluation for filters? Breaking change in Enreplacedy Framework Core 3
            // Enabling filters will be a lot faster if we can.
            if (this.FilterHasAttachedImage)
            {
                var messagesWithImages = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<ImageAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithImages);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedLinkedImage)
            {
                var messagesWithLinkedImages = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<LinkedImageAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithLinkedImages);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedVideo)
            {
                var messagesWithVideos = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<VideoAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithVideos);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedDoreplacedent)
            {
                var messagesWithDoreplacedents = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<FileAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithDoreplacedents);
                filtersApplied = true;
            }

            if (this.FilterHasAttachedMentions)
            {
                var messagesWithMentions = results.AsEnumerable()
                    .Where(m => m.Attachments.OfType<MentionsAttachment>().Count() >= 1);

                filteredMessages = filteredMessages.Union(messagesWithMentions);
                filtersApplied = true;
            }

            if (!filtersApplied)
            {
                // No attachment filters were selected, so show all messages
                filteredMessages = results;
            }

            var orderedMessages = filteredMessages
                .OrderByDescending(m => m.Id);

            this.ResultsView.replacedociateWith = this.SelectedGroupChat;
            this.ResultsView.DisplayMessages(orderedMessages, cacheContext);
            _ = this.ResultsView.LoadPage(0);
        }

19 Source : StarsViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void LoadHiddenMessages()
            {
                using (var persistContext = this.PersistManager.OpenNewContext())
                {
                    var cacheContext = this.CacheManager.OpenNewContext();

                    var hiddenList = PersistManager.GetHiddenMessagesForGroup(this.MessageContainer, persistContext);
                    var messagesList = new List<Message>();

                    foreach (var hidden in hiddenList)
                    {
                        var msg = cacheContext.Messages.FirstOrDefault(m => m.Id == hidden.MessageId);
                        messagesList.Add(msg);
                    }

                    this.IsEmpty = messagesList.Count == 0;
                    this.Type = "Hidden";

                    var sortedMessages = messagesList
                        .AsQueryable()
                        .OrderBy(m => m.CreatedAtUnixTime);

                    this.MessagesList.DisplayMessages(sortedMessages, cacheContext);
                    _ = this.MessagesList.LoadPage(0);
                }
            }

19 Source : SearchViewModel.cs
with GNU General Public License v3.0
from alexdillon

private IQueryable<Message> GetMessagesForGroup(IMessageContainer group)
        {
            if (group is Group g)
            {
                return this.CacheContext.Messages
                    .AsNoTracking()
                    .Where(m => m.GroupId == g.Id);
            }
            else if (group is Chat c)
            {
                // Chat.Id returns the Id of the other user
                // However, GroupMe messages are natively returned with a Conversation Id instead
                // Conversation IDs are user1+user2.
                var sampleMessage = c.Messages.FirstOrDefault();

                return this.CacheContext.Messages
                    .AsNoTracking()
                    .Where(m => m.ConversationId == sampleMessage.ConversationId);
            }
            else
            {
                return Enumerable.Empty<Message>().AsQueryable();
            }
        }

19 Source : StarsViewModel.cs
with GNU General Public License v3.0
from alexdillon

private void LoadStarredMessages()
            {
                using (var persistContext = this.PersistManager.OpenNewContext())
                {
                    var cacheContext = this.CacheManager.OpenNewContext();
                    var starList = PersistManager.GetStarredMessagesForGroup(this.MessageContainer, persistContext);
                    var messagesList = new List<Message>();

                    foreach (var star in starList)
                    {
                        var msg = cacheContext.Messages.FirstOrDefault(m => m.Id == star.MessageId);
                        messagesList.Add(msg);
                    }

                    this.IsEmpty = messagesList.Count == 0;
                    this.Type = "Starred";

                    var sortedMessages = messagesList
                        .AsQueryable()
                        .OrderBy(m => m.CreatedAtUnixTime);

                    this.MessagesList.DisplayMessages(sortedMessages, cacheContext);
                    _ = this.MessagesList.LoadPage(0);
                }
            }

19 Source : ExpressionCompilationTests.cs
with Apache License 2.0
from alexz76

[Fact]
		public void ExpressionTree_TestOne()
		{
			// Arrange
			var companies = new[]
			{
				"Consolidated Messenger", "Alpine Ski House", "Southridge Video", "City Power & Light", "Coho Winery", "Wide World Importers",
				"Graphic Design Insreplacedute", "Adventure Works", "Humongous Insurance", "Woodgrove Bank", "Margie's Travel", "Northwind Traders",
				"Blue Yonder Airlines", "Trey Research", "The Phone Company", "Wingtip Toys", "Lucerne Publishing", "Fourth Coffee"
			}.AsQueryable();

			var expParameter = Expression.Parameter(typeof(string), "company");
			var expArguments = Expression.Constant("ho");
			var expContains = Expression.Call(expParameter, typeof(string).GetMethod(nameof(string.Contains), new[] { typeof(string) }), new[] { expArguments });

			var expContainsIsTrue = Expression.IsTrue(expContains);

			var isTrueCall = Expression.Call(
				typeof(Queryable),
				nameof(Queryable.Where),
				new[] { companies.ElementType },
				companies.Expression,
				Expression.Lambda<Func<string, bool>>(expContainsIsTrue, new[] { expParameter }));

			// Act
			var results = companies.Provider.CreateQuery<string>(isTrueCall);

			// replacedert
			results.Any().Should().BeTrue();
			results.Count().Should().BeGreaterThan(0);
		}

See More Examples