コード例 #1
0
        public async Task <IActionResult> Create([Bind("ServiceBookLogId,Date,Mileage,ServiceType,NextServiceDate,NextServiceMileage,CarWork,Details")] ServiceBookLog serviceBookLog)
        {
            var currentUserId = userManager.GetUserId(User);

            if (ModelState.IsValid)
            {
                _context.Add(serviceBookLog);
                await _context.SaveChangesAsync();

                int?id = int.Parse(RouteData.Values["id"].ToString());

                if (id != null)
                {
                    var serviceBooks = new ServiceBook[]
                    {
                        new ServiceBook {
                            CarId = (int)id, ServiceBookLogId = serviceBookLog.ServiceBookLogId
                        }
                    };

                    foreach (ServiceBook serviceBook in serviceBooks)
                    {
                        _context.ServiceBooks.Add(serviceBook);
                    }
                    await _context.SaveChangesAsync();
                }
                return(RedirectToAction("Details", "Cars", new { id }));
            }
            return(View(serviceBookLog));
        }
コード例 #2
0
        //Add new customer record
        public async Task AddCustomer(CustomerDTO customerDTO)
        {
            //check if customer already exists
            Customer customer = await db.Customers.Where(i => i.CustomerName == customerDTO.CustomerName).FirstAsync();

            if (customer != null)
            {
                throw new Exception("Customer already exists");
            }

            Customer _customer = new Customer
            {
                CustomerName    = customerDTO.CustomerName,
                PhysicalAddress = customerDTO.PhysicalAddress,
                Town            = customerDTO.Town,
                PostalCode      = customerDTO.PostalCode,
                Province        = customerDTO.Province,
                Telephone       = customerDTO.Telephone,
                Mobile          = customerDTO.Mobile,
                Email           = customerDTO.Email
            };
            await db.Customers.AddAsync(_customer);

            await db.SaveChangesAsync();
        }
コード例 #3
0
        public async Task <IActionResult> Create(Car car, IFormFile image)
        {
            var currentUserId = userManager.GetUserId(User);

            if (ModelState.IsValid)
            {
                car.UserId = currentUserId;

                if (image != null && image.Length > 0)
                {
                    var fileName = string.Empty;

                    if (car.UserId != null)
                    {
                        fileName = $"{car.Brand}_{car.Model}_{car.UserId}.{image.FileName.Split('.').Last()}";
                    }
                    else
                    {
                        fileName = $"{car.Brand}_{car.Model}_null.{image.FileName.Split('.').Last()}";
                    }
                    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\carimages", fileName);
                    using (var fileSteam = new FileStream(filePath, FileMode.Create))
                    {
                        await image.CopyToAsync(fileSteam);
                    }
                    car.Image = fileName;
                }

                _context.Add(car);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(car));
        }
コード例 #4
0
        public async Task SaveAsync(T objectModel, long userId, long?targetObjectId, long houseId)
        {
            var objectTypeName = objectModel.GetType().Name;
            var objectTypeId   = context.Set <ObjectType>().Where(x => x.Name == objectTypeName).FirstOrDefault().Id;

            var _object = new Models.Object()
            {
                CreatedById  = userId,
                ModifiedById = userId,
                CreatedDate  = DateTime.Now,
                ModifiedDate = DateTime.Now,
                ObjectTypeId = objectTypeId
            };

            await context.AddAsync(_object);

            await context.SaveChangesAsync();

            historyContext.PopulateHistory((int)HistoryFunctionTypes.Create, objectModel, _object, userId, targetObjectId, houseId);

            objectModel.ObjectId = _object.ObjectId;

            await context.AddAsync <T>(objectModel);

            await context.SaveChangesAsync();
        }
