Inheritance: ILookupRepository
 // constructor
 public PastSalesOrderController()
 {
     objectProvider = objectProvider == null ? new ObjectProvider() : objectProvider;
     unitOfWork = unitOfWork == null ? objectProvider.UnitOfWork : unitOfWork;
     orderRepository = orderRepository == null ? unitOfWork.OrderRepository : orderRepository;
     orderLineRepository = orderLineRepository == null ? unitOfWork.OrderLineRepository : orderLineRepository;
 }
        private static void AddTaxToGirl(string firstname, string lastname, int tax)
        {
            var girlRepo = new GenericRepository<Girl>(new GirlsAgencyContext());
            var girl = girlRepo.Search(g => g.FirstName == firstname && g.LastName == lastname).FirstOrDefault();

            if (girl == null)
            {
                throw new ApplicationException("Girl does not exists/found");
            }

            var girlTaxes = new GirlsTaxesEntities();

            string girlFullName = girl.FirstName + " " + girl.LastName;

            var girlTax = GetAssignTax(girlFullName, girlTaxes);

            if (girlTax == null)
            {
                girlTaxes.GirlsTaxes.Add(new GirlsTax
                {
                    GirlName = girlFullName,
                    Tax = tax
                });
            }
            else
            {
                girlTax.Tax = tax;
            }

            girlTaxes.SaveChanges();
        }
 public ICollection<Test> Get()
 {
     var db = new StudentSystemDbContext();
     var testsRepo = new GenericRepository<Test>(db);
     List<Test> tests = testsRepo.All().ToList();
     return tests;
 }
Beispiel #4
0
        static void Main(string[] args)
        {
            var loadFile = File.ReadAllLines(@"c:\users\luiz.araujo\documents\visual studio 2015\Projects\FinancialDic\FinancialDic.Load\load.csv");

            _repository = new GenericRepository<Word>();

            var count = 0;

            foreach (var line in loadFile)
            {
                var words = line.Split(';');

                count ++;

                var word = new Word()
                {
                    Id = count,
                    Portuguese = words[0],
                    English = words[1]
                };

                _repository.AddOrUpdate(word);
            }

            Console.WriteLine("Fim");
        }
        public IHttpActionResult Post(TestRequestModel model)
        {
            if (model == null)
            {
                return this.BadRequest();
            }

            var db = new StudentSystemDbContext();
            var testsRepo = new GenericRepository<Test>(db);
            var coursesRepo = new GenericRepository<Course>(db);
            List<Course> allCourses = coursesRepo.All().ToList();
            var testCourse = new Course
            {
                Name = model.Course.Name,
                Description = model.Course.Description
            };

            var testToAdd = new Test
            {
                Course = testCourse
            };

            testsRepo.Add(testToAdd);
            testsRepo.SaveChanges();
            return this.Ok();
        }
 public ICollection<Student> Get()
 {
     var db = new StudentSystemDbContext();
     var studentsRepo = new GenericRepository<Student>(db);
     List<Student> students = studentsRepo.All().ToList();
     return students;
 }
Beispiel #7
0
        public void GetData()
        {
            GenericRepository<t_loan_lead> loan = new GenericRepository<t_loan_lead>(new sherlockEntities());
            loan.GetAll();

            GenericRepository<t_life_lead> life = new GenericRepository<t_life_lead>(new sherlockEntities());
            life.GetAll();

            GenericRepository<t_asu_lead> asu = new GenericRepository<t_asu_lead>(new sherlockEntities());
            asu.GetAll();

            GenericRepository<t_debt_lead> debt = new GenericRepository<t_debt_lead>(new sherlockEntities());
            debt.GetAll();

            GenericRepository<t_equityrelease_lead> equityrelease = new GenericRepository<t_equityrelease_lead>(new sherlockEntities());
            equityrelease.GetAll();

            GenericRepository<t_logbookloan_lead> logbookloan = new GenericRepository<t_logbookloan_lead>(new sherlockEntities());
            logbookloan.GetAll();

            GenericRepository<t_mortgage_lead> mortgage = new GenericRepository<t_mortgage_lead>(new sherlockEntities());
            mortgage.GetAll();

            GenericRepository<t_pmi_lead> pmi = new GenericRepository<t_pmi_lead>(new sherlockEntities());
            pmi.GetAll();

            GenericRepository<t_ppi_lead> ppi = new GenericRepository<t_ppi_lead>(new sherlockEntities());
            ppi.GetAll();

            GenericRepository<t_sme_mi_lead> sme_mi = new GenericRepository<t_sme_mi_lead>(new sherlockEntities());
            sme_mi.GetAll();

            GenericRepository<t_solar_lead> solar = new GenericRepository<t_solar_lead>(new sherlockEntities());
            solar.GetAll();
        }
        static void Main(string[] args)
        {
            var contactsRepository = new GenericRepository<Contact>();

            contactsRepository.Delete(5);

            //for (int i = 0; i < 1000; i++)
            //{
            //    var currentContact = new Contact();
            //    currentContact.FirstName = "ContactFirstName" + i;
            //    currentContact.LastName = "ContactLastName" + i;

            //    if (i % 3 == 0)
            //    {
            //        currentContact.Sex = Sex.Male;
            //        currentContact.Status = Status.Active;
            //    }
            //    else if (i % 3 == 1)
            //    {
            //        currentContact.Sex = Sex.Female;
            //        currentContact.Status = Status.Inactive;
            //    }
            //    else
            //    {
            //        currentContact.Sex = Sex.Other;
            //        currentContact.Status = Status.Deleted;
            //    }

            //    Random rand = new Random();
            //    currentContact.Telephone = rand.Next(1000000000, 2000000000).ToString();

            //    contactsRepository.Add(currentContact);
            //}
        }
