示例#1
0
        public IActionResult Post(CustomEmployee model)
        {
            var countryId = from c in db.Country
                            where c.country_name == model.country_name
                            select c.id;

            if (model.id != 0)
            {
                Employee employee = db.Employees.Where(x => x.id == model.id).FirstOrDefault();
                employee.name       = model.name;
                employee.job_title  = model.job_title;
                employee.gender     = model.gender;
                employee.email      = model.email;
                employee.phone_no   = model.phone_no;
                employee.address    = model.address;
                employee.country_id = countryId.FirstOrDefault();
                db.SaveChanges();
                return(Ok(2));
            }
            else
            {
                Employee employee = new Employee();
                employee.name       = model.name;
                employee.job_title  = model.job_title;
                employee.gender     = model.gender;
                employee.email      = model.email;
                employee.phone_no   = model.phone_no;
                employee.address    = model.address;
                employee.country_id = countryId.FirstOrDefault();
                db.Add(employee);
                db.SaveChanges();

                return(Ok(1));
            }
        }
示例#2
0
        public AuthenticateResponse Authenticate(AuthenticateRequest model, string ipAddress)
        {
            var user = _webApiDbcontext.User.SingleOrDefault(x => x.Username == model.Username && x.Password == model.Password);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt and refresh tokens
            var jwtToken     = GenerateJwtToken(user);
            var refreshToken = GenerateRefreshToken(ipAddress);

            if (user.RefreshTokens == null)
            {
                user.RefreshTokens = new List <RefreshToken>();
            }
            // save refresh token
            user.RefreshTokens.Add(refreshToken);
            _webApiDbcontext.Update(user);
            _webApiDbcontext.SaveChanges();

            return(new AuthenticateResponse(user, jwtToken, refreshToken.Token));
        }
示例#3
0
        public PurchaseTransactionDto CreateTrans(long id, PurchaseTransactionDto purchaseTransaction)
        {
            var user = _context.Users.FirstOrDefault(x => x.Id == id);

            if (user == null)
            {
                return(null);
            }

            var postTrans = mapper.Map <PurchaseTransaction>(purchaseTransaction);

            _context.PurchaseTransactions.Add(postTrans);
            _context.SaveChanges();

            purchaseTransaction = mapper.Map <PurchaseTransactionDto>(postTrans);

            // if member’s birth month falls into transact month
            if (user.Dob.Month == postTrans.TransactDateTime.Month)
            {
                //add 10 points to user
                user.Point = user.Point.HasValue ? user.Point += _appSettings.BirthmonthPoint : user.Point = _appSettings.BirthmonthPoint;
                _context.SaveChanges();
                // give Rp. 100 value voucher with 3 months of validity
                purchaseTransaction.Voucher = CreateVoucher(postTrans.TransactDateTime,
                                                            postTrans.TransactDateTime.AddMonths(_appSettings.VoucherValidity),
                                                            _appSettings.VoucherValue);
            }
            ;

            return(purchaseTransaction);
        }
        public Location CreateLocation(Location newLocation)
        {
            var location = _context.Locations.Add(newLocation);

            _context.SaveChanges();

            return(newLocation);
        }
示例#5
0
        public Entities.Book DeleteBook(string category, int bookId)
        {
            var book = context.Genres.Include(g => g.Books).FirstOrDefault(g => g.Title == category).Books.FirstOrDefault(b => b.Id == bookId);

            context.Books.Remove(book);
            context.SaveChanges();
            return(book);
        }
示例#6
0
        private void CreateEditions()
        {
            var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName);

            if (defaultEdition == null)
            {
                defaultEdition = new Edition {
                    Name = EditionManager.DefaultEditionName, DisplayName = EditionManager.DefaultEditionName
                };
                _context.Editions.Add(defaultEdition);
                _context.SaveChanges();

                /* Add desired features to the standard edition, if wanted... */
            }
        }
