Exemple #1
0
        private static bool ShouldFetchFromServer(ApplicationSchemaDefinition detail, ApplicationSchemaDefinition list)
        {
            if (detail == null)
            {
                //sometimes we might need only to see the list
                return(false);
            }
            if (EnumerableExtensions.Any(detail.Associations) || EnumerableExtensions.Any(detail.Compositions))
            {
                return(true);
            }
            foreach (var displayable in detail.Displayables)
            {
                if (!(displayable is IApplicationAttributeDisplayable))
                {
                    return(true);
                }
                var attrDisplayable = (IApplicationAttributeDisplayable)displayable;
                if (list.Fields.All(f => f.Attribute != attrDisplayable.Attribute))
                {
                    return(true);
                }
            }

            //return true, if detail has more data then list
            return(false);
        }
        public async void IntegrationTest(IEnumerable <Tuple <int, int> > data, DatasetStatistics expectedStatistics)
        {
            var datasets = this.datasetService.GetDatasets();

            Assert.False(EnumerableExtensions.Any(datasets), "There should be no dataset when starting");

            var datasetId = (await this.datasetService.CreateDataset("Test")).Id;

            datasets = this.datasetService.GetDatasets();
            Assert.Equal(1, datasets.Count);
            var dataset = datasets.SingleOrDefault(d => d.Id == datasetId);

            Assert.NotNull(dataset);
            Assert.Equal(DatasetStatus.Created, dataset.Status);

            await this.datasetService.ImportDataset(datasetId, data);

            datasets = this.datasetService.GetDatasets();
            Assert.Equal(1, datasets.Count);
            dataset = datasets.SingleOrDefault(d => d.Id == datasetId);
            Assert.NotNull(dataset);
            Assert.Equal(DatasetStatus.Imported, dataset.Status);

            var stats = this.datasetService.GetDatasetStatistics(datasetId);

            Assert.Equal(expectedStatistics.AverageFriendCount, stats.AverageFriendCount);
            Assert.Equal(expectedStatistics.UniqueUsers, stats.UniqueUsers);

            await this.datasetService.DeleteDataset(datasetId);

            datasets = this.datasetService.GetDatasets();
            Assert.False(EnumerableExtensions.Any(datasets),
                         "There should be no dataset after we deleted ours");
        }
        public async Task <IActionResult> Post(IList <IFormFile> files)
        {
            if (files == null || !EnumerableExtensions.Any(files))
            {
                return(BadRequest());
            }

            StringValues authorisationHeader = Request.Headers["Authorization"];
            string       email = GetEmailFromAuthorizationHeader(authorisationHeader);

            var request = await CreateSaveAssetRegisterFileRequest(files);

            await _backgroundProcessor.QueueBackgroundTask(
                async() =>
            {
                await _importAssetsUseCase.ExecuteAsync(request, _backgroundProcessor.GetCancellationToken()).ConfigureAwait(false);
                await _assetRegisterUploadProcessedNotifier.SendUploadProcessedNotification(
                    new UploadProcessedNotification
                {
                    Email = email,
                    UploadSuccessfullyProcessed = true
                },
                    _backgroundProcessor.GetCancellationToken());
            }
                );

            return(Ok());
        }
Exemple #4
0
        /// <summary>
        /// Inserts given CatalogItems and checks that it succeeded.
        /// </summary>
        /// <param name="catalogItems">Items to be inserted</param>
        public void EnsureCatalogItemsExist(List <CatalogItem> catalogItems)
        {
            if (catalogItems == null || !EnumerableExtensions.Any(catalogItems))
            {
                throw new ArgumentException("Collection of items to be added is empty");
            }

            _webApplicationContext.PerformServiceAction(new Action <CatalogContext>(context =>
            {
                catalogItems.ForEach(item =>
                {
                    var existingItem = context.CatalogItems.SingleOrDefault(i => i.Id == item.Id);
                    if (existingItem != null)
                    {
                        context.CatalogItems.Remove(existingItem);
                    }
                });
                context.SaveChanges();

                context.AddRange(catalogItems);
                context.SaveChanges();
            }));

            AssertCatalogItemsExist(catalogItems);
        }