Beispiel #9
0
 public User GetUserById(int IdUser)
 {
     using (var repository = new GenericRepository())
     {
         return repository.ReadById<User>(IdUser);
     }
 }
        public object Add(AddTripModel model)
        {
            GenericRepository<Trip> TripRepo = new GenericRepository<Trip>();
            GenericRepository<User> userRepo = new GenericRepository<User>();
             User user = userRepo.GetSingle(u => u.Username == User.Identity.Name);
            DateTime departDate;
            if (!DateTime.TryParse(model.Depdate, out departDate))
            {
                return false;
            }

            Trip Trip = new Trip()
            {
                UserId =user.UserId,
                DepartDate = departDate,
                AvailableSeatNumber = model.Seatnum,
                Price = model.Price,
                DepMin=model.Min,
                DepHour=model.Hour,
                EstimatedHour=model.EstHour,
                EstimatedMin=model.EstMin,
                DepartLocationId=model.DepLocId,
                ArrivalLocationId=model.ArrLocId,
                CarId = 1,

            };
            TripRepo.Add(Trip);
            return true;
        }
        public void DeleteMovieWhenExistingItemShouldDelete()
        {
            //Arrange -> prepare the objects
            var repo = new GenericRepository<Movie>(new MoviesGalleryContext());
            var movie = new Movie()
            {
                Id = 1,
                Length = 10,
                Ration = 10
            };

            //Act -> perform some logic
            repo.Add(movie);
            repo.SaveChanges();

            var movieFromDb = repo.GetById(movie.Id);

            repo.Delete(movieFromDb);
            repo.SaveChanges();

            var newMovieFromDb = repo.GetById(movie.Id);
            
            //Asssert -> expect and exception
            Assert.IsNull(newMovieFromDb);
        }
        public void UpdateNews_Should_Successfully_Update_News()
        {
            var repository = new GenericRepository<News>(new NewsContext());

            var newsToUpdate = repository.All().FirstOrDefault();
            if (newsToUpdate == null)
            {
                Assert.Fail("Cannot run test - no news in the repository");
            }

            var newsModel = new NewsBindingModel
            {
                Title = "Updated Sample title.",
                Content = "Updated Sample content",
                PublishDate = DateTime.Now
            };

            newsToUpdate.Title = newsModel.Title;
            newsToUpdate.Content = newsModel.Content;
            if (newsModel.PublishDate.HasValue)
            {
                newsToUpdate.PublishDate = newsModel.PublishDate.Value;
            }

            repository.Update(newsToUpdate);
            repository.SaveChanges();
        }
Beispiel #13
0
 public AccountContext()
 {
     rUser = new GenericRepository<User>((u,n)=>u.Name ==n);
     rAccount = new GenericRepository<Account>((a,n)=>a.Number==n);
     AccountService = new AccountService(rUser, rAccount);
     cb = new ControllerBuilder(AccountService);
 }