コード例 #5
0
        public async Task <IActionResult> PutEmployee(int id, Employee employee)
        {
            if (id != employee.EmployeeID)
            {
                return(BadRequest());
            }

            _context.Entry(employee).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!EmployeeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
コード例 #6
0
 public override async Task Add(InventarioModel inventario)
 {
     try
     {
         _context.tbl_inventario.Add(inventario);
         await _context.SaveChangesAsync();
     }
     catch (Exception)
     {
         throw;
     }
 }
コード例 #7
0
 public override async Task Add(ProductoModel producto)
 {
     try
     {
         _context.tbl_producto.Add(producto);
         await _context.SaveChangesAsync();
     }
     catch (Exception)
     {
         throw;
     }
 }
コード例 #8
0
        //Add new order record
        public async Task AddOrder(OrderDTO orderDTO)
        {
            CultureInfo en = new CultureInfo("en");

            /*
             * // convert delivery date date string into DateTime object
             * DateTime deliveryDate;
             * try
             * {
             *  deliveryDate = DateTime.ParseExact(orderDTO.deliveryDate, "dd/mm/yyyy", en);
             * }
             * catch (Exception ex)
             * {
             *  throw ex;
             * }
             */

            //search for a product record to get the price
            Product product = await db.Products.FindAsync(orderDTO.ProductID);

            if (product == null)
            {
                throw new Exception("Product not found");
            }

            //search for a customer record
            Customer customer = await db.Customers.FindAsync(orderDTO.CustomerID);

            if (customer == null)
            {
                throw new Exception("Customer not found");
            }

            Order order = new Order
            {
                CustomerID   = customer.CustomerID,
                Total        = product.UnitPrice * orderDTO.Quantity,
                OrderDate    = new DateTime(),
                DeliveryDate = DateTime.ParseExact(orderDTO.DeliveryDate, "dd/mm/yyyy", en)
            };

            order.OrderDetails.Add(
                new OrderDetail
            {
                Order    = order,
                Product  = product,
                Quantity = orderDTO.Quantity,
            });

            db.Orders.Add(order);
            await db.SaveChangesAsync();
        }
コード例 #9
0
        //Add new order record
        public async Task <Order> AddOrder(CreateOrderInput createOrderInput)
        {
            Debug.WriteLine(JsonConvert.SerializeObject(createOrderInput.OrderDetails));
            //CultureInfo en = new CultureInfo("en");

            //search for a customer record
            Customer customer = await db.Customers.FindAsync(createOrderInput.CustomerID);

            if (customer == null)
            {
                throw new Exception("Customer not found");
            }

            Order order = new Order
            {
                Customer        = customer,
                OrderDate       = DateTime.Now,
                DeliveryAddress = createOrderInput.DeliveryAddress,
                DeliveryDate    = DateTime.Parse(createOrderInput.DeliveryDate),
                OrderStatus     = createOrderInput.OrderStatus,
                Currency        = "R"
            };

            order.OrderDetails = new List <OrderDetail>();
            foreach (var item in createOrderInput.OrderDetails)
            {
                var orderDetail = new OrderDetail();
                orderDetail.ProductID     = item.ProductID;
                orderDetail.ProductName   = item.ProductName;
                orderDetail.UnitPrice     = item.UnitPrice;
                orderDetail.Currency      = item.Currency;
                orderDetail.Quantity      = item.Quantity;
                orderDetail.UnitOfMeasure = item.UnitOfMeasure;
                order.SubTotal           += item.UnitPrice * item.Quantity;
                order.OrderDetails.Add(orderDetail);
            }

            order.Tax   = order.SubTotal * (decimal)0.15;
            order.Total = order.SubTotal + order.Tax;
            db.Orders.Add(order);
            await db.SaveChangesAsync();

            return(order);
        }
コード例 #10
0
        //Add new customer record
        public async Task <Customer> AddCustomer(CreateCustomerInput createCustomerInput)
        {
            Customer _customer = new Customer
            {
                CustomerName    = createCustomerInput.CustomerName,
                PhysicalAddress = createCustomerInput.PhysicalAddress,
                Town            = createCustomerInput.Town,
                PostalCode      = createCustomerInput.PostalCode,
                Province        = createCustomerInput.Province,
                Telephone       = createCustomerInput.Telephone,
                Mobile          = createCustomerInput.Mobile,
                Email           = createCustomerInput.Email
            };
            await db.Customers.AddAsync(_customer);

            await db.SaveChangesAsync();

            return(_customer);
        }
コード例 #11
0
        //Add new product record
        public async Task AddProduct(ProductDTO productDTO)
        {
            //check if product already exists
            Product product = await db.Products.FirstOrDefaultAsync(i => i.ProductName == productDTO.ProductName);

            if (product != null)
            {
                throw new Exception("Product already exists");
            }

            Product _product = new Product
            {
                ProductName   = productDTO.ProductName,
                UnitPrice     = productDTO.UnitPrice,
                UnitOfMeasure = productDTO.UnitOfMeasure,
                Currency      = productDTO.Currency
            };
            await db.Products.AddAsync(_product);

            await db.SaveChangesAsync();
        }
コード例 #12
0
        public virtual async Task Update(T item)
        {
            switch (item)
            {
            case DAContractModels.Location _:
            {
                _context.Locations.Update(_mapper.Map <DABaseModels.Location>(item));
                break;
            }

            case DAContractModels.Service _:
            {
                _context.Services.Update(_mapper.Map <DABaseModels.Service>(item));
                break;
            }

            case DAContractModels.Metric _:
            {
                _context.Metrics.Update(_mapper.Map <DABaseModels.Metric>(item));
                break;
            }

            case DAContractModels.Formula _:
            {
                _context.Formulas.Update(_mapper.Map <DABaseModels.Formula>(item));
                break;
            }

            case DAContractModels.Statistic _:
            {
                _context.Statistics.Update(_mapper.Map <DABaseModels.Statistic>(item));
                break;
            }

            default:
                return;
            }

            await _context.SaveChangesAsync().ConfigureAwait(false);
        }
コード例 #13
0
        public async Task CreateAsync(AuthenticationTokenCreateContext tokenContext)
        {
            string clientName = tokenContext.Ticket.Properties.Dictionary["as:client_id"];

            if (clientName == null)
            {
                return;
            }

            Guid clientid = _context.AuthClients.First(client => client.Name == clientName).Id;

            var refreshTokenId = Guid.NewGuid();

            var refreshTokenLifeTime = tokenContext.OwinContext.Get <int>("as:clientRefreshTokenLifeTime");

            var issuedUtc  = DateTime.UtcNow;
            var expiresUtc = DateTime.UtcNow.AddMinutes(refreshTokenLifeTime);

            var token = new RefreshToken()
            {
                Id         = refreshTokenId,
                ClientId   = clientid,
                Subject    = tokenContext.Ticket.Identity.Name,
                IssuedUtc  = issuedUtc.ToString(),
                ExpiresUtc = expiresUtc.ToString()
            };

            tokenContext.Ticket.Properties.ExpiresUtc = expiresUtc;

            token.ProtectedTicket = tokenContext.SerializeTicket();

            _context.RefreshTokens.Add(token);

            var result = await _context.SaveChangesAsync();

            if (result != 0)
            {
                tokenContext.SetToken(refreshTokenId.ToString());
            }
        }
コード例 #14
0
ファイル: DataContext.cs プロジェクト: war-man/APPartment
        public async Task SaveAsync(T objectModel, long userId, long houseId, long?targetObjectId)
        {
            var objectTypeName = objectModel.GetType().Name;
            var objectTypeId   = context.Set <ObjectType>().Where(x => x.Name == objectTypeName).FirstOrDefault().Id;

            var _object = new APPartment.Models.Object()
            {
                CreatedById  = userId,
                ModifiedById = userId,
                CreatedDate  = DateTime.Now,
                ModifiedDate = DateTime.Now,
                ObjectTypeId = objectTypeId
            };

            await context.AddAsync(_object);

            await context.SaveChangesAsync();

            objectModel.ObjectId = _object.ObjectId;

            await this.SaveChangesAsync(true, houseId, userId, targetObjectId, _object.ObjectId, objectModel, ContextExecutionTypes.Create);
        }
コード例 #15
0
        //Add new product record
        public async Task <Product> AddProduct(CreateProductInput createProductInput)
        {
            //check if product already exists
            Product product = await db.Products.FirstOrDefaultAsync(i => i.ProductName == createProductInput.ProductName);

            if (product != null)
            {
                throw new Exception("Product already exists");
            }

            Product _product = new Product
            {
                ProductName   = createProductInput.ProductName,
                UnitPrice     = createProductInput.UnitPrice,
                UnitOfMeasure = createProductInput.UnitOfMeasure,
                Currency      = createProductInput.Currency
            };
            await db.Products.AddAsync(_product);

            await db.SaveChangesAsync();

            return(product);
        }
コード例 #16
0
        public async void UpdateDatabase()
        {
            var result = new ValuesModel();

            foreach (var item in MicrocontrollerMap.IpMapId)
            {
                string url = item.Value;
                int    id  = item.Key;
                if (!String.IsNullOrEmpty(url))
                {
                    result.MicrocontrollerID = id;
                    result.Temperature       = GetTemperature(url);
                    result.DoorOpen          = GetDoorOpen(url);
                    result.Dust     = GetDust(url);
                    result.DateTime = DateTime.Now;
                    result.Humidity = GetHumidity(url);
                    result.Power    = GetPower(url);
                    _context.Add(result);
                    await _context.SaveChangesAsync();
                }
            }
        }
コード例 #17
0
        /// <summary>
        /// Creates the database if it does not exist
        /// Seeds data into the database if the database the database does not contain required data for startup
        /// The data is seeded from a json file and converted to the C# objectusing the newton.Json nuget package
        /// </summary>
        /// <param name="context"></param>
        /// <param name="roleManager"></param>
        /// <param name="userManager"></param>

        /// <returns></returns>

        public static async Task Preseeder(DataAccessContext context, RoleManager <IdentityRole> roleManager, UserManager <BlogUser> userManager)
        {
            try
            {
                List <string> list = new List <string>();

                context.Database.EnsureCreated();

                //Checks if there is data in the roles table and seeds data into it, if empty.
                if (!roleManager.Roles.Any())
                {
                    List <string> roles = new List <string> {
                        "Admin", "ProEditor", "Editor", "Member"
                    };
                    foreach (var item in roles)
                    {
                        var role = new IdentityRole(item);
                        await roleManager.CreateAsync(role);
                    }
                }

                //Checks if there is data in the BlogUser table and seeds data into it, if empty.
                if (!userManager.Users.Any())
                {
                    int    count = 0;
                    string DataConvertedToString = File.ReadAllText("../BLOGIT.DataAccess/DataSeeding/UserSeed.json");
                    var    blogUsers             = JsonConvert.DeserializeObject <List <BlogUser> >(DataConvertedToString);
                    foreach (var user in blogUsers)
                    {
                        if (count == 0)
                        {
                            var result = await userManager.CreateAsync(user, "admin");

                            if (!result.Succeeded)
                            {
                                throw new Exception("Error");
                            }
                            await userManager.AddToRoleAsync(user, "Admin");

                            list.Add(user.Id);
                        }
                        if (count == 1)
                        {
                            var result = await userManager.CreateAsync(user, "proeditor");

                            if (!result.Succeeded)
                            {
                                throw new Exception("Error");
                            }
                            await userManager.AddToRoleAsync(user, "ProEditor");

                            list.Add(user.Id);
                        }
                        if (count == 2)
                        {
                            var result = await userManager.CreateAsync(user, "member");

                            if (!result.Succeeded)
                            {
                                throw new Exception("Error");
                            }
                            await userManager.AddToRoleAsync(user, "Member");

                            list.Add(user.Id);
                        }
                        if (count == 3)
                        {
                            var result = await userManager.CreateAsync(user, "proeditor");

                            if (!result.Succeeded)
                            {
                                throw new Exception("Error");
                            }
                            await userManager.AddToRoleAsync(user, "ProEditor");
                        }
                        count++;
                    }
                }


                //Checks if there is data in the Categories table and seeds data into it, If empty.
                if (!context.Categories.Any())
                {
                    string DataConvertedToString = File.ReadAllText("../BLOGIT.DataAccess/DataSeeding/Category.json");
                    var    categories            = JsonConvert.DeserializeObject <List <Category> >(DataConvertedToString);
                    foreach (var item in categories)
                    {
                        context.Categories.Add(item);
                    }
                    await context.SaveChangesAsync();
                }

                //Checks if there is data in the Post table
                if (!context.Post.Any())
                {
                    List <string> catergories = new List <string> {
                        "Religion", "General", "LifeStyle", "Technology", "Architecture", "Adventure"
                    };
                    int    count  = 0;
                    int    count2 = 0;
                    string DataConvertedToString = File.ReadAllText("../BLOGIT.DataAccess/DataSeeding/PostSeed.json");
                    var    subPosts = JsonConvert.DeserializeObject <List <Post> >(DataConvertedToString);
                    foreach (var item in subPosts)
                    {
                        Post post = new Post
                        {
                            PostTitle     = item.PostTitle,
                            PostDetails   = item.PostDetails,
                            PostCreator   = context.BlogUser.FirstOrDefault(user => user.Id == list[count]),
                            ApprovalState = true
                        };
                        post.PostCategories = new List <PostCategories>
                        {
                            new PostCategories {
                                Category   = context.Categories.FirstOrDefault(Category => Category.CategoryName == catergories[count2]),
                                CategoryId = context.Categories.FirstOrDefault(Category => Category.CategoryName == catergories[count2]).CategoryId, PostId = post.PostId, Post = post
                            },
                            new PostCategories {
                                Category   = context.Categories.FirstOrDefault(Category => Category.CategoryName == catergories[count2 + 1]),
                                CategoryId = context.Categories.FirstOrDefault(Category => Category.CategoryName == catergories[count2 + 1]).CategoryId, PostId = post.PostId, Post = post
                            }
                        };
                        count++;
                        count2 += 2;

                        context.Post.Add(post);
                    }
                    await context.SaveChangesAsync();
                }
            }
            catch (Exception)
            {
            }
        }
コード例 #18
0
ファイル: LikeService.cs プロジェクト: lexTutor/BLOGITWebApp
        /// <summary>
        /// Sends an instance of a liked post to the database
        /// </summary>
        /// <param name="like"></param>
        /// <returns></returns>
        public async Task <bool> LikePost(Likes like)
        {
            await _ctx.AddAsync(like);

            return(await _ctx.SaveChangesAsync() > 0);
        }
コード例 #19
0
 /// <summary>
 /// sends an instance of a comment on a post to the database
 /// </summary>
 /// <param name="commment"></param>
 /// <returns></returns>
 public async Task <bool> AddComment(Comments commment)
 {
     _ctx.Comments.Add(commment);
     return(await _ctx.SaveChangesAsync() > 0);
 }
コード例 #20
0
        public virtual async Task Create(T item)
        {
            await _dbSet.AddAsync(item).ConfigureAwait(false);

            await _context.SaveChangesAsync().ConfigureAwait(false);
        }