Beispiel #1
0
 public GroupController(AimLoginContext loginDb, LivestockContext livestockDb, DataMapService <AdmuGroup> data, DataMapService <User> userData)
 {
     this.loginDb     = loginDb;
     this.livestockDb = livestockDb;
     this.data        = data;
     this.userData    = userData;
 }
        private static void SeedWeightTransactions(LivestockContext livestockContext)
        {
            if (livestockContext.WeightTransactions.Any())
            {
                return;
            }

            var animal = livestockContext.Animals.OrderBy(a => a.Number).First();

            if (animal == null)
            {
                SeedAnimals(livestockContext);
                animal = livestockContext.Animals.OrderBy(a => a.Number).First();
            }

            livestockContext.WeightTransactions.AddRange(
                new WeightTransactionModel
            {
                AnimalId        = animal.Id,
                TransactionDate = DateTimeOffset.Parse("2021-01-13T16:00:00Z"),
                Weight          = 63
            });

            livestockContext.SaveChanges();
        }
        static void Main(string[] args)
        {
            _generators = new List <IEntityFileGenerator>();
            _generators.Add(new IndexGenerator());
            _generators.Add(new CreateEditGenerator("Create"));
            _generators.Add(new CreateEditGenerator("Edit"));
            _generators.Add(new DetailsDeleteGenerator("Details"));
            _generators.Add(new DetailsDeleteGenerator("Delete"));

            Environment.CurrentDirectory = Path.GetRelativePath(Environment.CurrentDirectory, "../");

            var json = Json.Parse(File.ReadAllText("appsettings.json"));

            using (var db = new LivestockContext(json.Get("ConnectionStrings").Get("Livestock").As <string>()))
            {
                _generators.Add(new ControllerGenerator(db));
                foreach (var entity in db.Model.GetEntityTypes().Where(e => !IGNORED_TYPES.Contains(e.ClrType)))
                {
                    foreach (var gen in _generators)
                    {
                        var info = gen.Generate(entity);
                        if (!Directory.Exists(Path.GetDirectoryName(info.path)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(info.path));
                        }

                        File.WriteAllText(info.path, info.data);
                    }
                }
            }
        }
        private static void SeedAnimals(LivestockContext context)
        {
            if (context.Animals == null || context.Animals.Any())
            {
                return;
            }

            context.Animals.AddRange(
                new AnimalModel()
            {
                Type          = AnimalType.Cattle,
                Subspecies    = "Brahman",
                Number        = 1,
                BatchNumber   = 1,
                BirthDate     = new DateTimeOffset(DateTime.UtcNow.AddDays(-15)),
                PurchaseDate  = new DateTimeOffset(DateTime.UtcNow.AddDays(-13)),
                PurchasePrice = 200m,
                ArrivalWeight = 120m,
                Sold          = false,
                SellPrice     = null,
                Deceased      = false
            });

            context.SaveChanges();
        }
        private static void SeedMedicalTransactions(LivestockContext context)
        {
            if (context.MedicalTransactions == null || context.MedicalTransactions.Any())
            {
                return;
            }

            var animal = context.Animals.OrderBy(a => a.Number).First();

            if (animal == null)
            {
                SeedAnimals(context);
                animal = context.Animals.OrderBy(a => a.Number).First();
            }

            context.MedicalTransactions.AddRange(
                new MedicalTransactionModel()
            {
                AnimalId        = animal.Id,
                MedicineId      = context.MedicineTypes.OrderBy(m => m.Description).First().Id,
                TransactionDate = DateTimeOffset.Parse("2021-01-13T16:00:00Z"),
                UnitId          = context.Units.OrderBy(u => u.Description).First().Id,
                Dose            = 0.5m
            });

            context.SaveChanges();
        }
        private static void SeedFeedingTransactions(LivestockContext livestockContext)
        {
            if (livestockContext.FeedingTransactions.Any())
            {
                return;
            }

            var animal = livestockContext.Animals.OrderBy(a => a.Number).First();

            if (animal == null)
            {
                SeedAnimals(livestockContext);
                animal = livestockContext.Animals.OrderBy(a => a.Number).First();
            }

            livestockContext.FeedingTransactions.AddRange(
                new FeedingTransactionModel()
            {
                AnimalId        = animal.Id,
                FeedTypeId      = livestockContext.FeedTypes.OrderBy(f => f.Description).First().Id,
                Quantity        = 0.5m,
                TransactionDate = DateTimeOffset.Parse("2021-01-13T16:00:00Z"),
                UnitId          = livestockContext.Units.OrderBy(u => u.Description).First().Id
            },
                new FeedingTransactionModel()
            {
                AnimalId        = animal.Id,
                FeedTypeId      = livestockContext.FeedTypes.OrderBy(f => f.Description).First().Id,
                Quantity        = 1,
                TransactionDate = DateTimeOffset.Parse("2021-01-12T16:00:00Z"),
                UnitId          = livestockContext.Units.OrderBy(u => u.Description).First().Id
            });

            livestockContext.SaveChanges();
        }
 public HomeController(LivestockContext livestockDb, AimLoginContext loginDb, IAimUserManager userManager, DataMapService <User> data)
 {
     this.livestockDb = livestockDb;
     this.loginDb     = loginDb;
     this.userManager = userManager;
     this.data        = data;
 }
 private WeightTransactionCrudService SetUpService(LivestockContext context)
 {
     context.SeedTestAnimal(TestConstants.AnimalId1);
     context.SeedTestAnimal(TestConstants.AnimalId2);
     context.SeedWeightTransaction(TestConstants.AnimalId1);
     context.SaveChanges();
     return(new WeightTransactionCrudService(_logger, context));
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="logger">The logger.</param>
 /// <param name="mapper">The mapper.</param>
 /// <param name="livestockContext">The database context that contains the feeding transactions table.</param>
 public FeedingTransactionCrudService(ILogger <FeedingTransactionCrudService> logger,
                                      IMapper <FeedingTransactionModel, IFeedingTransaction> mapper,
                                      LivestockContext livestockContext)
 {
     Logger           = logger;
     Mapper           = mapper;
     LivestockContext = livestockContext;
 }
 public void Seed(IServiceProvider serviceProvider)
 {
     using var context = new LivestockContext(serviceProvider.GetRequiredService <DbContextOptions <LivestockContext> >());
     SeedAnimals(context);
     SeedMedicalTransactions(context);
     SeedFeedingTransactions(context);
     SeedWeightTransactions(context);
 }
 public AccountController(LivestockContext livestockDb, AimLoginContext aimloginDb, IAimUserManager aimloginUsers, DataMapService <User> aimLoginData, IAimHasher aimHasher)
 {
     this.livestockDb   = livestockDb;
     this.aimLoginData  = aimLoginData;
     this.aimloginDb    = aimloginDb;
     this.aimloginUsers = aimloginUsers;
     this.aimHasher     = aimHasher;
 }
Beispiel #12
0
        internal static void SeedTestAnimal(this LivestockContext context, long id)
        {
            var animal = new AnimalModel
            {
                Id = id
            };

            context.Animals.Add(animal);
        }
        public static LivestockContext Create(ILoggerFactory loggerFactory)
        {
            var connection = OpenConnection();
            var options    = GetOptions(connection, loggerFactory);
            var context    = new LivestockContext(options);

            context.Database.EnsureCreated();
            return(context);
        }
Beispiel #14
0
        /// <summary>
        /// Adds an animal to the persisted store.
        /// </summary>
        /// <param name="item">The animal to be added.</param>
        /// <param name="cancellationToken">A token that can be used to signal operation cancellation.</param>
        /// <returns>The added animal.</returns>
        public virtual async Task <IAnimal> AddAsync(IAnimal item, CancellationToken cancellationToken)
        {
            Logger.LogInformation("Adding an animal...");

            var entity  = AnimalMapper.Map(item);
            var changes = await LivestockContext.AddAsync(entity, cancellationToken)
                          .ConfigureAwait(false);

            await LivestockContext.SaveChangesAsync(cancellationToken)
            .ConfigureAwait(false);

            return(AnimalMapper.Map(changes.Entity));
        }
Beispiel #15
0
        internal static LivestockContext SeedWeightTransaction(this LivestockContext context,
                                                               long animalId,
                                                               DateTimeOffset?transactionDate = null,
                                                               decimal weight = 88)
        {
            context.WeightTransactions.Add(new WeightTransactionModel
            {
                AnimalId        = animalId,
                TransactionDate = transactionDate ?? TestConstants.DefaultDate,
                Weight          = weight
            });

            return(context);
        }
Beispiel #16
0
        /// <inheritdoc/>
        public void ArchiveAnimals(int[] animalIds)
        {
            Logger.LogInformation("Archiving animals...");

            var animals = LivestockContext.Animals
                          .Where(animal => animalIds.Contains((int)animal.Id) &&
                                 !animal.Archived)
                          .ToList();

            Logger.LogDebug("Archiving {@Count} unarchived animals...", animals.Count);
            foreach (var animal in animals)
            {
                animal.Archived = true;
            }

            LivestockContext.SaveChanges();
        }
Beispiel #17
0
        /// <summary>
        /// Removes the animal with an ID that matches the key value from the persisted store.
        /// </summary>
        /// <param name="key">The identifying value of the animal.</param>
        /// <param name="cancellationToken">A token that can be used to signal operation cancellation.</param>
        /// <returns>The ID of the animal that was removed.</returns>
        /// <exception cref="EntityNotFoundException{AnimalModel}">When the animal with the given key is not found.</exception>
        public virtual async Task <long> RemoveAsync(long key, CancellationToken cancellationToken)
        {
            Logger.LogInformation($"Removing the animal with ID {key}...");

            var entity = await LivestockContext.Animals.FindAsync(new object[] { key }, cancellationToken)
                         .ConfigureAwait(false);

            if (entity == null)
            {
                throw new EntityNotFoundException <AnimalModel>(key);
            }

            var changes = LivestockContext.Animals.Remove(entity);
            await LivestockContext.SaveChangesAsync(cancellationToken)
            .ConfigureAwait(false);

            return(changes.Entity.Id);
        }
        private static void SeedFeedTypes(LivestockContext livestockContext)
        {
            if (livestockContext.FeedTypes.Any())
            {
                return;
            }

            livestockContext.FeedTypes.AddRange(
                new FeedTypeModel()
            {
                Id          = 1,
                Description = "Wheat"
            },
                new FeedTypeModel()
            {
                Id          = 2,
                Description = "Maze"
            });
        }
        private static void SeedMedicine(LivestockContext context)
        {
            if (context.MedicineTypes == null || context.MedicineTypes.Any())
            {
                return;
            }

            context.MedicineTypes.AddRange(
                new MedicineTypeModel()
            {
                Id          = 1,
                Description = "Antibiotics"
            },
                new MedicineTypeModel()
            {
                Id          = 2,
                Description = "Painkillers"
            });
        }
        private static void SeedUnits(LivestockContext context)
        {
            if (context.Units == null || context.Units.Any())
            {
                return;
            }

            context.Units.AddRange(
                new UnitModel()
            {
                Id          = 1,
                Description = "ℓ"
            },
                new UnitModel()
            {
                Id          = 2,
                Description = "kg"
            });
        }
Beispiel #21
0
        /// <summary>
        /// Updates the properties of an animal in the persisted store.
        /// </summary>
        /// <param name="item">The animal with its desired values.</param>
        /// <param name="cancellationToken">A token that can be used to signal operation cancellation.</param>
        /// <returns>The updated animal.</returns>
        /// <exception cref="EntityNotFoundException{AnimalModel}">When the animal with the given key is not found.</exception>
        public virtual async Task <IAnimal> UpdateAsync(IAnimal item, CancellationToken cancellationToken)
        {
            Logger.LogInformation($"Updating the animal with ID {item.Id}...");

            var entity = await LivestockContext.Animals.FindAsync(new object[] { item.Id }, cancellationToken)
                         .ConfigureAwait(false);

            if (entity == null)
            {
                throw new EntityNotFoundException <AnimalModel>(item.Id);
            }

            UpdateEntityValues(entity, item);

            var changes = LivestockContext.Animals.Update(entity);
            await LivestockContext.SaveChangesAsync(cancellationToken)
            .ConfigureAwait(false);

            return(AnimalMapper.Map(changes.Entity));
        }
        public void Seed(IServiceProvider serviceProvider)
        {
            var options = serviceProvider.GetRequiredService <DbContextOptions <LivestockContext> >();

            using var context = new LivestockContext(options);
            if (_env.IsE2E())
            {
                context.Database.EnsureCreated();
            }
            else
            {
                context.Database.Migrate();
            }

            SeedFeedTypes(context);
            SeedUnits(context);
            SeedMedicine(context);

            context.SaveChanges();
        }
Beispiel #23
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, LivestockContext livestockDb)
        {
            //livestockDb.Database.Migrate();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            // For nginx
            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
            });

            app.UseRequestLocalization();
            app.UseHttpsRedirection();
            app.UseStatusCodePages();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseAuthentication();
            app.UseMiddleware <AimLoginMiddleware>();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "areas",
                    template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
                    );
            });
        }
Beispiel #24
0
 public EnumVehicleLifeEventTypeController(LivestockContext context)
 {
     _context = context;
 }
Beispiel #25
0
 public MenuHeaderItemMapController(LivestockContext context)
 {
     _context = context;
 }
 public AlUserInfoController(LivestockContext context)
 {
     _context = context;
 }
 public LifeEventController(LivestockContext livestock)
 {
     this._livestock = livestock;
 }
 public LocationController(LivestockContext context)
 {
     _context = context;
 }
Beispiel #29
0
 public EnumCritterLifeEventTypeController(LivestockContext context)
 {
     _context = context;
 }
 public CritterLifeEventController(LivestockContext context)
 {
     _context = context;
 }