public async Task <IActionResult> NewDevice([FromBody] Device dev)
    {
        if (ModelState.IsValid)
        {
            await _dbcontext.AddAsync(dev);

            _dbcontext.SaveChanges();
            return(new ObjectResult(dev));
        }
        return(BadRequest(ModelState));
    }
예제 #2
0
        public async Task <IActionResult> CreateOrder()
        {
            try
            {
                string name = HttpContext.User.Identity.Name;
                var    user = await _db.User.Include(z => z.Orders).
                              Where(x => x.UserName == name).ToArrayAsync();

                var Order = new Order
                {
                    OrderStatus = OrderStatus.Rendering,
                    OrderDate   = DateTime.Now,
                    CustomerId  = user[0].Id
                };
                await _db.AddAsync(Order);

                await _db.SaveChangesAsync();

                return(Ok(Order));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return(StatusCode(409));
            }
        }
예제 #3
0
        public async Task <User> CreateUser(User user)
        {
            EfModels.Models.User UserEF = _mapper.Map <EfModels.Models.User>(user);
            await _db.AddAsync(UserEF);

            await _db.SaveChangesAsync();

            return(_mapper.Map <User>(UserEF));
        }
예제 #4
0
        public async Task <Store> CreateStore(StoreModel model)
        {
            var store = new Store();

            Reflection.UpdateEntity(store, model);
            await _db.AddAsync(store);

            var stock = new Stock
            {
                Store = store
            };

            stock.Products = new Dictionary <string, int>();
            await _db.AddAsync(stock);

            await _db.SaveChangesAsync();

            return(store);
        }
        public async Task <Case> Post([FromBody] Case newCase)
        {
            newCase.refNumber = DateTime.Now.Ticks.ToString();
            //newCase.CompanyId = 1;
            EntityEntry <Case> z = await db.AddAsync(newCase);

            await db.SaveChangesAsync();

            return(z.Entity);
        }
예제 #6
0
        public static async Task DoWhatIMean(MyDbContext context)
        {
            var match = new Customer
            {
                Orders = new List <Order>
                {
                    new Order(),
                    new Order(),
                },
                Address = new Address(),
            };

            // See aspnet/EntityFrameworkCore#6534
            await context.AddAsync(match);

            await context.SaveChangesAsync();

            var results = from c in context.Customers
                          where c.Id < 400
                          select new
            {
                Name  = c.Address.CustomerId,
                Count = c.Orders.Count(),
            };

            var realz = await results.ToListAsync();

            Console.WriteLine($"DTO count: {realz.Count}.");

            // See aspnet/EntityFrameworkCore#8208 and aspnet/EntityFrameworkCore#9128
            var lastResults = await context.Customers.Select(c => new
            {
                Name       = c.Address.CustomerId,
                MaxOrderId = c.Orders.OrderByDescending(o => o.Id).Select(o => o.Id).First(),
            }).LastAsync();

            Console.WriteLine($"Inner DTO max Id: {lastResults.MaxOrderId}");

            // See aspnet/EntityFrameworkCore#8208 and aspnet/EntityFrameworkCore#9128
            var deepResults = await context.Customers.Select(c => new
            {
                Name   = c.Address.CustomerId,
                Orders = c.Orders.Select(i => new
                {
                    i.Id,
                    i.Yes
                }).ToList(),
            }).ToListAsync();

            foreach (var item in deepResults)
            {
                Console.WriteLine($"Inner DTO count: {item.Orders.Count}.");
            }
        }
예제 #7
0
        public async Task <Product> CreateProduct(ProductModel model)
        {
            var product = new Product();

            Reflection.UpdateEntity(product, model);
            await _db.AddAsync(product);

            await _db.SaveChangesAsync();

            return(product);
        }
예제 #8
0
        public async Task <Staff> CreateStaff(StaffModel model)
        {
            var staff = new Staff();

            Reflection.UpdateEntity(staff, model);
            await _db.AddAsync(staff);

            await _db.SaveChangesAsync();

            return(staff);
        }
