Esempio n. 1
0
        public ParameterItemParser(System.Collections.Generic.IEnumerable <Model.StrategyParameter> parameters)
        {
            var allNames = new Regex("^(" + string.Join("|", parameters.Select(p => p.Id)) + ")$");

            _main = new WordChainParser()
                    .ExpectWord(allNames, "name");
        }
Esempio n. 2
0
        public void ConfigureContainer(ContainerBuilder containerBuilder)
        {
            WebAppTypeFinder typeFinder = new WebAppTypeFinder();

            System.Collections.Generic.IEnumerable <Type> startupConfigurations = typeFinder.FindClassesOfType <IVerivoxStartup>();

            //register engine
            containerBuilder.RegisterInstance(this).As <IEngine>().SingleInstance();

            //register type finder
            containerBuilder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();

            //find dependency registrars provided by other assemblies
            System.Collections.Generic.IEnumerable <Type> dependencyRegistrars = typeFinder.FindClassesOfType <IDependencyRegistrar>();

            //create and sort instances of dependency registrars
            IOrderedEnumerable <IDependencyRegistrar> instances = dependencyRegistrars
                                                                  //.Where(dependencyRegistrar => PluginManager.FindPlugin(dependencyRegistrar)?.Installed ?? true) //ignore not installed plugins
                                                                  .Select(dependencyRegistrar => (IDependencyRegistrar)Activator.CreateInstance(dependencyRegistrar))
                                                                  .OrderBy(dependencyRegistrar => dependencyRegistrar.Order);

            //register all provided dependencies
            foreach (IDependencyRegistrar dependencyRegistrar in instances)
            {
                dependencyRegistrar.Register(containerBuilder);
            }
        }
        public IActionResult List(int?minPrice, int?maxPrice, int page = 1)
        {
            int ITEM_PER_PAGE_SIZE = 5;

            int loggedUserId = this.GetClaim <int>(nameof(DataAccess.Entities.User.Id));

            // count free apartment
            int totalAmount = apartmentRepository.Count(BuildFilter(minPrice, maxPrice));

            // get free apartment
            System.Collections.Generic.IEnumerable <Apartment> apartments =
                apartmentRepository.Get(page: page, amount: ITEM_PER_PAGE_SIZE, filter: BuildFilter(minPrice, maxPrice));

            // save previous filter inputs value
            ViewData[nameof(minPrice)] = minPrice ?? 100;
            ViewData[nameof(maxPrice)] = maxPrice ?? 1000;

            ListViewModel listViewModel = new ListViewModel()
            {
                UserId          = loggedUserId,
                Apartments      = apartments,
                IsUsersRequest  = apartmentRepository.HasRequests(loggedUserId, apartments.Select(a => a.Id).ToArray()),
                PaginationModel = BuildPagination(ITEM_PER_PAGE_SIZE, page, totalAmount, minPrice, maxPrice)
            };

            return(View(listViewModel));
        }
Esempio n. 4
0
 private static System.Collections.Generic.IEnumerable <deviceInfo> getDevices(System.Collections.Generic.IEnumerable <System.Guid> guids, SPDRP[] properties)
 {
     return(guids
            .Select(g => SetupDiGetClassDevs(g, null, System.IntPtr.Zero, DIGCF_PRESENT | DIGCF_PROFILE))
            .Where(h => h.ToInt32() != INVALID_HANDLE_VALUE)
            .SelectMany(h => getDevices(h, properties)));
 }
Esempio n. 5
0
        /// <summary>
        /// Add and configure services
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        /// <returns>Service provider</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            //find startup configurations provided by other assemblies
            WebAppTypeFinder typeFinder = new WebAppTypeFinder();

            System.Collections.Generic.IEnumerable <Type> startupConfigurations = typeFinder.FindClassesOfType <IVerivoxStartup>();

            //create and sort instances of startup configurations
            IOrderedEnumerable <IVerivoxStartup> instances = startupConfigurations
                                                             .Select(startup => (IVerivoxStartup)Activator.CreateInstance(startup))
                                                             .OrderBy(startup => startup.Order);

            //configure services
            foreach (IVerivoxStartup instance in instances)
            {
                instance.ConfigureServices(services, configuration);
            }

            //register dependencies
            VerivoxConfig config = services.BuildServiceProvider().GetService <VerivoxConfig>();

            _serviceProvider = RegisterDependencies(config, services, typeFinder);
            //resolve assemblies here. otherwise, plugins can throw an exception when rendering views
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            return(_serviceProvider);
        }