Exemple #5
0
        public async Task <UpdateRoomResponse> UpdateRoom(UpdateRoomRequest requestModel)
        {
            //Find and check if room exists in database
            var room = await FindById(requestModel.RoomId);

            //Check if room type exists
            if (!await _param.IsOfParamType(requestModel.RoomType, GlobalParams.ParamTypeRoomType))
            {
                throw new HttpStatusCodeException(HttpStatusCode.NotFound, "RoomService: RoomType is not valid");
            }

            //Update room with new information
            room = UpdateRoomRequest.UpdateToRoom(room, requestModel);


            //Update to database
            room = await _repoWrapper.Room.UpdateAsync(room, room.RoomId);

            var equipments =
                (List <Equipment>) await _repoWrapper.Equipment.FindAllAsyncWithCondition(e => e.RoomId == room.RoomId);

            List <int> equipmentIds = null;

            if (EnumerableExtensions.Any(equipments))
            {
                equipmentIds = equipments.Select(e => e.EquipmentId).ToList();
            }

            return(UpdateRoomResponse.ResponseFromRoom(room, equipmentIds));
        }
        public async Task <IEnumerable <FilePhoto> > GetDefaultDate(string rover)
        {
            var cacheKey = $"{rover}Data";

            if (!_cache.TryGetValue(cacheKey, out List <FilePhoto> filePhotos))
            {
                filePhotos = new List <FilePhoto>();
                var fileDates = await GetDatesFromFile();

                foreach (var date in fileDates)
                {
                    var earthDate   = date.Date.ToString("yyyy-MM-dd");
                    var photoResult = await _nasaPhotoRepository.GetPhoto(rover, earthDate);

                    filePhotos.Add(new FilePhoto()
                    {
                        DateString = date.DateStringName,
                        Photos     = photoResult
                    });
                }

                var cacheEntryOptions = new MemoryCacheEntryOptions()
                                        .SetSlidingExpiration(TimeSpan.FromMinutes(15));

                if (EnumerableExtensions.Any(filePhotos))
                {
                    _cache.Set(cacheKey, filePhotos, cacheEntryOptions);
                }
            }

            return(_cache.Get(cacheKey) as IEnumerable <FilePhoto>);
        }
        public static void EnsurePeopleSeedDataForContext(this YourDollarContext context)
        {
            if (EnumerableExtensions.Any(context.People))
            {
                return;
            }

            var people = new List <PersonEntity>()
            {
                new PersonEntity()
                {
                    FirstName = "John",

                    LastName = "Doe",

                    Email = "*****@*****.**",

                    PhoneNumber = "123-321-1234"
                },

                new PersonEntity()
                {
                    FirstName = "Jane",

                    LastName = "Doe",

                    Email = "*****@*****.**",

                    PhoneNumber = "098-098-1123",
                }
            };

            context.People.AddRange(people);
            context.SaveChanges();
        }
Exemple #8
0
        public async Task <IActionResult> GetEntityTechnologies(
            [FromServices] IEntityRepository entityRepository,
            [FromServices] ITechnologyRepository technologyRepository,
            [FromServices] IEntityService entityService,
            string id)
        {
            var result = await entityRepository.FindTechnologies(technologyRepository, id);

            if (result != null && EnumerableExtensions.Any(result))
            {
                var referenceEntityId = configuration.GetSection("ReferenceEntityId");
                if (referenceEntityId != null && !String.IsNullOrEmpty(referenceEntityId.Value))
                {
                    var referenceEntityTechnologies =
                        await entityRepository.FindTechnologies(technologyRepository, referenceEntityId.Value);

                    if (referenceEntityTechnologies != null && EnumerableExtensions.Any(referenceEntityTechnologies))
                    {
                        result = entityService.PopulateEntityTechnologiesGroupStatus(result,
                                                                                     referenceEntityTechnologies);
                    }
                }
                return(Ok(result));
            }
            return(NoContent());
        }
        public PostDTO CreatePost(CreatePostDTO postDTO)
        {
            var post = postDTO.ToPost();

            if (EnumerableExtensions.Any(postDTO.Tags))
            {
                foreach (var tagId in postDTO.Tags)
                {
                    var postTags = new PostTags()
                    {
                        Post = post, TagId = tagId
                    };
                    post.PostTags.Add(postTags);
                }
            }

            if (postDTO.PostId != 0)
            {
                ++post.PostNum;
                _database.Posts.Add(post);
            }
            else
            {
                _database.Posts.Add(post);
                _database.Save();
                post.PostId = post.Id;
                _database.Posts.Update(post);
            }

            _database.Save();
            return(post.ToPostDTO());
        }
        /// <inheritdoc cref="IsValidCategoriesIds"/>
        public bool IsValidCategoriesIds(IList <int> categoryIds, out string message)
        {
            message = string.Empty;

            if (categoryIds == null || !EnumerableExtensions.Any(categoryIds))
            {
                message = "A product should has any category!";
            }
            else if (categoryIds.Count > this._maxCatCount)
            {
                message = $"A product shouldn't have more than {this._maxCatCount} category!";
            }
            else
            {
                using (var context = this._contextFactory.GetContext())
                {
                    var wrongIds = categoryIds.Where(id => context.Categories.FindAsync(id) == null);

                    if (!wrongIds.Any())
                    {
                        return(true);
                    }

                    message = $"Categories have wrong ids: {string.Join(", ", categoryIds)}";
                }
            }

            return(false);
        }
Exemple #11
0
        public BusinessController(MyContext mc)
        {
            _mc = mc;

            if (EnumerableExtensions.Any(_mc.Businesses))
            {
                return;
            }
            var business = new Business {
                Id         = Guid.NewGuid(),
                No         = "001",
                Name       = "名称001",
                Status     = (int)EntityStatus.Init,
                LastChange = DateTime.Now
            };

            _mc.Businesses.Add(business);
            business = new Business {
                Id         = Guid.NewGuid(),
                No         = "002",
                Name       = "名称002",
                Status     = (int)EntityStatus.Init,
                LastChange = DateTime.Now
            };
            _mc.Businesses.Add(business);
            _mc.SaveChanges();
        }
        private void UninstallSampleProject(SampleProjectInfo sample)
        {
            if (this.App.SerializationManager.CurrentProjectFile == sample.AbsolutePathToProjectFile)
            {
                MessageBox.Show("Cannot uninstall " + sample.Name + ". The project is currently open. Please close current project and try again.");
                return;
            }
            string        directoryName = Path.GetDirectoryName(sample.AbsolutePathToProjectFile);
            DirectoryInfo parent        = Directory.GetParent(directoryName);

            try
            {
                foreach (string current in Directory.EnumerateFiles(directoryName))
                {
                    File.Delete(current);
                }
                Directory.Delete(directoryName);
                FileInfo[] files = parent.GetFiles();
                for (int i = 0; i < files.Length; i++)
                {
                    FileInfo fileInfo = files[i];
                    fileInfo.Delete();
                }
                if (!EnumerableExtensions.Any <DirectoryInfo>(parent.GetDirectories()) && !EnumerableExtensions.Any <FileInfo>(parent.GetFiles()))
                {
                    parent.Delete();
                }
            }
            catch (IOException ex)
            {
                MessageBox.Show("Some files could not be uninstalled. " + ex.Message);
            }
            MessageBox.Show("The project was successfully uninstalled.");
        }
Exemple #13
0
        public void CreateUser(CreateAccountRequest request)
        {
            Require.NotNull(request, nameof(request));

            var doesExist = EnumerableExtensions.Any(GetUserList(account => account.Email.Address == request.Email));

            if (doesExist)
            {
                throw new AccountAlreadyExistsException();
            }

            var newAccount = new Account(
                request.Firstname,
                request.Lastname,
                new MailAddress(request.Email),
                new Password(request.Password),
                AccountRole.User,
                ConfirmationStatus.Unconfirmed,
                DateTime.Now,
                request.Profile);

            var userId = _userRepository.CreateAccount(newAccount);

            _confirmationService.SetupEmailConfirmation(userId);
        }
