Ejemplo n.º 1
0
        public async Task <bool> AddToWishlist(string username, Guid productId)
        {
            var product = await this.context.Products.FindAsync(productId);

            var user = await this.userManager.FindByNameAsync(username);

            if (product == null || user == null)
            {
                return(false);
            }

            var userProduct = new UserProduct
            {
                User    = user,
                Product = product
            };

            bool alreadyExists = this.context.UsersProducts
                                 .FirstOrDefault(x => x.ProductId == userProduct.Product.Id &&
                                                 x.UserId == userProduct.User.Id) != null;

            if (!alreadyExists)
            {
                user.WishlistedProducts.Add(userProduct);
                await this.context.SaveChangesAsync();
            }

            return(true);
        }
Ejemplo n.º 2
0
        public void TestRemovalOfCompositeKeys_Commit()
        {
            UserProduct retrievedUP = null;

            using (ADOCRUDContext context = new ADOCRUDContext(connectionString))
            {
                UserProduct up = new UserProduct();
                up.UserId    = userId;
                up.ProductId = productId;

                context.Insert <UserProduct>(up);
                context.Commit();
            }

            using (ADOCRUDContext context = new ADOCRUDContext(connectionString))
            {
                // Makes sure user product being retreived exists
                UserProduct up = context.QueryItems <UserProduct>("select * from dbo.UserProduct where UserId = @userId and ProductId = @productId", new { userId = userId, productId = productId }).FirstOrDefault();
                Assert.IsTrue(up != null && up.UserId == userId && up.ProductId == productId);

                context.Remove(up);
                context.Commit();

                retrievedUP = context.QueryItems <UserProduct>("select * from dbo.UserProduct where UserId = @userId and ProductId = @productId", new { userId = userId, productId = productId }).FirstOrDefault();
            }

            Assert.IsTrue(retrievedUP == null, "A problem occurred when trying to remove a composite key");
        }