Esempio n. 6
0
        internal Message Chats(System.Collections.Generic.IEnumerable <ChatRoom> chats)
        {
            var data = new SerializableStorage();

            data.Add("Chats", chats.Select(chat => Tuple.Create(chat.Name, chat.Id, chat.Connections.Select(c => c.Id).ToArray())).ToArray());
            return(CreateMessage(ChatServerMessages.ChatRooms, data));
        }
Esempio n. 7
0
        private static async System.Threading.Tasks.Task SetKeyValueAsync <E>(DbContext dbContext, E entity, System.Collections.Generic.IEnumerable <System.Reflection.PropertyInfo> properties)
            where E : class, new()
        {
            // Creates an ORDER BY statement.
            var strOrder = string.Join(",", properties.Select(e => e.Name).ToArray()) + " DESC";
            // Gets the las entity in the table sorted by the Primary keys.
            var lastEntity = await System.Linq.Dynamic.Core.DynamicQueryableExtensions.OrderBy(dbContext.Set <E>(), strOrder).FirstOrDefaultAsync();

            // If null then it means its a new entity.
            if (lastEntity == null)
            {
                lastEntity = new E();
            }

            System.Threading.Tasks.Parallel.ForEach(properties, (p) =>
            {
                var val = p.GetValue(entity);

                if (val.Equals(GetDefaultValue(p.PropertyType)))
                {
                    val = GetKeyValue(ref lastEntity, p);
                }

                p.SetValue(entity, val);
            });
        }
Esempio n. 8
0
        public void test_ToEnumerableAttributes()
        {
            Runtime rt = TestingHelpers.LoadSmallRuntime <TitanicDataRow>("titanic_train.csv", 0, 5);

            System.Collections.Generic.IEnumerable <PmlAttribute> atts = rt.Impl.ToEnumerableAttributes();
            string[] names = atts.Select(a => a.Name).ToArray();
            CollectionAssert.AreEqual(new[] { "survived", "pclass", "sex", "embarked" }, names);
        }
Esempio n. 9
0
        public override async System.Threading.Tasks.Task <System.Collections.Generic.IEnumerable <Lpp.Dns.DTO.RequestObserverDTO> > InsertOrUpdate(System.Collections.Generic.IEnumerable <Lpp.Dns.DTO.RequestObserverDTO> values)
        {
            //This no longer works as we are setting the ID on the new observers at the portal side.
            //The update base code doesn't inser those entities in the database, thus we need to manually update/insert.
            //var result = await base.InsertOrUpdate(values);

            Guid        requestID   = values.First().RequestID;
            List <Guid> observerIDs = values.Select(p => p.ID.Value).ToList();

            //PMNDEV-4548 - We are only inserting new Observers via the Observer Add dialog and will not be handling deletions/removals.
            //Check if we need to delete any entities
            //if (DataContext.RequestObservers.Any(p => p.RequestID == requestID && observerIDs.Contains(p.ID) == false))
            //{
            //    var toDelete = DataContext.RequestObservers.Where(p => p.RequestID == requestID && observerIDs.Contains(p.ID) == false);
            //    DataContext.RequestObservers.RemoveRange(toDelete);
            //}

            foreach (var observer in values)
            {
                if (DataContext.RequestObservers.Any(p => p.ID == observer.ID))
                {
                    //Existing Observer
                    await base.Update(values.Where(p => p.ID == observer.ID));
                }
                else
                {
                    //New Observer
                    RequestObserver newObserver = DataContext.RequestObservers.Create();
                    newObserver.ID              = observer.ID.Value;
                    newObserver.DisplayName     = observer.DisplayName;
                    newObserver.Email           = observer.Email;
                    newObserver.RequestID       = observer.RequestID;
                    newObserver.SecurityGroupID = observer.SecurityGroupID;
                    newObserver.UserID          = observer.UserID;
                    DataContext.RequestObservers.Add(newObserver);
                }
            }
            await DataContext.SaveChangesAsync();

            if (values.Any(p => p.EventSubscriptions.Any(es => es.RequestObserverID == Guid.Empty)))
            {
                var toInsertCollection = values.Where(p => p.EventSubscriptions.Any(es => es.RequestObserverID == Guid.Empty));
                foreach (var observer in toInsertCollection)
                {
                    foreach (var observerEventSubscription in observer.EventSubscriptions.Where(p => p.RequestObserverID == Guid.Empty))
                    {
                        var obj = DataContext.RequestObserverEventSubscriptions.Create();
                        obj.EventID           = observerEventSubscription.EventID;
                        obj.Frequency         = observerEventSubscription.Frequency.HasValue ? observerEventSubscription.Frequency.Value : DTO.Enums.Frequencies.Immediately;
                        obj.RequestObserverID = observer.ID.Value;
                        DataContext.RequestObserverEventSubscriptions.Add(obj);
                    }
                }

                await DataContext.SaveChangesAsync();
            }
            return(values);
        }
        public override void AfterCommit(System.Collections.Generic.IEnumerable <IncomingMessage> messages)
        {
            var subscriptionFilterInfos = messages.Select(msg => new SubscriptionFilterInfo
            {
                Metadata = msg.Metadata,
                Queue    = msg.Queue
            }).ToArray();

            Queues.Subscriptions.Notify(subscriptionFilterInfos);
        }
        protected override async Task OnInitializedAsync()
        {
            AuthenticationState authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();

            System.Security.Claims.ClaimsPrincipal user = authState.User;
            if (user.Identity.IsAuthenticated)
            {
                System.Collections.Generic.IEnumerable <System.Security.Claims.Claim> userClaims = user.Claims.Where(claim => claim.Type.Equals(ClaimType));
                Claims = userClaims.Any() ? userClaims.Select(claim => claim.Value).Aggregate(AddClaims) : "";
            }
        }