示例#7
0
        public IActionResult Like([FromBody] LikeDto likeDto)
        {
            if (likeDto == null)
            {
                return(BadRequest());
            }

            likeDto.CreatedDate = DateTime.UtcNow;

            var existingMatch = _context.Likes.AsQueryable().Where(x => x.UserId == likeDto.UserId && x.LikedId == likeDto.LikedId);

            if (existingMatch.Any())
            {
                return(Ok());
            }

            var likesEntry = _context.Likes.Add(_mapper.Map <Likes>(likeDto));

            _context.SaveChanges();
            var match = _context.Likes.AsQueryable().FirstOrDefault(x => x.UserId == likeDto.LikedId && x.LikedId == likeDto.UserId);

            if (match != null)
            {
                return(Ok(true));
            }

            return(likesEntry == null?StatusCode(500) : Ok());
        }
示例#8
0
        public async Task <ActionResult <UserClienteInfo> > CrearUserCliente(UserClienteInfo model)
        {
            var user = new ApplicationUser {
                UserName = model.Cliente.email, Cliente = model.Cliente
            };

            if (await _userManager.FindByNameAsync(model.Cliente.email) != null)
            {
                return(BadRequest("El email está en uso"));
            }
            try
            {
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "Cliente");


                    _context.SaveChanges();

                    return(model);
                }
                else
                {
                    return(BadRequest("Email o contraseña invalidos."));
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
示例#9
0
        public void Create()
        {
            new DefaultEditionCreator(_context).Create();
            new DefaultLanguagesCreator(_context).Create();
            new HostRoleAndUserCreator(_context).Create();
            new DefaultSettingsCreator(_context).Create();

            _context.SaveChanges();
        }
示例#10
0
        private void AddSettingIfNotExists(string name, string value, int?tenantId = null)
        {
            if (_context.Settings.IgnoreQueryFilters().Any(s => s.Name == name && s.TenantId == tenantId && s.UserId == null))
            {
                return;
            }

            _context.Settings.Add(new Setting(tenantId, null, name, value));
            _context.SaveChanges();
        }
示例#11
0
        private void AddLanguageIfNotExists(ApplicationLanguage language)
        {
            if (_context.Languages.IgnoreQueryFilters().Any(l => l.TenantId == language.TenantId && l.Name == language.Name))
            {
                return;
            }

            _context.Languages.Add(language);
            _context.SaveChanges();
        }
示例#12
0
        public UserDto CreateUser(CreateUserDto user)
        {
            // check registered email
            var userInDb = _context.Users.FirstOrDefault(x => x.Email == user.Email);

            if (userInDb != null)
            {
                return(null);
            }

            // map encrypted password
            var mapUser = mapper.Map <User>(user);

            mapUser.Password = CreatePasswordHash(user.Password);

            _context.Users.Add(mapUser);
            _context.SaveChanges();

            return(mapper.Map <UserDto>(mapUser));
        }
示例#13
0
        public async Task <string> Post(Blog blog)
        {
            if (!ModelState.IsValid)
            {
                return(JsonConvert.SerializeObject(false));
            }

            await _dbContext.Blogs.AddAsync(blog);

            _dbContext.SaveChanges();

            return(JsonConvert.SerializeObject(true));
        }
示例#14
0
        public IActionResult Post([FromBody] Team team)
        {
            if (ModelState.IsValid)
            {
                _context.Teams.Add(team);
                _context.SaveChanges();

                return(Ok("Команда добавлена."));
            }
            else
            {
                return(BadRequest());
            }
        }
        public User Create(User user, string password)
        {
            // Validation..
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new AppException("Password is required");
            }
            if (_context.Users.Any(x => x.Username == user.Username))
            {
                throw new AppException("Username " + user.Username + " is already taken");
            }

            byte[] passwordHash, passwordSalt;
            CreatePasswordHash(password, out passwordHash, out passwordSalt);

            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            _context.Users.Add(user);
            _context.SaveChanges();

            return(user);
        }