Beispiel #14
0
        public void TestCreateBusiness()
        {
            var a = EntityHelper.GetAccount("first", "lastName");
            var b = EntityHelper.GetBusiness("business1", Category.ActiveLife);

            using (var Scope = new SQLiteDatabaseScope<PraLoupAutoMappingConfiguration>())
            {
                using (ISession Session = Scope.OpenSession())
                {
                    Session.Transaction.Begin();
                    IRepository r = new GenericRepository(Session);
                    EntityDataService<Business, BusinessValidator> bds = new EntityDataService<Business, BusinessValidator>(r, new BusinessValidator());

                    IDataService ds = new DataService(null, bds, null, null, null, null, null, null, null, new UnitOfWork(Session));
                    BusinessActions ba = new BusinessActions(a, ds, new PraLoup.Infrastructure.Logging.Log4NetLogger(), null);
                    ba.CreateBusiness(b, a, Role.BusinessAdmin);
                    Session.Transaction.Commit();
                }

                using (ISession Session = Scope.OpenSession())
                {
                    IRepository r = new GenericRepository(Session);
                    EntityDataService<Business, BusinessValidator> bds = new EntityDataService<Business, BusinessValidator>(r, new BusinessValidator());

                    var b1 = bds.Find(b.Id);
                    Assert.IsNotNull(b1);
                    Assert.AreEqual(b, b1);
                }
            }
        }
Beispiel #15
0
 public Data()
 {
   _context = new DataContext();
   _configurations = new GenericRepository<Configuration>(_context);
   _messages = new GenericRepository<StoredMessage>(_context);
   _robots = new GenericRepository<Robot>(_context);
 }
        public IHttpActionResult Post(HomeworkRequestModel model)
        {
            if (model == null)
            {
                return this.BadRequest();
            }

            var db = new StudentSystemDbContext();
            var homeworsRepo = new GenericRepository<Homework>(db);
            var coursesRepo = new GenericRepository<Course>(db);
            var studentsRepo = new GenericRepository<Student>(db);
            Course defaultCourse = coursesRepo.All().ToList().FirstOrDefault();
            Student defaultStudent = studentsRepo.All().ToList().FirstOrDefault();
            var homeworkToAdd = new Homework
            {
                FileUrl = model.FileUrl,
                TimeSent = new DateTime(model.TimeSentTicks),
                Course = defaultCourse,
                CourseId = defaultCourse.Id,
                Student = defaultStudent,
                StudentIdentification = defaultStudent.StudentIdentification
            };

            homeworsRepo.Add(homeworkToAdd);
            homeworsRepo.SaveChanges();
            return this.Ok();
        }
 public ICollection<Homework> Get()
 {
     var db = new StudentSystemDbContext();
     var homeworksRepo = new GenericRepository<Homework>(db);
     List<Homework> homeworks = homeworksRepo.All().ToList();
     return homeworks;
 }
Beispiel #18
0
 public void Constructor_If_Passed_Context_Is_Null_Must_Throw_Exception()
 {
     //
     // Arrange, Act, Assert
     //
     var repository = new GenericRepository<IModel>(null);
 }
 public MemberService()
 {
     _eventMemberRepo = UoW.Repository<EventMember>();
     _calendarMemberRepo = UoW.Repository<CalendarMember>();
     _eventRepo = UoW.Repository<Event>();
     _calendarRepo = UoW.Repository<Calendar>();
 }
        //
        // GET: /School/
        public ActionResult Index()
        {
            var schoolRepository = new GenericRepository(new SchoolContext());
            var students = schoolRepository.GetQuery<Student>();

            return View();
        }
Beispiel #21
0
 public void Delete()
 {
     IGenericRepository<SysUser> user = new GenericRepository<SysUser>();
     //user.Delete(4);
     if (user.Submit() == -1)
         Assert.Fail();
 }
 public void GivenAGenericRepository()
 {
     var contextFake = Substitute.For<DbContext>();
     var customerRepository = new GenericRepository<Customer>(contextFake);
     Bag.CustomerRepository = customerRepository;
     Bag.ContextFake = contextFake;
 }
 public ShareService()
 {
     _userRepo = UoW.Repository<User>();
     _calendarRepo = UoW.Repository<Calendar>();
     _eventRepo = UoW.Repository<Event>();
     _invitationService = new InvitationService();
 }
 public ICollection<Course> Get()
 {
     var db = new StudentSystemDbContext();
     var coursesRepo = new GenericRepository<Course>(db);
     List<Course> courses = coursesRepo.All().ToList();
     return courses;
 }