Esempio n. 12
0
        public ActionResult Index(string[] includedTags, string monthYearPair = "")
        {
            System.Collections.Generic.IEnumerable <IJournalEntry> validEntries    = Enumerable.Empty <IJournalEntry>();
            System.Collections.Generic.IEnumerable <IJournalEntry> filteredEntries = Enumerable.Empty <IJournalEntry>();
            ApplicationUser user = null;

            if (User.Identity.IsAuthenticated)
            {
                user = UserManager.FindById(User.Identity.GetUserId());
                StaffRank userRank = user.GetStaffRank(User);
                validEntries = TemplateCache.GetAll <IJournalEntry>().Where(blog => blog.IsPublished() && (blog.Public || blog.MinimumReadLevel <= userRank));
            }
            else
            {
                validEntries = TemplateCache.GetAll <IJournalEntry>().Where(blog => blog.IsPublished() && blog.Public);
            }

            System.Collections.Generic.IEnumerable <string> allTags = validEntries.SelectMany(blog => blog.Tags).Distinct();
            if (includedTags != null && includedTags.Count() > 0)
            {
                validEntries = validEntries.Where(blog => blog.Tags.Any(tag => includedTags.Contains(tag)));
            }

            if (!string.IsNullOrWhiteSpace(monthYearPair))
            {
                string[] pair  = monthYearPair.Split("|||", StringSplitOptions.RemoveEmptyEntries);
                string   month = pair[0];
                int      year  = -1;

                if (!string.IsNullOrWhiteSpace(month) && int.TryParse(pair[1], out year))
                {
                    filteredEntries = validEntries.Where(blog =>
                                                         month.Equals(blog.PublishDate.ToString("MMMM", CultureInfo.InvariantCulture), StringComparison.InvariantCultureIgnoreCase) &&
                                                         blog.PublishDate.Year.Equals(year));
                }
            }

            if (filteredEntries.Count() == 0)
            {
                filteredEntries = validEntries;
            }

            BlogViewModel vModel = new BlogViewModel(filteredEntries.OrderByDescending(obj => obj.PublishDate))
            {
                AuthedUser     = user,
                MonthYearPairs = validEntries.Select(blog => new Tuple <string, int>(blog.PublishDate.ToString("MMMM", CultureInfo.InvariantCulture), blog.PublishDate.Year)).Distinct(),
                IncludeTags    = includedTags?.Where(tag => tag != "false").ToArray() ?? (new string[0]),
                AllTags        = allTags.ToArray()
            };

            return(View(vModel));
        }
        public async Task GetImageLeaderboardImplementationAsync(string image, string location, ServiceCategory?category, Division?division, Tier?tier, int pageNumber)
        {
            using (Context.Channel.EnterTypingState())
            {
                if (!ScoreRetrievalService.Metadata.SupportsInexpensiveDetailQueries)
                {
                    throw new InvalidOperationException("Image-specific queries cannot be performed on online score providers. Please use datasource to specify an offline score provider.");
                }

                System.Collections.Generic.IEnumerable <ScoreboardSummaryEntry> teams = (await ScoreRetrievalService.GetScoreboardAsync(new ScoreboardFilterInfo(division, tier)).ConfigureAwait(false))?.TeamList;
                if (teams == null)
                {
                    throw new Exception("Error obtaining scoreboard.");
                }

                if (category.HasValue)
                {
                    var catVal = category.Value;
                    teams = teams.Where(t => t.Category == catVal);
                }

                if (location != null)
                {
                    teams = teams.Where(t => t.Location == location);
                }

                string filterDesc = Utilities.JoinNonNullNonEmpty(", ",
                                                                  !division.HasValue ? null : division.Value.ToStringCamelCaseToSpace() + " Division",
                                                                  !tier.HasValue ? null : tier.Value.ToStringCamelCaseToSpace() + " Tier",
                                                                  !category.HasValue ? null : category.Value.ToCanonicalName(),
                                                                  LocationResolutionService.GetFullNameOrNull(location));

                var downloadTasks = teams.Select(t => ScoreRetrievalService.GetDetailsAsync(t.TeamId)).ToArray();

                try
                {
                    await Task.WhenAll(downloadTasks).ConfigureAwait(false);
                }
                catch
                {
                    // oh well?
                }

                await ReplyAsync(
                    message : ScoreEmbedBuilder.CreateImageLeaderboardEmbed(downloadTasks.Where(t => t.IsCompletedSuccessfully).Select(
                                                                                t => new System.Collections.Generic.KeyValuePair <ScoreboardSummaryEntry, ScoreboardImageDetails>(t.Result.Summary,
                                                                                                                                                                                  t.Result.Images.SingleOrDefault(i => i.ImageName.Equals(image, StringComparison.InvariantCultureIgnoreCase))))
                                                                            .Where(kvp => kvp.Value != null).OrderByDescending(kvp => kvp.Value.Score).ThenBy(kvp => kvp.Value.PlayTime),
                                                                            filterDescription: filterDesc, pageNumber: pageNumber)).ConfigureAwait(false);
            }
        }
        public async ValueTask ReturnAllStudentsSpecificationWithIncludesToLoginAndSessionAndCourse()
        {
            const string dbName = "FakeDatabase";

            using (TrainingDb dbContext = this.testFixture.CreateInMemoryDbContext(dbName))
            {
                dbContext.Database.EnsureCreated();
                var repo = new StudentRepository(dbContext);

                var specification = new AllStudentsSpecification();
                System.Collections.Generic.IEnumerable <Student> allStudents =
                    await repo.ListAsync(specification
                                         .Including(st => st.Login));

                allStudents.All(student => specification.Test(student)).Should().BeTrue();

                allStudents.Should().HaveCount(3);

                allStudents.Select(st => st.Login)
                .Should().NotBeNull();
                allStudents.Select(st => st.Sessions)
                .Should().NotBeNull();
                allStudents.SelectMany(st => st.Sessions)
                .Select(ss => ss.Session)
                .Select(s => s.Course).Should().NotBeNull();

                foreach (Student student in allStudents)
                {
                    student.Login.Should().NotBeNull();
                    student.Sessions.Should().NotBeNull();
                    foreach (StudentSession session in student.Sessions)
                    {
                        session.Session.Should().NotBeNull();
                        session.Session.Course.Should().NotBeNull();
                    }
                }
            }
        }
        public static System.Collections.Generic.IEnumerable <System.String> GetNetIdList()
        {
            System.Collections.Generic.IEnumerable <DbNetId> output = null;
            var recElement = Configuration.FileRecognizerConfigurationSection.GetSection().Recognizer;
            var group      = Oits.Configuration.DbMap.DbMapSection.GetSection().Groups[recElement.GroupName];

            using (var cnxn = group.CreateConnection()) {
                cnxn.Open();
                var cmd = group.Commands[recElement.CommandName];
                output = cmd.ExecuteReaderSingleResult <DbNetId>(cnxn, null, theFilter, group.Results[recElement.ResultName]);
            }
            return(output.Select(
                       x => x.NetId
                       ));
        }