示例#16
0
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var context = new WebApiDbContext(
                       serviceProvider.GetRequiredService <DbContextOptions <WebApiDbContext> >()))
            {
                // Look for any stations
                if (context.Stations.Any())
                {
                    Console.WriteLine("FOUND SOME");
                    return;   // Data was already seeded
                }

                Console.WriteLine($"READING FROM STATIONS");
                List <NOAAStation> stationList = NOAAStationHelper.GetNOAAStationsList();

                Console.WriteLine($"FINDING DUPLICATES");
                // as it turns out, there are duplicates in the data
                var duplicates = stationList.GroupBy(s => s.ICAO)
                                 .Where(grp => grp.Count() > 1)
                                 .Select(grp => grp.Key);

                Console.WriteLine($"{duplicates.Count()} DUPLICATES FOUND");

                //find the duplicate ICAO values
                //store one
                //remove all
                //re-insert the one
                Console.WriteLine($"REMOVING DUPLICATES");
                foreach (var item in duplicates)
                {
                    NOAAStation m = stationList.First(s => s.ICAO == item);
                    stationList.RemoveAll(s => s.ICAO == item);
                    stationList.Add(m);
                }

                //WRITE TO DB
                try{
                    context.Stations.AddRange(stationList);
                    context.SaveChanges();
                    Console.WriteLine($"LOADING COMPLETE: {context.Stations.Count()}");
                }
                catch (Exception exp) {
                    Console.WriteLine(exp.Message);
                }
            }
        }
示例#17
0
        private void CreateDefaultTenant()
        {
            // Default tenant

            var defaultTenant = _context.Tenants.IgnoreQueryFilters().FirstOrDefault(t => t.TenancyName == AbpTenantBase.DefaultTenantName);

            if (defaultTenant == null)
            {
                defaultTenant = new Tenant(AbpTenantBase.DefaultTenantName, AbpTenantBase.DefaultTenantName);

                var defaultEdition = _context.Editions.IgnoreQueryFilters().FirstOrDefault(e => e.Name == EditionManager.DefaultEditionName);
                if (defaultEdition != null)
                {
                    defaultTenant.EditionId = defaultEdition.Id;
                }

                _context.Tenants.Add(defaultTenant);
                _context.SaveChanges();
            }
        }
示例#18
0
        public IActionResult Post(ApplicationUserModel model)
        {
            var user = db.applicationUsers.Where(x => x.name == model.name).FirstOrDefault();

            if (user == null)
            {
                ApplicationUser applicationUser = new ApplicationUser();
                applicationUser.name         = model.name;
                applicationUser.email        = model.email;
                applicationUser.password     = model.password;
                applicationUser.created_date = DateTime.Now;
                applicationUser.updated_date = DateTime.Now;
                db.Add(applicationUser);
                db.SaveChanges();
                return(Ok(true));
            }
            else
            {
                return(Ok(false));
            }
        }
        /// <summary>
        /// Save method.
        /// </summary>
        public void Save()
        {
            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                var outputLines = new List <string>();
                foreach (var eve in e.EntityValidationErrors)
                {
                    outputLines.Add(string.Format("{0}: Entity of type \"{1}\" in state \"{2}\" has the following validation errors:", DateTime.Now, eve.Entry.Entity.GetType().Name, eve.Entry.State));
                    foreach (var ve in eve.ValidationErrors)
                    {
                        outputLines.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                    }
                }
                System.IO.File.AppendAllLines(@"C:\errors.txt", outputLines);

                throw e;
            }
        }
示例#20
0
        private void CreateDefaultBlogs()
        {
            // Default Blogs

            if (!_context.Tags.Any())
            {
                List <Tag> tags = new List <Tag> {
                    new Tag()
                    {
                        Title = "c#", CreationTime = DateTime.Now, CreatorUserId = 1, IsDeleted = false
                    },
                    new Tag()
                    {
                        Title = ".net", CreationTime = DateTime.Now, CreatorUserId = 1, IsDeleted = false
                    },
                    new Tag()
                    {
                        Title = ".net core", CreationTime = DateTime.Now, CreatorUserId = 1, IsDeleted = false
                    },
                    new Tag()
                    {
                        Title = "sql", CreationTime = DateTime.Now, CreatorUserId = 1, IsDeleted = false
                    },
                    new Tag()
                    {
                        Title = "java", CreationTime = DateTime.Now, CreatorUserId = 1, IsDeleted = false
                    },
                    new Tag()
                    {
                        Title = "javascript", CreationTime = DateTime.Now, CreatorUserId = 1, IsDeleted = false
                    }
                };
                _context.Tags.AddRange(tags);
                _context.SaveChanges();
            }
        }