Ejemplo n.º 3
0
        public static int Update(UserProduct userProduct)
        {
            try
            {
                using (GroceryGetterEntities dc = new GroceryGetterEntities())
                {
                    tblUserProduct tbluserProduct = dc.tblUserProducts.FirstOrDefault(up => up.Id == userProduct.Id);
                    if (tbluserProduct != null)
                    {
                        tbluserProduct.UserId    = userProduct.UserId;
                        tbluserProduct.ProductId = userProduct.ProductId;
                        tbluserProduct.Amount    = userProduct.Amount;
                        tbluserProduct.Notes     = userProduct.Notes;
                        tbluserProduct.InCart    = userProduct.InCart;

                        return(dc.SaveChanges());
                    }
                    else
                    {
                        return(0);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Deletes a user product.
        /// </summary>
        /// <param name="user_product"></param>
        /// <param name="instance_use"></param>
        /// <returns>string</returns>
        public string Delete(UserProduct user_product, string instance_use)
        {
            string result;

            switch (instance_use)
            {
            case "Username":
                result = db_userproduct.DeleteByUsername(user_product.Username);
                break;

            case "Product Id":
                result = db_userproduct.DeleteByProductId(user_product.ProductId);
                break;

            case "Both":
                result = db_userproduct.Delete(user_product);
                break;

            default:
                result = "The chosen instanse to use is invalid.";
                break;
            }

            return(result);
        }
Ejemplo n.º 5
0
        public List <UserProduct> GetUserProduct(string userid, string flag)

        {
            string sql;

            sql = "";
            //Sales Order
            if (flag == "SO" || flag == "OE")
            {
                sql = @"Select distinct item_code = c.item_code, item_description = c.item_description
                       From  app_user_customer a, sales_order b, sales_order_detail c
                       Where a.user_id=:userid
                       and a.customer_code = b.customer_code
                       and a.site_no = b.site_no
                       and b.company_code = c.company_code
                       and b.order_no=c.order_no";
            }

            //Track Delivery
            if (flag == "TD")
            {
                sql = @"Select distinct item_code = c.item_code, item_description = c.item_description
                       From  app_user_customer a, delivery_note b, delivery_note_detail c
                       Where a.user_id=:userid
                       and a.customer_code = b.customer_code
                       and a.site_no = b.site_no
                       and b.company_code = c.company_code
                       and b.dnote_no=c.dnote_no
                       and b.delivery_status='O'";
            }

            //Track Delivery
            if (flag == "DD")
            {
                sql = @"Select distinct item_code = c.item_code, item_description = c.item_description
                       From  app_user_customer a, delivery_note b, delivery_note_detail c
                       Where a.user_id=:userid
                       and a.customer_code = b.customer_code
                       and a.site_no = b.site_no
                       and b.company_code = c.company_code
                       and b.dnote_no=c.dnote_no
                       and b.delivery_status='C'";
            }


            var result = _dataContext.SqlExecutor.Select <DynamicModel>(sql, userid);

            List <UserProduct> det = new List <UserProduct>();


            for (int i = 0; i < result.Count; i++)
            {
                var         data = result[i];
                UserProduct s    = new UserProduct();
                s.Item_Code        = data.GetValue <string>("item_code");
                s.Item_Description = data.GetValue <string>("item_description");
                det.Add(s);
            }
            return(det.ToList());
        }
        public UserProduct AddToCart(UserProduct product)
        {
            try
            {
                using (SqlConnection con = new SqlConnection(GlobalConnection.Editor))
                {
                    var param = new DynamicParameters();
                    param.Add("@userId", product.UserId);
                    param.Add("@productId", product.Product.Id);
                    param.Add("@productQuantity", product.Product.Quantity);
                    param.Add("@productPrice", product.Product.Price.Value);
                    param.Add("@productColor", product.Product.Color[0]);
                    param.Add("@productSize", product.Product.Size[0]);

                    return(con.Query <UserProduct, Product, int, UserProduct>("[RudderStack].[SaveUserProduct]", (user, p, price) => {
                        user.Product = p;
                        user.Product.Price = new Price()
                        {
                            Value = price
                        };
                        return user;
                    }, param, splitOn: "Quantity, Value", commandType: CommandType.StoredProcedure).FirstOrDefault());
                }
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 7
0
        public void Create(UserProduct entity)
        {
            using (var context = new ListItContext())
            {
                var result = context.Set <UserProduct>().Add(entity);

                try
                {
                    context.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException e)
                {
                    StringBuilder builder = new StringBuilder();
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        builder.Append("Entity of type " + eve.Entry.Entity.GetType().Name
                                       + " in state " + eve.Entry.State + " has the following" +
                                       " validation errors:");
                        foreach (var ve in eve.ValidationErrors)
                        {
                            builder.Append("Property: " + ve.PropertyName + ", Error: " + ve.ErrorMessage);
                        }
                    }
                    throw new Exception(builder.ToString());
                }
            }
        }
Ejemplo n.º 8
0
        public void DeleteUserProduct(UserProduct userProduct)
        {
            var entity = context.UserProducts.Single(p => p.id == userProduct.id);

            context.Remove(entity);
            context.SaveChanges();
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,UserId,ProductId")] UserProduct userProduct)
        {
            if (id != userProduct.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userProduct);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserProductExists(userProduct.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["ProductId"] = new SelectList(_context.Products, "Id", "Id", userProduct.ProductId);
            ViewData["UserId"]    = new SelectList(_context.Users, "ID", "ID", userProduct.UserId);
            return(View(userProduct));
        }
        public ActionResult <UserProduct> PostUserProduct(UserProduct userProduct)
        {
            _context.userProducts.Add(userProduct);
            _context.SaveChanges();

            return(Ok());
        }
Ejemplo n.º 11
0
        public void Success_ListAllUserProducts()
        {
            //Arrange
            int                index;
            int                max_index;
            UserProduct        user_product;
            List <UserProduct> user_products;

            //Act
            index     = 1;
            max_index = 51;

            while (index < max_index)
            {
                user_product = new UserProduct
                {
                    ProductId = products[index].Id,
                    Username  = user.Username,
                    IsActive  = false
                };

                db_userproduct.CreateUserProduct(user_product);
                index++;
            }

            user_products = db_userproduct.ListAllUserProducts();


            //Assert
            Assert.IsTrue(user_products.Count >= 50);
        }
Ejemplo n.º 12
0
        public void Success_FindUserProduct()
        {
            //Arrange
            int         index;
            UserProduct user_product;
            UserProduct result;

            //Act
            index = 52;

            user_product = new UserProduct
            {
                ProductId = products[index].Id,
                Username  = user.Username,
                IsActive  = false
            };

            db_userproduct.CreateUserProduct(user_product);

            result = db_userproduct.FindUserProduct(user_product);


            //Assert
            Assert.AreEqual(user_product.Username, result.Username);
        }
Ejemplo n.º 13
0
        public ActionResult Like()
        {
            var Product_Id = Convert.ToInt32(Request["Product_Id"]);
            var Vote       = Convert.ToInt32(Request["Vote"]);

            if (Vote < 1 || Vote > 5)
            {
                throw new Exception();
            }
            var    Url  = (Request["Url"]);
            string path = Url.Substring(0, Url.IndexOf("?"));

            Url = path + "?Id=" + Product_Id;

            var user = db.Users.Include("Role").Where(p => p.Email == User.Identity.Name).FirstOrDefault();

            if (db.UserProducts.Any(p => p.Product.Id == Product_Id && p.User.Id == user.Id && p.Product.IsOnlyForMarketer == false))
            {
                return(Redirect(Url + "&message=2"));
            }

            var Product = db.Products.Include("Category").Where(p => p.IsOnlyForMarketer == false).Where(p => p.Id == Product_Id).FirstOrDefault();

            Product.Like       += Vote;
            Product.TotalVotes += 5;
            var data = new UserProduct();

            data.Product = Product;
            data.User    = user;
            db.UserProducts.Add(data);
            db.SaveChanges();
            return(Redirect(Url + "&message=0"));
        }
Ejemplo n.º 14
0
        public object Like()
        {
            var Product_Id = Convert.ToInt32(HttpContext.Current.Request.Form["Product_Id"]);
            var Vote       = Convert.ToInt32(HttpContext.Current.Request.Form["Vote"]);

            if (Vote < 1 || Vote > 5)
            {
                throw new DbEntityValidationException("خطا در دریافت رای");
            }
            var Token = HttpContext.Current.Request.Form["Api_Token"];
            var user  = db.Users.Include("Role").Where(p => p.Api_Token == Token).FirstOrDefault();

            if (db.UserProducts.Any(p => p.Product.Id == Product_Id && p.User.Id == user.Id))
            {
                return(new {
                    Message = 1
                });
            }

            var Product = db.Products.Include("Category").Where(p => p.IsOnlyForMarketer == false).Where(p => p.Id == Product_Id).FirstOrDefault();

            Product.Like       += Vote;
            Product.TotalVotes += 5;
            var data = new UserProduct();

            data.Product = Product;
            data.User    = user;
            db.UserProducts.Add(data);
            db.SaveChanges();
            return(new { Message = 0 });
        }
Ejemplo n.º 15
0
        public void Update(UserProduct entity)
        {
            using (var context = new ListItContext())
            {
                context.Set <UserProduct>().Attach(entity);
                context.Entry(entity).State = EntityState.Modified;

                bool saveFailed;

                do
                {
                    saveFailed = false;

                    try
                    {
                        context.SaveChanges();
                    }
                    catch (System.Data.Entity.Infrastructure.DbUpdateConcurrencyException e)
                    {
                        saveFailed = true;
                        e.Entries.Single().Reload();
                        //throw new KeyNotFoundException(e.Message, e.InnerException);
                    }
                } while (saveFailed);
            }
        }
Ejemplo n.º 16
0
        public int AddProduct(Product product, string UserId)
        {
            UserProduct userproduct = null;

            try
            {
                //Adding into Product Table
                product = this.StoreDBContext.Products.Add(product);
                this.StoreDBContext.SaveChanges();

                if (product.ProductId > 0)
                {
                    userproduct           = new UserProduct();
                    userproduct.ProductId = product.ProductId;
                    userproduct.UserId    = UserId;

                    //Adding into UserProduct Table
                    userproduct = StoreDBContext.UserProducts.Add(userproduct);
                    StoreDBContext.SaveChanges();
                }

                return(userproduct.UserProductId);
            }
            catch (DbEntityValidationException ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Finds a user products by their username and productId.
        /// </summary>
        /// <param name="user_product"></param>
        /// <returns>UserProduct</returns>
        public UserProduct FindUserProduct(UserProduct user_product)
        {
            UserProduct result;

            try
            {
                using (var connection = new SqlConnection(db.GetConnectionString()))
                    using (var cmd = connection.CreateCommand())
                    {
                        connection.Open();
                        cmd.CommandText = "SELECT * FROM Table_UserProduct WHERE username = @username AND productId = @productId";
                        cmd.Parameters.AddWithValue("username", user_product.Username);
                        cmd.Parameters.AddWithValue("productId", user_product.ProductId);

                        var reader = cmd.ExecuteReader();
                        reader.Read();
                        result = new UserProduct
                        {
                            ProductId = reader.GetInt32(reader.GetOrdinal("productId")),
                            Username  = reader.GetString(reader.GetOrdinal("username")),
                            IsActive  = reader.GetBoolean(reader.GetOrdinal("isActive"))
                        };

                        connection.Close();
                    }
            }

            catch (Exception exception)
            {
                result = UserProductException(exception);
            }

            return(result);
        }
Ejemplo n.º 18
0
        public ActionResult UpdateUP(int uid, int pid, int tcount, int fcount)
        {
            var up = ur.GetProductByUser(pid, uid);

            if (up != null)
            {
                up.TotalCount  = tcount;
                up.FrozenCount = fcount;
                up.UpdateTime  = DateTime.Now;
                ur.UpdateUserProduct(up);
            }
            else
            {
                up = new UserProduct
                {
                    UserId      = uid,
                    TotalCount  = tcount,
                    FrozenCount = fcount,
                    ProductId   = pid,
                    CreateTime  = DateTime.Now,
                    UpdateTime  = DateTime.Now
                };
                ur.CreateUserProduct(up);
            }
            return(Content("1"));
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Updates a user product in the database.
        /// </summary>
        /// <param name="old_user_product"></param>
        /// <param name="new_user_product"></param>
        /// <returns>string</returns>
        public string UpdateUserProduct(UserProduct old_user_product, UserProduct new_user_product)
        {
            string result;

            try
            {
                using (var connection = new SqlConnection(db.GetConnectionString()))
                    using (var cmd = connection.CreateCommand())
                    {
                        connection.Open();
                        cmd.CommandText = "UPDATE Table_UserProduct SET username = @new_username, productId = @new_productId, isActive = @new_isActive WHERE username = @old_username AND productId = @old_productId";
                        cmd.Parameters.AddWithValue("old_productId", old_user_product.ProductId);
                        cmd.Parameters.AddWithValue("old_username", old_user_product.Username);
                        cmd.Parameters.AddWithValue("new_productId", new_user_product.ProductId);
                        cmd.Parameters.AddWithValue("new_username", new_user_product.Username);
                        cmd.Parameters.AddWithValue("new_isActive", new_user_product.IsActive);
                        cmd.ExecuteNonQuery();
                        connection.Close();
                    }

                result = "Success";
            }

            catch (Exception exception)
            {
                result = UserProductException(exception).Username;
            }

            return(result);
        }
        public async Task <IActionResult> PutUserProduct(int id, UserProduct userProduct)
        {
            if (id != userProduct.piece_id)
            {
                return(BadRequest());
            }

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

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

            return(NoContent());
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Deletes a user product by its username and product_id.
        /// </summary>
        /// <param name="product_id"></param>
        /// <returns>string</returns>
        public string Delete(UserProduct user_product)
        {
            string result;

            try
            {
                using (var connection = new SqlConnection(db.GetConnectionString()))
                    using (var cmd = connection.CreateCommand())
                    {
                        connection.Open();
                        cmd.CommandText = "DELETE FROM Table_UserProduct WHERE username = @username AND productId = @productId";
                        cmd.Parameters.AddWithValue("username", user_product.Username);
                        cmd.Parameters.AddWithValue("productId", user_product.ProductId);
                        cmd.ExecuteNonQuery();
                        connection.Close();
                    }

                result = "Success";
            }

            catch (Exception exception)
            {
                result = UserProductException(exception).Username;
            }

            return(result);
        }
Ejemplo n.º 22
0
 public static UserProduct LoadById(Guid id)
 {
     using (GroceryGetterEntities dc = new GroceryGetterEntities())
     {
         tblUserProduct exsitingRow = dc.tblUserProducts.FirstOrDefault(u => u.Id == id);
         if (exsitingRow != null)
         {
             UserProduct uProduct = new UserProduct
             {
                 Id           = exsitingRow.Id,
                 UserId       = exsitingRow.UserId,
                 ProductId    = exsitingRow.ProductId,
                 ProductTitle = exsitingRow.tblProduct.Title,
                 InCart       = exsitingRow.InCart,
                 Amount       = exsitingRow.Amount,
                 Notes        = exsitingRow.Notes,
                 //ProductAisle = exsitingRow.tblAisleProduct.Aisle
             };
             return(uProduct);
         }
         else
         {
             throw new Exception("Row was not found.");
         }
     }
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Creates a user product in the database.
        /// </summary>
        /// <param name="user_product"></param>
        /// <returns>string</returns>
        public string CreateUserProduct(UserProduct user_product)
        {
            string result;

            try
            {
                using (var connection = new SqlConnection(db.GetConnectionString()))
                    using (var cmd = connection.CreateCommand())
                    {
                        connection.Open();
                        cmd.CommandText = "INSERT INTO Table_UserProduct (username, productId, isActive) VALUES(@username, @productId, @isActive)";
                        cmd.Parameters.AddWithValue("username", user_product.Username);
                        cmd.Parameters.AddWithValue("productId", user_product.ProductId);
                        cmd.Parameters.AddWithValue("isActive", user_product.IsActive);
                        cmd.ExecuteNonQuery();
                        connection.Close();

                        result = "Success";
                    }
            }

            catch (Exception exception)
            {
                result = UserProductException(exception).Username;
            }

            return(result);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// finds a list of user products by username, productId or both.
        /// </summary>
        /// <param name="user_product"></param>
        /// <param name="instance_use"></param>
        /// <returns>List<UserProduct></returns>
        public List <UserProduct> Find(UserProduct user_product, string instance_use)
        {
            List <UserProduct> result;

            switch (instance_use)
            {
            case "Username":
                result = db_userproduct.FindUserProductByUsername(user_product.Username);
                break;

            case "Product Id":
                result = db_userproduct.FindUserProductByProductId(user_product.ProductId);
                break;

            case "Both":
                result = new List <UserProduct>();
                result.Add(db_userproduct.FindUserProduct(user_product));
                break;

            default:
                result = new List <UserProduct>();
                break;
            }

            return(result);
        }
Ejemplo n.º 25
0
 public Product(UserProduct product)
 {
     Id          = product.id;
     Name        = product.name;
     Cost        = product.cost;
     Description = product.description;
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Ships all orders connected to a given user that isn't shipped.
        /// </summary>
        /// <param name="username"></param>
        public void ShipOrders(string username)
        {
            int   index;
            Order order;
            List <OrderDetail> order_details;
            List <Order>       orders;

            //Find orders connected to the given username
            orders = ctr_order.FindByUsername(username);

            index = 0;
            //sort all orders from the list that already is shipped
            while (index < orders.Count)
            {
                order = orders[index];

                if (order.IsShipped)
                {
                    orders.Remove(order);
                }

                else
                {
                    index++;
                }
            }

            //ships the unshipped orders to the user.
            foreach (Order current_order in orders)
            {
                OrderDetail temp_od = new OrderDetail
                {
                    OrderId = current_order.Id
                };

                order_details = ctr_orderdetail.Find(temp_od, "Order Id");

                foreach (OrderDetail order_detail in order_details)
                {
                    UserProduct user_product = new UserProduct
                    {
                        Username  = username,
                        ProductId = order_detail.ProductId,
                        IsActive  = false
                    };

                    Console.WriteLine("Create User Product: " + ctr_userproduct.Create(user_product));
                }

                //mark the order as shipped.
                current_order.IsShipped = true;
                Console.WriteLine("Update Order: " + ctr_order.Update(current_order));

                //Updates the wallet of the user.
                CustomUser user = ctr_user.FindByUsername(current_order.Username);
                user.Wallet -= current_order.Price;
                Console.WriteLine("Update User wallet: " + ctr_user.Update(user));
            }
        }
Ejemplo n.º 27
0
        public bool Update(int id, int userId, int productId)
        {
            var userProduct = new UserProduct {
                Id = id, UserId = userId, ProductId = productId
            };

            return(_userProductService.Update(userProduct));
        }
Ejemplo n.º 28
0
        public bool Delete(int id)
        {
            var userProduct = new UserProduct {
                Id = id
            };

            return(_userProductService.Delete(userProduct));
        }
Ejemplo n.º 29
0
        public int Delete(UserProduct entity)
        {
            var sqlCommand = string.Format(@"DELETE FROM [UserProduct] WHERE [Id] = @Id");

            return(this._db.Execute(sqlCommand, new
            {
                entity.Id
            }));
        }
Ejemplo n.º 30
0
        // GET
        public ActionResult Edit(Guid id)
        {
            //var user = Session["user"] as User;
            UserProduct userProduct = UserProductManager.LoadById(id);

            //UserProduct userProduct = UserProductManager.SearchGroceryByProduct(user.Id, product.Title);

            return(View(userProduct));
        }
Ejemplo n.º 31
0
        public bool AddUsersOwnProduct(int userId, string productName, int productType, double productProteins, double productCarbohydrates, double productFat, double productCalories)
        {
            if (!Verify(userId))
            {
                throw new SoapException("Nie rozpoznano użytkownika.", SoapException.ClientFaultCode);
            }
            else
            {
                try
                {
                    using (var dB = new DailyServerContext())
                    {
                        var newUsersProduct = new UserProduct()
                        {
                            PName = productName,
                            ProductCategoryPCategoryId = 12, //productCategory,
                            ProductTypePTypeId = productType,
                            Proteins = productProteins,
                            Carbohydrates = productCarbohydrates,
                            Fat = productFat,
                            Calories = productCalories,
                            UserUserId = userId
                        };
                        dB.UserProductSet.Add(newUsersProduct);
                        dB.SaveChanges();
                    }
                    return true;
                }
                catch (Exception)
                {

                    return false;
                }
            }
        }
Ejemplo n.º 32
0
 public UserProductViewModel(UserProduct product)
 {
     this.product = product;
     this.UsedByUser = product.UsedByUser;
 }