Esempio n. 16
0
        private static System.Collections.Generic.IEnumerable <byte> EncryptOutput(byte[] key, System.Collections.Generic.IEnumerable <byte> data)
        {
            byte[] s = EncryptInitalize(key);
            int    i = 0;
            int    j = 0;

            return(data.Select((b) =>
            {
                i = (i + 1) & 255;
                j = (j + s[i]) & 255;
                Swap(s, i, j);

                return (byte)(b ^ s[(s[i] + s[j]) & 255]);
            }));
        }
Esempio n. 17
0
        public override object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            System.Collections.Specialized.NameValueCollection nameValueCollection = controllerContext.HttpContext.Request.Form;

            System.Collections.Generic.IEnumerable <string> keys = nameValueCollection.AllKeys.Where(s => s.StartsWith("acl-"));

            return(keys.Select(s =>
            {
                string[] substring = s.Substring(4).Split('-');
                return new ACLUpdateRecord
                {
                    Role = substring[0],
                    Key = substring[1],
                    Allowed = nameValueCollection[s].Contains("true")
                };
            }).ToList());
        }
    public async ValueTask WorkWithAndExpression()
    {
        const string dbName = "FakeDatabase";

        using TrainingDb dbContext = this.testFixture.CreateInMemoryDbContext(dbName);
        dbContext.Database.EnsureCreated();
        IReadonlyRepository <Login> repo = new Repository <Login, TrainingDb>(dbContext);

        ISpecification <Login> spec =
            this.specificationFactories.For <Login>().Where(l => l.Id >= 1)
            .And(l2 => l2.Id <= 2)
            .Include(l => l.Student);

        System.Collections.Generic.IEnumerable <Login> logins = await repo.ListAsync(spec);

        logins.Should().HaveCount(2);
        logins.Select(l => l.Student).Should().NotBeNull();
    }
        public override bool UpLoad(System.Collections.Generic.IEnumerable <MemberIntegral> datas, string storeId)
        {
            var serverRepository = CurrentRepository;

            if (datas == null)
            {
                return(false);
            }
            //删除重复数据
            var paySNs = CurrentRepository.Entities.Select(o => o.PaySN).ToList();

            datas = datas.Where(o => !paySNs.Exists(p => p == o.PaySN));

            var tempDatas = datas.Select(o => Pharos.Logic.Entity.BaseEntityExtension.InitEntity <MemberIntegral>(o));

            serverRepository.AddRange(tempDatas.ToList());
            return(true);
        }