Exemple #14
0
        /// <summary>
        ///     Inserts test data into database.
        /// </summary>
        public void Seed()
        {
            if (!EnumerableExtensions.Any(_context.Users))
            {
                try
                {
                    _context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT users ON");

                    _context.SaveChanges();

                    SeedPermissions();
                    SeedUsers();
                    SeedUserPermissions();
                    SeedBoatTypes();
                    SeedBoats();
                    SeedReservations();

                    _context.Database.ExecuteSqlRaw("SET IDENTITY_INSERT users OFF");
                    _context.SaveChanges();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        public async Task <bool> IsAutorizador(string userName)
        {
            var validadorSpecificaciones   = new RequisicionByValidadorSpecifiation(userName);
            var requisicionesComoValidador = await this.requisicionRepository.ListAsync(validadorSpecificaciones);

            return(EnumerableExtensions.Any(requisicionesComoValidador));
        }
        public static void Shows(BoxOfficeContext dbContext)
        {
            if (EnumerableExtensions.Any(dbContext.Tickets))
            {
                return;
            }

            var shows = Enumerable.Range(1, 55).Select(i => new Show()
            {
                Name     = $"Show {i}",
                Sessions = new List <ShowSession>()
                {
                    new ShowSession()
                    {
                        From      = DateTimeOffset.UtcNow,
                        To        = DateTimeOffset.UtcNow.AddHours(2),
                        FreeSeats = 100
                    },
                    new ShowSession()
                    {
                        From      = DateTimeOffset.UtcNow.AddDays(1),
                        To        = DateTimeOffset.UtcNow.AddDays(1).AddHours(2),
                        FreeSeats = 100
                    }
                }
            });

            dbContext.AddRange(shows);
            dbContext.SaveChanges();
        }
        private bool IsValid(Transaction transaction)
        {
            var results = new List <ValidationResult>();
            var context = new ValidationContext(transaction);

            Validator.TryValidateObject(transaction, context, results, true);

            return(!EnumerableExtensions.Any(results));
        }
Exemple #18
0
        public async Task <IActionResult> GetAllEntities([FromServices] IEntityRepository entityRepository)
        {
            var result = await entityRepository.FindAllAsync();

            if (EnumerableExtensions.Any(result))
            {
                return(Ok(result));
            }
            return(NoContent());
        }
Exemple #19
0
        public async Task SaveAsync(params Currency[] currencies)
        {
            if (currencies == null || !EnumerableExtensions.Any(currencies))
            {
                return;
            }

            var minDate = currencies.Min(e => e.Date);
            var maxDate = currencies.Max(e => e.Date);

            var currecyCroups = currencies.GroupBy(e => e.Code);

            using (var context = _conetextFactory.Create())
            {
                var dbCurrencies = await context.Currencies.ToListAsync();

                var dbValues = await context.DbCurrencyValues
                               .Where(e => minDate <= e.Date && e.Date <= maxDate).ToListAsync();

                foreach (var currencyCroup in currecyCroups)
                {
                    var dbCurrency = dbCurrencies.FirstOrDefault(e => e.Code == currencyCroup.Key);

                    var newCurrency = dbCurrency == null;

                    if (newCurrency)
                    {
                        dbCurrency = CreateCurrency(currencyCroup.Key);
                        await context.AddAsync(dbCurrency);
                    }

                    foreach (var currency in currencyCroup)
                    {
                        var dbValue = dbValues.FirstOrDefault(
                            e => e.Date == currency.Date && e.CurrencyId == dbCurrency.Id);

                        if (newCurrency || dbValue == null)
                        {
                            dbValue = CreateCurrencyValue(
                                dbCurrency.Id, currency.Amount,
                                currency.Rate, currency.Date
                                );

                            dbValues.Add(dbValue);
                            await context.AddAsync(dbValue);
                        }

                        dbValue.Rate   = currency.Rate;
                        dbValue.Amount = currency.Amount;
                    }
                }

                await context.SaveChangesAsync();
            }
        }
        private void InitializeDatabase(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                var applicationDbContext = serviceScope.ServiceProvider
                                           .GetRequiredService <ApplicationDbContext>();
                applicationDbContext.Database.Migrate();

                var persistedGrantDbContext = serviceScope.ServiceProvider
                                              .GetRequiredService <PersistedGrantDbContext>();
                persistedGrantDbContext.Database.Migrate();

                var configDbContext = serviceScope.ServiceProvider
                                      .GetRequiredService <ConfigurationDbContext>();
                configDbContext.Database.Migrate();

                if (!EnumerableExtensions.Any(configDbContext.Clients))
                {
                    foreach (var client in Config.Clients)
                    {
                        client.ClientUri = _clientUri;
                        client.RedirectUris.Add(_clientUri);
                        client.PostLogoutRedirectUris.Add(_clientUri);
                        client.AllowedCorsOrigins.Add(_clientUri);
                        configDbContext.Clients.Add(client.ToEntity());
                    }

                    configDbContext.SaveChanges();
                }

                if (!EnumerableExtensions.Any(configDbContext.IdentityResources))
                {
                    foreach (var res in Config.IdentityResources)
                    {
                        configDbContext.IdentityResources.Add(res.ToEntity());
                    }

                    configDbContext.SaveChanges();
                }

                if (!EnumerableExtensions.Any(configDbContext.ApiResources))
                {
                    foreach (var api in Config.ApiScopes)
                    {
                        var apiScope = configDbContext.ApiScopes.Where(x => x.Name == api.Name);
                        if (apiScope.Count() == 0)
                        {
                            configDbContext.ApiScopes.Add(api.ToEntity());
                        }
                    }

                    configDbContext.SaveChanges();
                }
            }
        }
        public static void EnsureExpenseSeedDataForContext(this YourDollarContext context)
        {
            if (EnumerableExtensions.Any(context.Expenses))
            {
                return;
            }

            var expenseList = new List <ExpenseEntity>()
            {
                new ExpenseEntity()
                {
                    ShortName            = "Light Bill",
                    BudgetCategory       = context.BudgetCategories.FirstOrDefault(c => c.ShortName == "Utilities"),
                    Amount               = 150m,
                    CompanyAccountNumber = "123-556-33322AB",
                    CompanyName          = "XYZLights",
                    DueDate              = DateTime.Parse("06/15/2019"),
                    PayoutDate           = DateTime.Parse("05/16/2019"),
                    IsRecurring          = true
                },
                new ExpenseEntity()
                {
                    ShortName            = "Water Bill",
                    BudgetCategory       = context.BudgetCategories.FirstOrDefault(c => c.ShortName == "Utilities"),
                    Amount               = 25m,
                    CompanyAccountNumber = "ABC-ID",
                    CompanyName          = "CrystalClearH2O",
                    DueDate              = DateTime.Parse("05/25/2019"),
                    PayoutDate           = DateTime.Parse("06/1/2019"),
                    IsRecurring          = true
                },
                new ExpenseEntity()
                {
                    ShortName      = "Groceries",
                    BudgetCategory = context.BudgetCategories.FirstOrDefault(c => c.ShortName == "Food"),
                    Amount         = 250m,
                    PayoutDate     = DateTime.Parse("05/15/2019"),
                    IsRecurring    = true
                },
                new ExpenseEntity()
                {
                    ShortName            = "Car Loan",
                    BudgetCategory       = context.BudgetCategories.FirstOrDefault(c => c.ShortName == "Transportation"),
                    Amount               = 380m,
                    PayoutDate           = DateTime.Parse("05/15/2019"),
                    DueDate              = DateTime.Parse("06/01/2019"),
                    CompanyName          = "WeToteDaNote",
                    CompanyAccountNumber = "11111666-badjuju",
                    IsRecurring          = true
                }
            };

            context.Expenses.AddRange(expenseList);
            context.SaveChanges();
        }
        private static bool IsPackageInstalled(IPackage pack)
        {
            string packagePath = GetPackagePath(pack);

            // return Directory.Exists(packagePath) &&  // Directory.EnumerateFiles(packagePath, "*.dspx", SearchOption.AllDirectories).Any<string>();
            if (!Directory.Exists(packagePath))
            {
                return(false);
            }
            return(EnumerableExtensions.Any(Directory.EnumerateFiles(packagePath, "*.dspx", SearchOption.AllDirectories)));
        }
Exemple #23
0
        public static async Task SeedDataAsync(DataContext context, UserManager <AppUser> userManager)
        {
            if (!userManager.Users.Any())
            {
                var users = new List <AppUser>
                {
                    new AppUser
                    {
                        DisplayName = "TestUserFirst",
                        UserName    = "******",
                        Email       = "*****@*****.**"
                    },
                    new AppUser
                    {
                        DisplayName = "TestUserSecond",
                        UserName    = "******",
                        Email       = "*****@*****.**"
                    },
                };

                foreach (var user in users)
                {
                    await userManager.CreateAsync(user, "2wsx@WSX");
                }
            }

            if (!EnumerableExtensions.Any(context.HelpdeskOrders))
            {
                var helpdeskOrders = new List <HelpdeskOrder>
                {
                    new HelpdeskOrder
                    {
                        Number      = "abc",
                        Title       = "abc",
                        Description = "abc"
                    },
                    new HelpdeskOrder
                    {
                        Number      = "abc2",
                        Title       = "abc2",
                        Description = "abc2"
                    },
                    new HelpdeskOrder
                    {
                        Number      = "abc3",
                        Title       = "abc3",
                        Description = "abc3"
                    }
                };

                context.HelpdeskOrders.AddRange(helpdeskOrders);
                context.SaveChanges();
            }
        }
 public virtual void DeleteByTotalEmployeeHoursPerCompanyIds(IEnumerable <int> ids)
 {
     if (EnumerableExtensions.Any(ids))
     {
         foreach (var id in ids)
         {
             var item = GetById(id);
             PermanentDelete(item);
         }
     }
 }
Exemple #25
0
        public async Task <ApplicationUser> AddClaims(ApplicationUser user, Claim claim)
        {
            var result = await _userManager.AddClaimAsync(user, claim);

            if (EnumerableExtensions.Any(result.Errors))
            {
                throw new InvalidOperationException(string.Join(", ", result.Errors.Select(DisplayErrorMessage)));
            }

            return(user);
        }
        public async Task TitleOnlySearchWorksAsync()
        {
            var searchCriteria = new SearchCriteria()
            {
                Title = "Road Trip"
            };

            var searchResponses = await _service.SearchAsync(searchCriteria).ConfigureAwait(false);

            Assert.IsTrue(EnumerableExtensions.Any(searchResponses));
        }
Exemple #27
0
        public async Task CreateInsights(IEnumerable <Models.Entities.SafetyIndicator> insights)
        {
            var enumerable = insights as Models.Entities.SafetyIndicator[] ?? insights.ToArray();

            if (insights == null || !EnumerableExtensions.Any(enumerable))
            {
                throw new ArgumentException(nameof(insights));
            }

            await _safetyIndicatorRepository.Insert(enumerable);
        }
        public async Task RomanceSearchReturnsNothingAsync()
        {
            var searchCriteria = new SearchCriteria()
            {
                Genres = "Romance"
            };

            var searchResponses = await _service.SearchAsync(searchCriteria).ConfigureAwait(false);

            Assert.IsFalse(EnumerableExtensions.Any(searchResponses));
        }
        public async Task InvalidTitleFindsNothing()
        {
            var searchCriteria = new SearchCriteria()
            {
                Title = "Road Trips"
            };

            var searchResponses = await _service.SearchAsync(searchCriteria).ConfigureAwait(false);

            Assert.IsFalse(EnumerableExtensions.Any(searchResponses));
        }
        public void SeedEverything(ApplicationDbContext context)
        {
            if (!EnumerableExtensions.Any(context.Users))
            {
                SeedUsers(context);
            }

            if (!EnumerableExtensions.Any(context.Courses))
            {
                SeedCourses(context);
            }
        }