Beispiel #25
0
 public WFTracking()
 {
     _unitOfWork = new EFContext();
     _requestRepository = new GenericRepository<Request>(_unitOfWork);
     _requestActionRepository = new GenericRepository<RequestAction>(_unitOfWork);
     _stateRepository = new GenericRepository<State>(_unitOfWork);
     _transitionRepository = new GenericRepository<Transition>(_unitOfWork);
 }
 public LdapContext(DbContext context)
 {
     _configRepo = new LdapConfigRepository(context);
     _ouRepo = new GenericRepository<OuAssignment>(context);
     _groupConfigs = new GenericRepository<GroupAssignmentConfig>(context);
     _groupAssignments = new GenericRepository<GroupAssignment>(context);
     _personalFolders = new PersonalFolderRepository(context);
 }
        public async Task ActualizeArticles()
        {
            //Get Total Number of feeds
            int feedcounter = _sources.SelectMany(source => source.FeedList).Count();
            int activecounter = 0;

            foreach (var sourceModel in _sources)
            {
                if (sourceModel.SourceConfiguration.Source == SourceEnum.Favorites)
                    continue;

                foreach (var feed in sourceModel.FeedList)
                {
                    var newfeed = await FeedHelper.Instance.DownloadFeed(feed);
                    _progressService.ShowProgress("Feeds werden heruntergeladen...", Convert.ToInt32((++activecounter * 100) / feedcounter));
                    if (newfeed != null)
                    {
                        ArticleHelper.Instance.AddWordDumpFromFeed(ref newfeed);

                        var newarticles = await FeedToDatabase(newfeed);
                        _newArticleModels.AddRange(newarticles);
                        Messenger.Default.Send(newarticles, Messages.FeedRefresh);
                    }
                }
            }

            using (var unitOfWork = new UnitOfWork(true))
            {
                var repo = new GenericRepository<ArticleModel, ArticleEntity>(await unitOfWork.GetDataService());
                var state = (int)ArticleState.New;
                var newarticles = await repo.GetByCondition(d => d.State == state);
                foreach (var articleModel in newarticles)
                {
                    if (_newArticleModels.All(d => d.Id != articleModel.Id))
                    {
                        _newArticleModels.Add(await AddModels(articleModel, await unitOfWork.GetDataService(), true));
                    }
                }
            }

            _newArticles = _newArticleModels.Count;

            //Actualize articles
            if (!_aktualizeArticlesTasks.Any())
            {
                for (int i = 0; i < 4; i++)
                {
                    var tsk = AktualizeArticlesTask().ContinueWith(DeleteTaskFromList);
                    _aktualizeArticlesTasks.Add(tsk);
                }
            }

            foreach (var aktualizeArticlesTask in _aktualizeArticlesTasks)
            {
                await aktualizeArticlesTask;
            }
        }
        public ProfileController()
        {
            roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();    
            userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();

            objectProvider = objectProvider == null ? new ObjectProvider() : objectProvider;
            unitOfWork = unitOfWork == null ? objectProvider.UnitOfWork : unitOfWork;
            aspNetUsersRepository = aspNetUsersRepository == null ? unitOfWork.AspNetUserRepository : aspNetUsersRepository;
        }
 public ActionResult ActivityTypes()
 {
     IEnumerable<ActivityType> activities = new List<ActivityType>();
     using (GenericRepository<ActivityType> activityTypeRepository = new GenericRepository<ActivityType>(ConfigurationManager.ConnectionStrings["VentureSketchConnectionString"].ConnectionString))
     {
         activities = activityTypeRepository.List().ToList();
     }
     return this.View(HomeControllerAction.ActivityTypes, activities);
 }
 public ActionResult Index()
 {
     List<Qualification> qualifications = new List<Qualification>();
     using (GenericRepository<Qualification> qualificationRepository = new GenericRepository<Qualification>(ConfigurationManager.ConnectionStrings["VentureSketchConnectionString"].ConnectionString))
     {
         qualifications = qualificationRepository.List().ToList();
     }
     return this.View(HomeControllerAction.Index, qualifications);
 }
Beispiel #31
0
 public MoviesController(GenericRepository repo)
 {
     _repo = repo;
 }
Beispiel #32
0
 public InventorsController()
 {
     _inventor = new GenericRepository <Inventor>();
     _s        = _inventor.Get();
 }
Beispiel #33
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public ProjectsCRsController()
 {
     this._dbContext     = BaseContext.GetDbContext();
     this._objProjectCRs = new GenericRepository <ProjectCR>();
     this._objProject    = new GenericRepository <Projects>();
 }
Beispiel #34
0
        private void BtnCall_Clicked(object sender, EventArgs e)
        {
            List <Modelos.Usuario> datos = new GenericRepository <Modelos.Usuario>().TraerDatos("Usuarios").Result;

            lstView.ItemsSource = datos;
        }