Esempio n. 20
0
            public static ActionResult GetProfileProperty(int?propertyId, int?portalId)
            {
                ActionResult actionResult = new ActionResult();

                try
                {
                    int pid = portalId ?? PortalSettings.Current.PortalId;
                    if (!PortalSettings.Current.UserInfo.IsSuperUser && PortalSettings.Current.PortalId != pid)
                    {
                        actionResult.AddError(HttpStatusCode.Unauthorized.ToString(), Components.Constants.AuthFailureMessage);
                    }

                    if (actionResult.IsSuccess)
                    {
                        ProfilePropertyDefinition profileProperty = ProfileController.GetPropertyDefinition(propertyId ?? -1, pid);
                        ListController            listController  = new ListController();
                        System.Collections.Generic.IEnumerable <System.Web.UI.WebControls.ListItem> cultureList = DNNLocalization.Localization.LoadCultureInListItems(GetCultureDropDownType(pid), Thread.CurrentThread.CurrentUICulture.Name, "", false);

                        var response = new
                        {
                            Success               = true,
                            ProfileProperty       = MapProfileProperty(profileProperty),
                            UserVisibilityOptions = GetVisibilityOptions(),
                            DataTypeOptions       = listController.GetListEntryInfoItems("DataType").Where(x => !ExcludeControls.Contains(x.Value)).Select(t => new
                            {
                                t.EntryID,
                                Value = DNNLocalization.Localization.GetString(Components.Constants.Prefix + Regex.Replace(t.Value.ToString(), "[ ().-]+", ""), Components.Constants.LocalResourcesFile),
                            }).OrderBy(t => t.Value).ToList(),

                            LanguageOptions = cultureList.Select(c => new
                            {
                                c.Text,
                                c.Value
                            })
                        };
                        actionResult.Data = response;
                    }
                }
                catch (Exception exc)
                {
                    actionResult.AddError(HttpStatusCode.InternalServerError.ToString(), exc.Message);
                }
                return(actionResult);
            }
Esempio n. 21
0
        public async Task <SearchClientResponse> SearchClient(ClientSearchRequest request)
        {
            System.Collections.Generic.IEnumerable <Domain.Models.DbEntities.SearchedClientEntity> dbEntity = await _repository.SearchClient(request);

            return(new SearchClientResponse
            {
                Clients = dbEntity.Select(a =>
                                          new SearchedClient
                {
                    Id = a.Id,
                    FirstName = a.FirstName,
                    LastName = a.LastName,
                    BirthDate = a.BirthDate,
                    City = a.BirthCity,
                    PersonalNumber = a.PersonalNumber,
                    Sex = (Sex)a.SexId
                })
            });
        }
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext is null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            // Only accept enum values
            if (!bindingContext.ModelMetadata.IsFlagsEnum)
            {
                return(CompletedTask);
            }

            ValueProviderResult provideValue = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            // Do nothing if there is no actual values
            if (provideValue == ValueProviderResult.None)
            {
                return(CompletedTask);
            }

            // Get the real enum type
            Type enumType = bindingContext.ModelType;

            enumType = Nullable.GetUnderlyingType(enumType) ?? enumType;

            // Each value self may contains a series of actual values, split it with comma
            System.Collections.Generic.IEnumerable <string> strs = provideValue.Values.SelectMany(s => s.Split(','));

            // Convert all items into enum items.
            System.Collections.Generic.IEnumerable <object> actualValues = strs.Select(valueString => Enum.Parse(enumType, valueString));

            // Merge to final result
            int result = actualValues.Aggregate(0, (current, value) => current | (int)value);

            // Convert to Enum object
            object realResult = Enum.ToObject(enumType, result);

            // Result
            bindingContext.Result = ModelBindingResult.Success(realResult);

            return(CompletedTask);
        }