示例#21
0
 public void Commit()
 {
     Context.SaveChanges();
 }
        public static void Initialize(IServiceProvider serviceProvider)
        {
            using (var _context = new WebApiDbContext(serviceProvider.GetRequiredService <DbContextOptions <WebApiDbContext> >()))
            {
                // Agregando Artistas a la BD
                if (_context.Artistas.Any())
                {
                    return;
                }

                _context.Artistas.AddRange(
                    new Artista {
                    Nombre = "Luis Miguel"
                },
                    new Artista {
                    Nombre = "Ricardo Arjona"
                },
                    new Artista {
                    Nombre = "Kalimba"
                }
                    );

                _context.SaveChanges();


                // Agregando Albumes a la BD
                if (_context.Albumes.Any())
                {
                    return;
                }

                _context.Albumes.AddRange(
                    new Album
                {
                    ArtistaID = _context.Artistas.FirstOrDefault(a => a.Nombre.Equals("Kalimba")).ArtistaID,
                    Titulo    = $"Mi Otro Yo",
                    Precio    = 200,
                    Anio      = 2008
                },

                    new Album
                {
                    ArtistaID = _context.Artistas.FirstOrDefault(a => a.Nombre.Equals("Kalimba")).ArtistaID,
                    Titulo    = $"Aerosoul",
                    Precio    = 275,
                    Anio      = 2004
                },

                    new Album
                {
                    ArtistaID = _context.Artistas.FirstOrDefault(a => a.Nombre.Equals("Ricardo Arjona")).ArtistaID,
                    Titulo    = $"Circo Soledad",
                    Precio    = 180,
                    Anio      = 2017
                },

                    new Album
                {
                    ArtistaID = _context.Artistas.FirstOrDefault(a => a.Nombre.Equals("Luis Miguel")).ArtistaID,
                    Titulo    = $"Romance",
                    Precio    = 290,
                    Anio      = 1991
                }
                    );

                _context.SaveChanges();
            }
        }
示例#23
0
 public IActionResult Post(Player player)
 {
     _context.Players.Add(player);
     _context.SaveChanges();
     return(Ok());
 }
示例#24
0
        private void CreateRolesAndUsers()
        {
            // Admin role

            var adminRole = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == _tenantId && r.Name == StaticRoleNames.Tenants.Admin);

            if (adminRole == null)
            {
                adminRole = _context.Roles.Add(new Role(_tenantId, StaticRoleNames.Tenants.Admin, StaticRoleNames.Tenants.Admin)
                {
                    IsStatic = true
                }).Entity;
                _context.SaveChanges();
            }

            // Grant all permissions to admin role

            var grantedPermissions = _context.Permissions.IgnoreQueryFilters()
                                     .OfType <RolePermissionSetting>()
                                     .Where(p => p.TenantId == _tenantId && p.RoleId == adminRole.Id)
                                     .Select(p => p.Name)
                                     .ToList();

            var permissions = PermissionFinder
                              .GetAllPermissions(new WebApiAuthorizationProvider())
                              .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Tenant) &&
                                     !grantedPermissions.Contains(p.Name))
                              .ToList();

            var blogsPremission = PermissionFinder.GetAllPermissions(new BlogsAuthorizationProvider());

            permissions.AddRange(blogsPremission);

            if (permissions.Any())
            {
                _context.Permissions.AddRange(
                    permissions.Select(permission => new RolePermissionSetting
                {
                    TenantId  = _tenantId,
                    Name      = permission.Name,
                    IsGranted = true,
                    RoleId    = adminRole.Id
                })
                    );
                _context.SaveChanges();
            }

            // Admin user

            var adminUser = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == _tenantId && u.UserName == AbpUserBase.AdminUserName);

            if (adminUser == null)
            {
                adminUser                  = User.CreateTenantAdminUser(_tenantId, "*****@*****.**");
                adminUser.Password         = new PasswordHasher <User>(new OptionsWrapper <PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(adminUser, "123qwe");
                adminUser.IsEmailConfirmed = true;
                adminUser.IsActive         = true;

                _context.Users.Add(adminUser);
                _context.SaveChanges();

                // Assign Admin role to admin user
                _context.UserRoles.Add(new UserRole(_tenantId, adminUser.Id, adminRole.Id));
                _context.SaveChanges();
            }
        }
        public static void Initialize(WebApiDbContext _context)
        {
            #region Datos Iniciales de Artistas
            // Buscar cualquier artista
            if (_context.Artistas.Any())
            {
                return;
            }

            var artistas = new Artista[]
            {
                new Artista()
                {
                    Nombre = "Ricardo Arjona"
                },
                new Artista()
                {
                    Nombre = "Luis Miguel"
                },
                new Artista()
                {
                    Nombre = "Kalimba"
                }
            };

            _context.Artistas.AddRange(artistas);
            _context.SaveChanges();
            #endregion Datos Iniciales de Artistas

            #region Datos Iniciales de Albumes
            // Buscar cualquier album
            if (_context.Albumes.Any())
            {
                return;
            }

            var albumes = new Album[]
            {
                new Album()
                {
                    ArtistaID = _context.Artistas.FirstOrDefault(a => a.Nombre.Equals("Luis Miguel")).ArtistaID,
                    Titulo    = "Romance",
                    Anio      = 1991,
                    Precio    = 180
                },
                new Album()
                {
                    ArtistaID = _context.Artistas.FirstOrDefault(a => a.Nombre.Equals("Ricardo Arjona")).ArtistaID,
                    Titulo    = "Circo Soledad",
                    Anio      = 2017,
                    Precio    = 190
                },
                new Album()
                {
                    ArtistaID = _context.Artistas.FirstOrDefault(a => a.Nombre.Equals("Kalimba")).ArtistaID,
                    Titulo    = "Aerosoul",
                    Anio      = 2004,
                    Precio    = 210
                }
            };

            _context.Albumes.AddRange(albumes);
            _context.SaveChanges();
            #endregion Datos Iniciales de Albumes
        }
示例#26
0
        private void CreateHostRoleAndUsers()
        {
            // Admin role for host

            var adminRoleForHost = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == null && r.Name == StaticRoleNames.Host.Admin);

            if (adminRoleForHost == null)
            {
                adminRoleForHost = _context.Roles.Add(new Role(null, StaticRoleNames.Host.Admin, StaticRoleNames.Host.Admin)
                {
                    IsStatic = true, IsDefault = true
                }).Entity;
                _context.SaveChanges();
            }

            // Grant all permissions to admin role for host

            var grantedPermissions = _context.Permissions.IgnoreQueryFilters()
                                     .OfType <RolePermissionSetting>()
                                     .Where(p => p.TenantId == null && p.RoleId == adminRoleForHost.Id)
                                     .Select(p => p.Name)
                                     .ToList();

            var permissions = PermissionFinder
                              .GetAllPermissions(new WebApiAuthorizationProvider())
                              .Where(p => p.MultiTenancySides.HasFlag(MultiTenancySides.Host) &&
                                     !grantedPermissions.Contains(p.Name))
                              .ToList();

            if (permissions.Any())
            {
                _context.Permissions.AddRange(
                    permissions.Select(permission => new RolePermissionSetting
                {
                    TenantId  = null,
                    Name      = permission.Name,
                    IsGranted = true,
                    RoleId    = adminRoleForHost.Id
                })
                    );
                _context.SaveChanges();
            }

            // Admin user for host

            var adminUserForHost = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == null && u.UserName == AbpUserBase.AdminUserName);

            if (adminUserForHost == null)
            {
                var user = new User
                {
                    TenantId         = null,
                    UserName         = AbpUserBase.AdminUserName,
                    Name             = "admin",
                    Surname          = "admin",
                    EmailAddress     = "*****@*****.**",
                    IsEmailConfirmed = true,
                    IsActive         = true
                };

                user.Password = new PasswordHasher <User>(new OptionsWrapper <PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(user, "123qwe");
                user.SetNormalizedNames();

                adminUserForHost = _context.Users.Add(user).Entity;
                _context.SaveChanges();

                // Assign Admin role to admin user
                _context.UserRoles.Add(new UserRole(null, adminUserForHost.Id, adminRoleForHost.Id));
                _context.SaveChanges();

                _context.SaveChanges();
            }
        }
 public bool Save()
 {
     return(_context.SaveChanges() >= 0);
 }
示例#28
0
 public int Delete(int Id, int CompanyId)
 {
     dbContext.Staffs.Remove(dbContext.Staffs.FirstOrDefault(s => s.Id == Id && s.CompanyId == CompanyId));
     return(dbContext.SaveChanges());
 }