Beispiel #35
0
 public CommentService(GenericRepository <Comment> rep_Com, GenericRepository <Game> rep_Game)
 {
     this.unitOfWork = new UnitOfWork();
     this.unitOfWork.CommentRepository = rep_Com;
     this.unitOfWork.GameRepository    = rep_Game;
 }
Beispiel #36
0
 public ImageService()
 {
     imageRepository = new GenericRepository <Image>();
 }
Beispiel #37
0
 public RoleMasterService()
 {
     _dbContext           = new epassbook_dbEntities();
     unitOfWork           = new UnitOfWork(_dbContext);
     roleMasterRepository = unitOfWork.GenericRepository <RoleMaster>();
 }
Beispiel #38
0
 public UfBusiness()
 {
     this._rep = new GenericRepository <Database.Estado>();
 }
Beispiel #39
0
 public AnexoAppSvcGeneric(AppDbContext context) : base(context)
 {
     repository = new GenericRepository <Anexo>(context);
 }
        public void ShouldUpdateExistingEmployees()
        {
            // Arrange
            var departmentHr = Testdata.Departments.CreateDepartmentHumanResources();

            var originalEmployees = new List <Employee>();
            var originalEmployee1 = CreateEmployee1();

            originalEmployee1.Department = departmentHr;

            var originalEmployee2 = CreateEmployee2();

            originalEmployee2.Department = departmentHr;

            var originalEmployee3 = CreateEmployee3();

            originalEmployee3.Department = departmentHr;

            originalEmployees.Add(originalEmployee1);
            originalEmployees.Add(originalEmployee2);
            originalEmployees.Add(originalEmployee3);

            using (IGenericRepository <Employee> employeeRepository = new GenericRepository <Employee>(this.CreateContext()))
            {
                employeeRepository.AddRange(originalEmployees);
                employeeRepository.Save();
            }

            int n = 5000;
            var timespanOffset = new TimeSpan(0, 0, 0, 1);
            var stopwatch      = new Stopwatch();

            var updatedEmployees = new List <Employee>();
            var updatedEmployee1 = CreateEmployee1();

            updatedEmployee1.Id         = originalEmployee1.Id;
            updatedEmployee1.RowVersion = originalEmployee1.RowVersion;

            var updatedEmployee2 = CreateEmployee2();

            updatedEmployee2.Id         = originalEmployee2.Id;
            updatedEmployee2.RowVersion = originalEmployee2.RowVersion;

            var updatedEmployee3 = CreateEmployee3();

            updatedEmployee3.Id         = originalEmployee3.Id;
            updatedEmployee3.RowVersion = originalEmployee3.RowVersion;

            updatedEmployees.Add(originalEmployee1);
            updatedEmployees.Add(originalEmployee2);
            updatedEmployees.Add(originalEmployee3);

            // Act
            ChangeSet committedChangeSet;

            using (IGenericRepository <Employee> employeeRepository = new GenericRepository <Employee>(this.CreateContext()))
            {
                stopwatch.Start();
                for (int i = 0; i < n; i++)
                {
                    foreach (var updateEmployee in updatedEmployees)
                    {
                        updateEmployee.Birthdate += timespanOffset;
                        employeeRepository.Update(updateEmployee);
                    }
                }
                committedChangeSet = employeeRepository.Save();
                stopwatch.Stop();
            }

            this.testOutputHelper.WriteLine($"Elapsed={stopwatch.ElapsedMilliseconds}ms");

            // Assert
            committedChangeSet.Assert(expectedNumberOfAdded: 0, expectedNumberOfModified: 3, expectedNumberOfDeleted: 0);

            using (IGenericRepository <Employee> employeeRepository = new GenericRepository <Employee>(this.CreateContext()))
            {
                var allEmployees = employeeRepository.GetAll().ToList();
                allEmployees.Should().HaveCount(3);
                allEmployees.ElementAt(0).Birthdate.Should().Be(new DateTime(1986, 07, 11, 01, 23, 20));
                allEmployees.ElementAt(1).Birthdate.Should().Be(new DateTime(1990, 01, 01, 01, 23, 20));
                allEmployees.ElementAt(2).Birthdate.Should().Be(new DateTime(2000, 12, 31, 01, 23, 20));

                stopwatch.ElapsedMilliseconds.Should().BeLessThan(2500);
            }
        }
Beispiel #41
0
 public void AmennyibenEgyGenericRepo()
 {
     repo = new GenericRepository <TodoItem, TodoItemDTO, TodoItemProfile>();
 }