Esempio n. 23
0
            private ImmutableArray <Location> ScanBlockForDereferencesWithoutNullCheck(SyntaxNodeAnalysisContext context, ISymbol symbol, SyntaxNode containingBlockOrExpression)
            {
                if (containingBlockOrExpression == null)
                {
                    throw new ArgumentNullException(nameof(containingBlockOrExpression));
                }

                if (symbol != null)
                {
                    System.Collections.Generic.IEnumerable <MemberAccessExpressionSyntax> variableUses = from access in containingBlockOrExpression.DescendantNodes().OfType <MemberAccessExpressionSyntax>()
                                                                                                         let symbolAccessed = context.SemanticModel.GetSymbolInfo(access.Expression, context.CancellationToken).Symbol
                                                                                                                              where symbol.Equals(symbolAccessed)
                                                                                                                              select access;
                    if (!containingBlockOrExpression.DescendantNodes().Any(n => this.IsNonNullCheck(n, symbol, context)))
                    {
                        return(variableUses.Select(vu => vu.Expression.GetLocation()).ToImmutableArray());
                    }
                }

                return(ImmutableArray <Location> .Empty);
            }
        public async ValueTask WorkWithCachedSpecification()
        {
            const string dbName = "FakeDatabase";

            using (TrainingDb dbContext = this.testFixture.CreateInMemoryDbContext(dbName))
            {
                dbContext.Database.EnsureCreated();

                IOptions <MemoryCacheOptions> memCacheOptions =
                    Options.Create <MemoryCacheOptions>(new MemoryCacheOptions());
                var memoryCache = new MemoryCache(memCacheOptions);

                IReadonlyRepository <Login> repo =
                    new CachedRepository <Login, TrainingDb>(dbContext, memoryCache);

                ISpecification <Login> spec =
                    this.specificationFactories.For <Login>()
                    .Where(l => l.Id == 1)
                    .Include(l => l.Student)
                    .Not()
                    .AsCached(TimeSpan.FromHours(12), 1);

                System.Collections.Generic.IEnumerable <Login> logins = await repo.ListAsync(spec);

                logins.Should().HaveCount(2);
                logins.Select(l => l.Student).Should().NotBeNull();

                // Let's create a new repository instance with the same cache
                // I would expect in this case that the repository returns the same instances
                // if they have been retrieved from the cache.

                repo =
                    new CachedRepository <Login, TrainingDb>(dbContext, memoryCache);

                System.Collections.Generic.IEnumerable <Login> cachedLogins = await repo.ListAsync(spec);

                cachedLogins.Should().HaveCount(2);
                cachedLogins.Should().BeSameAs(logins);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Register dependencies using Autofac
        /// </summary>
        /// <param name="VerivoxConfig">Startup Verivox configuration parameters</param>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="typeFinder">Type finder</param>
        protected virtual IServiceProvider RegisterDependencies(VerivoxConfig dreamlinesConfig, IServiceCollection services, ITypeFinder typeFinder)
        {
            //var autofacServiceProviderFactory = new AutofacServiceProviderFactory(ConfigureContainer);
            //var containerBuilder = autofacServiceProviderFactory.CreateBuilder(services);
            //containerBuilder.Populate(services);
            //containerBuilder.Build();
            //return autofacServiceProviderFactory.CreateServiceProvider(containerBuilder);

            ContainerBuilder containerBuilder = new ContainerBuilder();

            //register engine
            containerBuilder.RegisterInstance(this).As <IEngine>().SingleInstance();

            //register type finder
            containerBuilder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();

            //find dependency registrars provided by other assemblies
            System.Collections.Generic.IEnumerable <Type> dependencyRegistrars = typeFinder.FindClassesOfType <IDependencyRegistrar>();

            //create and sort instances of dependency registrars
            IOrderedEnumerable <IDependencyRegistrar> instances = dependencyRegistrars
                                                                  //.Where(dependencyRegistrar => PluginManager.FindPlugin(dependencyRegistrar)?.Installed ?? true) //ignore not installed plugins
                                                                  .Select(dependencyRegistrar => (IDependencyRegistrar)Activator.CreateInstance(dependencyRegistrar))
                                                                  .OrderBy(dependencyRegistrar => dependencyRegistrar.Order);

            //register all provided dependencies
            foreach (IDependencyRegistrar dependencyRegistrar in instances)
            {
                dependencyRegistrar.Register(containerBuilder);
            }

            //populate Autofac container builder with the set of registered service descriptors
            containerBuilder.Populate(services);

            //create service provider
            _serviceProvider = new AutofacServiceProvider(containerBuilder.Build());
            return(_serviceProvider);
        }
Esempio n. 26
0
            public static ActionResult GetListInfo(string listName, int?portalId)
            {
                ActionResult actionResult = new ActionResult();

                try
                {
                    int pid = portalId ?? PortalSettings.Current.PortalId;
                    if (!PortalSettings.Current.UserInfo.IsSuperUser && PortalSettings.Current.PortalId != pid)
                    {
                        actionResult.AddError(HttpStatusCode.Unauthorized.ToString(), Components.Constants.AuthFailureMessage);
                    }

                    if (actionResult.IsSuccess)
                    {
                        ListController listController = new ListController();
                        System.Collections.Generic.IEnumerable <ListEntryInfo> entries = listController.GetListEntryInfoItems(listName, "", pid);
                        var response = new
                        {
                            Success = true,
                            listController.GetListInfo(listName, "", pid)?.EnableSortOrder,
                            Entries = entries.Select(t => new
                            {
                                t.EntryID,
                                t.Text,
                                t.Value,
                                t.SortOrder
                            }).OrderBy(x => x.SortOrder)
                        };
                        actionResult.Data = response;
                    }
                }
                catch (Exception exc)
                {
                    actionResult.AddError(HttpStatusCode.InternalServerError.ToString(), exc.Message);
                }
                return(actionResult);
            }
 public System.Collections.Generic.IEnumerable <Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.SendAsyncStep> Wrap(System.Collections.Generic.IEnumerable <Microsoft.Azure.PowerShell.Cmdlets.DesktopVirtualization.Runtime.SendAsyncStep> funcs) => funcs?.Select(Wrap);
 public System.Collections.Generic.IEnumerable <Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Runtime.SendAsyncStep> Wrap(System.Collections.Generic.IEnumerable <Microsoft.Azure.PowerShell.Cmdlets.BareMetal.Runtime.SendAsyncStep> funcs) => funcs?.Select(Wrap);
Esempio n. 29
0
 static void Test(System.Collections.Generic.IEnumerable <int> seq) =>
 Assert.Equal(seq.Last(), Assert.IsType <double>(Evaluation.Predict(seq.Select(x => (double)x).SkipLast(1).ToArray())), 12);
Esempio n. 30
0
        public long Delete <T, ID>(System.Collections.Generic.IEnumerable <ID> ids) where T : class
        {
            var response = _context.Session.Client.Bulk(b => b.DeleteMany(ids.Select(id => id + "")));

            return(response.Items.LongCount());
        }