예제 #9
0
        public async Task UpdateForDepartmentAsync
            (int departmentId, DateTime date, IList <DailyHealth> dailyHealths)
        {
            var employeeIds = await _myContext.Employees
                              .Where(x => x.DepartmentId == departmentId)
                              .Select(x => x.Id)
                              .ToListAsync();

            var inDb = await _myContext.DailyHealths
                       .Where(x => x.Date == date && employeeIds.Contains(x.EmployeeId))
                       .ToListAsync();

            foreach (var dbItem in inDb)
            {
                var one = dailyHealths
                          .SingleOrDefault(x =>
                                           x.EmployeeId == dbItem.EmployeeId && x.Date == dbItem.Date);
                if (one != null)
                {
                    dbItem.HealthCondition = one.HealthCondition;
                    dbItem.Temperature     = one.Temperature;
                    dbItem.Remark          = one.Remark;
                    _myContext.Update(dbItem);
                }
            }

            var dbKeys = inDb.Select(x =>
                                     new { x.EmployeeId, x.Date }).ToList();
            var incomingKeys = dailyHealths
                               .Select(x => new { x.EmployeeId, x.Date }).ToList();
            var toAddKeys = incomingKeys.Except(dbKeys); // todo

            foreach (var addKey in toAddKeys)
            {
                var toAdd = dailyHealths
                            .Single(x => x.EmployeeId == addKey.EmployeeId &&
                                    x.Date == addKey.Date);
                await _myContext.AddAsync(toAdd);
            }

            var toRemoveKeys = dbKeys.Except(incomingKeys); // todo

            foreach (var removeKey in toRemoveKeys)
            {
                var toRemove = inDb
                               .Single(x => x.EmployeeId == removeKey.EmployeeId &&
                                       x.Date == removeKey.Date);
                _myContext.Remove(toRemove);
            }

            await _myContext.SaveChangesAsync();
        }
예제 #10
0
        public async Task <Order> CreateOrder()
        {
            var order = new Order
            {
                OrderStatus = OrderStatus.Rendering,
                OrderDate   = DateTime.Now
            };
            await _db.AddAsync(order);

            await _db.SaveChangesAsync();

            return(order);
        }
예제 #11
0
        public async Task <bool> SendAsync(EmailEntity model, CancellationToken ct = default)
        {
            // Operation to send email goes here


            // Save email object to database
            await _context.AddAsync(model, ct);

            var t = await _context.SaveChangesAsync(cancellationToken : ct);

            // based on method result, return true or false
            return(t > 0);
        }
예제 #12
0
        public async Task <T> Create <T>(T post) where T : Post
        {
            await _myDbContext.AddAsync(post);

            await _myDbContext.SaveChangesAsync();

            if (post.IsPublic == true && post is AutoPost autoPost)
            {
                AutoPostSearchDTO postToIndex = _mapper.Map <T, AutoPostSearchDTO>(post);
                await _elasticClient.IndexDocumentAsync(postToIndex);
            }

            return(post);
        }
예제 #13
0
        public async Task <ActionResult <StandardResponse> > CopyContainer(Post post)
        {
            // Assume the username of post is the user who want to copy the container
            // NOT THE AURTHOR
            string ipAddress = gRpcClient.getServerIp(new ServerRequest()
            {
                ContainerId = post.ContainerId.ToString()
            }).Ip;

            if (ipAddress.Length == 0)
            {
                return(NotFound());
            }
            Container container = await _context.Container.FindAsync(post.ContainerId);

            Container newContainer = new Container()
            {
                Username      = post.Username,
                ContainerName = container.ContainerName,
                CreateTime    = DateTime.Now,
                Type          = container.Type
            };
            await _context.AddAsync(newContainer);

            await _context.SaveChangesAsync();

            CopyContainerDto dto = new CopyContainerDto()
            {
                ContainerId = newContainer.ContainerId,
                ImageId     = post.PostId
            };
            var dtoJSON = new StringContent(
                System.Text.Json.JsonSerializer.Serialize(dto, new JsonSerializerOptions()),
                Encoding.UTF8,
                "application/json");

            using var httpResponse = await _factory.CreateClient()
                                     .PostAsync("http://" + ipAddress + ":13000/api/docker/Import", dtoJSON);

            if (httpResponse.IsSuccessStatusCode)
            {
                return(NewResponse(200, "复制成功", null));
            }
            else
            {
                return(NewResponse(200, "复制失败", null));
            }
        }