Beispiel #42
0
 public SquadPessoaAppSvcGeneric(AppDbContext context) : base(context)
 {
     repository = new GenericRepository <SquadPessoa>(context);
 }
 public TypeAttributeController()
 {
     _typeAttribute = new GenericRepository <TypeAttribute>();
     _user          = new GenericRepository <User>();
     _attribute     = new GenericRepository <DataModel.Models.Attribute>();
 }
Beispiel #44
0
 protected override void Initialize(GenericRepository <TGenericEntity, TGenericEntityContainerDataStoreResolver> instance)
 {
     base.Initialize(instance);
     instance.DataStoreResolver = new DefaultFactory <TGenericEntityContainerDataStoreResolver>().Create();
 }
Beispiel #45
0
        public async Task Then_Make_TLevel_Provider_Flag_To_True(
            MatchingDbContext dbContext,
            Domain.Models.Provider provider,
            List <ProviderVenueViewModel> venueViewModels,
            MatchingConfiguration config,
            ILogger <GenericRepository <Domain.Models.Provider> > providerLogger,
            ILogger <GenericRepository <ProviderReference> > providerReferenceLogger,
            IHttpContextAccessor httpContextAccessor,
            IDateTimeProvider dateTimeProvider
            )
        {
            //Arrange
            provider.IsTLevelProvider = false;

            await dbContext.AddAsync(provider);

            await dbContext.SaveChangesAsync();

            dbContext.Entry(provider).State = EntityState.Detached;

            var viewModel = new ProviderDetailViewModel
            {
                Id = provider.Id,
                IsTLevelProvider = true,
                ProviderVenues   = venueViewModels
            };

            httpContextAccessor.HttpContext.Returns(new DefaultHttpContext
            {
                User = new ClaimsPrincipal(new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.GivenName, "System")
                }))
            });

            var mapperConfig = new MapperConfiguration(c =>
            {
                c.AddMaps(typeof(ProviderMapper).Assembly);
                c.ConstructServicesUsing(type =>
                                         type.Name.Contains("LoggedInUserNameResolver")
                        ? (object)new LoggedInUserNameResolver <ProviderDetailViewModel, Domain.Models.Provider>(httpContextAccessor)
                        : type.Name.Contains("UtcNowResolver")
                                ? new UtcNowResolver <ProviderDetailViewModel, Domain.Models.Provider>(dateTimeProvider)
                                : null);
            });

            var mapper = new Mapper(mapperConfig);

            var providerReferenceRepo = new GenericRepository <ProviderReference>(providerReferenceLogger, dbContext);
            var repo            = new GenericRepository <Domain.Models.Provider>(providerLogger, dbContext);
            var providerService = new ProviderService(mapper, repo, providerReferenceRepo);

            var sut = new ProviderController(providerService, config);

            //Act
            await sut.SaveProviderDetailAsync(viewModel);

            //Assert
            var result = await repo.GetSingleOrDefaultAsync(x => x.Id == provider.Id);

            provider.IsTLevelProvider.Should().BeFalse();
            result.IsTLevelProvider.Should().BeTrue();
        }
 public static async Task <ClientInstanceEntity> GetStoppingEntityForInstance(GenericRepository <ClientInstanceEntity, IClientInstance> clientInstanceRepository, InstanceDataDTO postInstanceData)
 {
     return(await clientInstanceRepository.TryGetAsync(t => t.InstanceId == postInstanceData.InstanceId) as ClientInstanceEntity);
 }
Beispiel #47
0
        public async Task <IActionResult> Post(string project, string name, string locale, string build, [FromBody] CreateScreenDto screenData)
        {
            GenericRepository <Build> buildRepo = _unitOfWork.BuildRepository;
            Build buildEntity;

            string currentUser = User.Identity.Name;

            // Workaround for local readonly user
            if (!Authentication.LdapHelper.CanWrite(currentUser))
            {
                return(Unauthorized());
            }

            try
            {
                Guid buildId;

                if (!Guid.TryParse(build, out buildId))
                {
                    buildEntity = (await buildRepo.GetAsync(b => b.BuildName.Equals(build))).FirstOrDefault();
                }
                else
                {
                    buildEntity = buildRepo.GetByID(buildId);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error in screens controller");
                return(BadRequest());
            }


            if (buildEntity == null)
            {
                return(BadRequest($"Build with id {build} doesn't exist!"));
            }


            if (!ModelState.IsValid || buildEntity == null || string.IsNullOrWhiteSpace(project) || string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(locale) || screenData == null)
            {
                return(BadRequest("Invalid or missing parameters"));
            }

            GenericRepository <Project> projectRepo = _unitOfWork.ProjectRepository;
            Project projectEntity = projectRepo.GetByID(project);

            if (projectEntity == null)
            {
                return(BadRequest($"Project {project} doesn't exist!"));
            }

            GenericRepository <Locale> localeRepo = _unitOfWork.LocaleRepository;

            if (localeRepo.GetByID(locale) == null)
            {
                return(BadRequest($"Unknown locale {locale}!"));
            }

            GenericRepository <Screen> screenRepo = _unitOfWork.ScreenRepository;

            if (screenRepo.GetByID(name, project) == null)
            {
                Screen screen = new Screen()
                {
                    Project = projectEntity, ScreenName = name
                };
                screenRepo.Insert(screen);
                await _unitOfWork.SaveAsync(currentUser);
            }

            GenericRepository <ScreenInBuild> screenInBuildRepo = _unitOfWork.ScreenInBuildRepository;

            var existingScreen = screenInBuildRepo.Get(sr => sr.BuildId == buildEntity.Id && sr.ProjectName.Equals(project) && sr.LocaleCode.Equals(locale) && sr.ScreenName.Equals(name)).FirstOrDefault();

            bool missingFile = false;

            if (existingScreen != null)
            {
                string existingScreenLocalPath = StorageHelper.GetScreenAbsPath(StorageHelper.GetScreenPath(project, locale, buildEntity.BuildName, name));

                if (System.IO.File.Exists(existingScreenLocalPath))
                {
                    byte[] existingContent = System.IO.File.ReadAllBytes(existingScreenLocalPath);

                    if (!screenData.Content.SequenceEqual(existingContent))
                    {
                        return(StatusCode((int)HttpStatusCode.Conflict));
                    }
                    else
                    {
                        return(StatusCode((int)HttpStatusCode.NoContent));
                    }
                }
                else
                {
                    missingFile = true;
                }
            }

            string screenLocalPath = _storageHelper.StoreScreen(project, locale, buildEntity.BuildName, name, screenData.Content);

            ScreenDto newScreen;

            if (!missingFile)
            {
                ScreenInBuild newScreenInBuild = new ScreenInBuild()
                {
                    ProjectName = project, ScreenName = name, BuildId = buildEntity.Id, LocaleCode = locale
                };
                screenInBuildRepo.Insert(newScreenInBuild);
                await _unitOfWork.SaveAsync(currentUser);

                newScreen = new ScreenDto(newScreenInBuild);
            }
            else
            {
                newScreen = new ScreenDto(existingScreen);
            }

            return(CreatedAtRoute(routeName: "GetScreenRoute", routeValues: new { project = project, id = newScreen.Id }, value: newScreen));
        }
 public ProjetoTecnologiaAppSvcGeneric(AppDbContext context) : base(context)
 {
     repository = new GenericRepository <ProjetoTecnologia>(context);
 }
Beispiel #49
0
 public static User GetSingleByEmail(this GenericRepository <User> userRepository, string email)
 {
     return(userRepository.GetAll().FirstOrDefault(x => x.Email == email));
 }
Beispiel #50
0
        public int Redone(int current, DateTime time)
        {
            int step = current;

            try
            {
                step--;

                List <BooksHistory> history;

                using (LibContext context = new LibContext())
                {
                    history = context.BooksHistory.Where(c => c.OperationDate <= time).ToList();
                    history.Reverse();
                    GenericRepository <Books> generic = new GenericRepository <Books>(context);

                    if (step < history.Count && step >= 0)
                    {
                        BooksHistory pacient   = history[step];
                        string       operation = pacient.Operation;

                        context.Database.ExecuteSqlCommand("DISABLE TRIGGER BooksHistory ON Books");
                        context.Database.ExecuteSqlCommand("DISABLE TRIGGER BooksInsert ON Books");

                        if (operation == "inserted")
                        {
                            Books entity = new Books
                            {
                                Id         = pacient.Id,
                                Title      = pacient.CurrentTitle,
                                Author     = pacient.CurrentAuthor.HasValue ? pacient.CurrentAuthor.Value : 0,
                                Department = pacient.CurrentDepartment
                            };

                            using (var scope = context.Database.BeginTransaction())
                            {
                                context.Books.Add(entity);
                                context.SaveChanges();
                                scope.Commit();
                            }
                        }
                        else if (operation == "updated")
                        {
                            Books entity = generic.Get(c => c.Id == pacient.Id).FirstOrDefault();
                            if (entity != null)
                            {
                                entity.Title      = pacient.CurrentTitle;
                                entity.Author     = pacient.CurrentAuthor.HasValue ? pacient.CurrentAuthor.Value : 0;
                                entity.Department = pacient.CurrentDepartment;

                                generic.Update(entity);
                            }
                        }
                        else if (operation == "deleted")
                        {
                            Books entity = generic.Get(c => c.Id == pacient.Id).FirstOrDefault();
                            if (entity != null)
                            {
                                generic.Remove(entity);
                            }
                        }

                        context.Database.ExecuteSqlCommand("ENABLE TRIGGER BooksHistory ON Books");
                        context.Database.ExecuteSqlCommand("ENABLE TRIGGER BooksInsert ON Books");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return(step);
        }
 public AccessoryManager(GenericRepository <Accessory> repository, Manager manager)
     : base(repository, manager)
 {
 }
Beispiel #52
0
 public OrderService(IOrderDataAccess orderDataAccess, ISMSService smsService, IUserService userService, IProductService productService, IMessageService messageService, CloudFarmDbContext cloudFarmDb, GenericRepository <PreSaleOrder> preOrdeRepository)
 {
     this.orderDataAccess       = orderDataAccess;
     this.smsService            = smsService;
     this.userService           = userService;
     this.productService        = productService;
     this.messageService        = messageService;
     this.cloudFarmDb           = cloudFarmDb;
     this.preSaleOrdeRepository = preOrdeRepository;
 }
Beispiel #53
0
 public FtsFuelPurchaseService()
 {
     _fuelpurchaseRepository = new GenericRepository <ftsFuelPurchase>();
 }
Beispiel #54
0
 public PrioritiesController(PermaContext context)
 {
     _context           = context;
     priorityRepository = new GenericRepository <Priority>(context);
 }
Beispiel #55
0
 public BookBs()
 {
     context    = new LibContext();
     repository = new GenericRepository <Books>(context);
 }
Beispiel #56
0
 private void CreateSut()
 {
     _DbContext = InMemoryContext(dbId.ToString());
     _Sut       = new GenericRepository <Race>(_DbContext);
 }
Beispiel #57
0
        //для сопоставления Id - name
        public async Task <IEnumerable <DAL.Sale> > CheckNameId(IEnumerable <DAL.Sale> Entities)
        {
            var _contactRepository = new GenericRepository <DAL.Contact>();

            IEnumerable <DAL.Client> clients = await GetAll();

            foreach (var sale in Entities)
            {
                Guid idClient = new Guid();
                if (clients.Any())
                {
                    var clients1 = clients.Where(c => c.Name == sale.ClientName);
                    var i        = clients1.Where(x => x != null).Select(c => c.Id);
                    if (i.Count() > 0)
                    {
                        idClient = i.Where(x => x != null).First();
                    }
                    //создать в БД
                    else
                    {
                        //контакт
                        DAL.Contact contact = new DAL.Contact();
                        contact.Id       = Guid.NewGuid();
                        contact.LastName = sale.ClientName;
                        _contactRepository.Add(contact);
                        //SaveChanges();
                        //клиент
                        DAL.Client client = new DAL.Client();
                        client.Id        = Guid.NewGuid();
                        client.Name      = sale.ClientName;
                        client.ContactId = contact.Id;
                        Add(client);
                        //SaveChanges();
                        idClient = client.Id;

                        clients = await GetAll();
                    }
                }
                //создать в БД
                else
                {
                    //контакт
                    DAL.Contact contact = new DAL.Contact();
                    contact.Id       = Guid.NewGuid();
                    contact.LastName = sale.ClientName;
                    _contactRepository.Add(contact);
                    //клиент
                    DAL.Client client = new DAL.Client();
                    client.Id        = Guid.NewGuid();
                    client.Name      = sale.ClientName;
                    client.ContactId = contact.Id;
                    Add(client);
                    idClient = client.Id;

                    clients = await GetAll();
                }
                sale.ClientId = idClient;
            }

            return(Entities);
        }
 public ClubController()
 {
     this.repository    = new ClubRepository();
     this.genRepository = new GenericRepository <ClubModel>();
 }
Beispiel #59
0
 public ProjectValidationService(Connection connection)
     : base(connection)
 {
     _genericRepository = new GenericRepository(connection);
 }
 public StudentrolService(IUnitOfWork uow,
                          GenericRepository <StudentRollen> studentrolRepository)
 {
     this.uow = uow;
     this.studentrolRepository = studentrolRepository;
 }