예제 #14
0
        public async Task <bool> Add(Store store)
        {
            bool bReturn = false;

            try
            {
                await _context.AddAsync <Store>(store);

                await _context.SaveChangesAsync();

                bReturn = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return(bReturn);
        }
예제 #15
0
        public async Task <bool> Add(Customer customer)
        {
            bool bReturn = false;

            try
            {
                await _context.AddAsync <Customer>(customer);

                await _context.SaveChangesAsync();//.SaveChanges();

                bReturn = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return(bReturn);
        }
예제 #16
0
        public async Task <Categoria> CriaCategoriaAsync(Categoria Categoria)
        {
            var novoCategoria = new Categoria
            {
                Nome      = Categoria.Nome,
                Descricao = Categoria.Descricao,
            };

            try
            {
                await _db.AddAsync(novoCategoria);

                await _db.SaveChangesAsync();

                return(novoCategoria);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
예제 #17
0
        public async Task <Result> FillAsync(int size)
        {
            for (int i = 0; i < size; i++)
            {
                var name      = $"{i}-{DateTime.Now.ToString("YYYY-MM-DD")}";
                var now       = DateTimeOffset.Now;
                var dataModel = new TestDataModel(name, now.ToString("o"), now);
                await _context.AddAsync(dataModel);
            }

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error occurred during saving data model {0} - {1}", e.Message, e.StackTrace);
                return(Result.Error);
            }

            return(Result.Success);
        }
예제 #18
0
        public async Task <UsersTransactions> SendAsync(string comment, double credits, string phone, string username)
        {
            var userTo   = _context.Users.FirstOrDefault(x => x.PhoneNumber == phone);
            var userFrom = _context.Users.FirstOrDefault(x => x.UserName == username);

            if (userTo == null)
            {
                throw new ArgumentNullException("User with this phone number does not exist.");
            }

            if (userFrom.Balance < credits)
            {
                throw new ArgumentException("Insufficient amount");
            }

            if (string.IsNullOrWhiteSpace(phone))
            {
                throw new ArgumentException("Phone can not be null");
            }

            userFrom.Balance -= credits;
            userTo.Balance   += credits;
            var transaction = new UsersTransactions
            {
                Id                = new Guid(),
                Comment           = comment,
                TransactionAmount = credits,
                UserFrom          = userFrom,
                UserTo            = userTo
            };

            this._context.Update(userFrom);
            this._context.Update(userTo);
            await _context.AddAsync(transaction);

            await _context.SaveChangesAsync();

            return(transaction);
        }
        public async Task <bool> Create(RatingRes ratingRes)
        {
            var rate = _mapper.Map <Rating>(ratingRes);

            var userId = _IhttpContextAccessor.HttpContext.User.FindFirstValue("sub");

            rate.UserId = userId;

            await _context.AddAsync(rate);

            await _context.SaveChangesAsync();

            var product = await _context.Products.FindAsync(ratingRes.ProductId);

            var rates = await Task.FromResult((int)_context.Ratings
                                              .Where(rate => rate.ProductId.Equals(ratingRes.ProductId))
                                              .Select(rate => rate.Value)
                                              .Average());

            product.Rated = rates;
            await _context.SaveChangesAsync();

            return(true);
        }
예제 #20
0
        public async Task <Produto> CriaProdutoAsync(Produto produto)
        {
            var novoProduto = new Produto
            {
                Nome        = produto.Nome,
                Descricao   = produto.Descricao,
                Valor       = produto.Valor,
                Marca       = produto.Marca,
                CategoriaId = produto.CategoriaId
            };

            try
            {
                await _db.AddAsync(novoProduto);

                await _db.SaveChangesAsync();

                return(novoProduto);
            } catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }