コード例 #1
0
        public async Task <Response> Depositar(Cuenta oCuenta, float monto, int Estado)
        {
            try
            {
                Transaccion oTransaccion = new Transaccion
                {
                    Accion       = "Deposito",
                    Fecha        = DateTime.Now,
                    Monto        = monto,
                    NuevoSaldo   = oCuenta.Saldo + monto,
                    NumeroCuenta = oCuenta.NumeroCuenta
                };
                Usuario user  = db.Usuario.FirstOrDefault(x => x.id_Usuario.Equals(oCuenta.Usuario.id_Usuario));
                var     index = user.Cuenta.ToList().FindIndex(x => x.id_Cuenta.Equals(oCuenta.id_Cuenta));
                user.Cuenta.ToList()[index].Saldo += monto;
                user.Cuenta.ToList()[index].Activo = Estado;
                user.Transaccion.Add(oTransaccion);
                db.Entry(user).State = System.Data.Entity.EntityState.Modified;
                var resp = await db.SaveChangesAsync();

                if (resp > 0)
                {
                    return(new Response
                    {
                        IsSuccess = true,
                        Message = "El deposito ha sido satisfactorio",
                        Result = user
                    });
                }
                else
                {
                    return(new Response
                    {
                        IsSuccess = false,
                        Message = "No se pudo almacenar en la db"
                    });
                }
            }
            catch (Exception ex)
            {
                return(new Response
                {
                    IsSuccess = false,
                    Message = ex.Message
                });
            }
        }
コード例 #2
0
        private async Task Update()
        {
            using (var context = new Model1())
            {
                var per = context.Person.FirstOrDefault(person => person.Login.Equals(LoginTextBox.Text));
                per.FirstName  = FirstNameTextBox.Text;
                per.SecondName = SecondNameTextBox.Text;
                per.LastName   = LastNameTextBox.Text;
                per.Login      = LoginTextBox.Text;
                per.Password   = PasswordTextBox.Text;
                await context.SaveChangesAsync();

                var manager = context.Manager.FirstOrDefault(man => man.IdPerson.Equals(per.Id));
                manager.CoefficientId = Int32.Parse(CoefficientComboBox.Text);
                manager.SalaryId      = Int32.Parse(SalaryComboBox.Text);
                await context.SaveChangesAsync();
            }
        }
コード例 #3
0
ファイル: ClassAttendance.cs プロジェクト: Frankofoedu/SPK
        private void btnSave_ClickEvent(object sender, EventArgs e)
        {
            var AttendanceList = new List <student_attendance>();

            if (string.IsNullOrWhiteSpace(cBoxSession.Text) && string.IsNullOrWhiteSpace(cBoxTerm.Text))
            {
                MessageBox.Show("Please select Session and Term first.", "An Error Occured.");
                return;
            }
            if (dGridClassMembers.Rows.Count < 1)
            {
                MessageBox.Show("No Students Loaded. \n Make sure there are students in the selected class.", "An Error Occured.");
                return;
            }

            var r = MessageBox.Show("Make sure you have selected the attendance status for the displayed students. \n Click 'OK' to proceed.",
                                    "Save Attendance?", MessageBoxButtons.OKCancel);

            Cursor = Cursors.WaitCursor;

            if (r != DialogResult.OK)
            {
                return;
            }

            foreach (DataGridViewRow row in dGridClassMembers.Rows)
            {
                var attendance = new student_attendance()
                {
                    date       = dtpDate.Text,
                    name       = (string)row.Cells[1].Value,
                    reg_number = (string)row.Cells[0].Value,
                    roll_call  = (string)row.Cells[3].Value,
                    session    = cBoxSession.Text,
                    term       = cBoxTerm.Text,
                    _class     = (string)row.Cells[2].Value,
                };

                AttendanceList.Add(attendance);
            }

            using (var db = new Model1())
            {
                db.student_attendance.AddRange(AttendanceList);
                db.SaveChangesAsync();
            }

            MessageBox.Show("Saved Successfully.");

            Students = new List <student>();
            dGridClassMembers.DataSource = Students;

            Cursor = Cursors.Arrow;
        }
コード例 #4
0
        public static async Task CreateEntity(AuctionEditVM editVM, Auction auction, object userId, HttpPostedFileBase upload)
        {
            Image   image   = CreateImageEntity(editVM, upload);
            Product product = CreateProductEntity(editVM, image);

            var client = db.Clients.Where(c => c.AccountId == (int)userId).FirstOrDefault();

            CreateAuctionEntity(editVM, auction, product, client);
            CreateBetAuctionEntity(editVM, auction, client);
            await db.SaveChangesAsync();
        }
コード例 #5
0
        //[ValidateAntiForgeryToken] //не приним. JsonRequest??????
        public async Task <ActionResult> Create(BetAuction betAuction, JsonRequestCreateBet data)
        {
            if (ModelState.IsValid && betAuction.AuctionId != 0)
            {
                db.BetAuction.Add(betAuction);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            else        //возвр. Json в Details.html
            {
                string  messageError = "";
                int     auctionId    = int.Parse(data.AuctionId);
                int     clientId     = int.Parse(data.ClientId);
                decimal bet          = decimal.Parse(data.Bet);
                try {
                    var myBetAuction = new BetAuction {
                        AuctionId = auctionId, ClientId = clientId, Bet = bet
                    };
                    var repeatBet = await db.BetAuction.FirstOrDefaultAsync(b => b.AuctionId == auctionId && b.ClientId == clientId && b.Bet == bet);

                    if (repeatBet != null)
                    {
                        messageError = "Такая ставка уже есть. Попробуйте снова!";
                        return(new JsonResult {
                            Data = messageError, JsonRequestBehavior = JsonRequestBehavior.DenyGet
                        });
                    }
                    db.BetAuction.Add(myBetAuction);
                    await db.SaveChangesAsync();

                    messageError = "Ставка сделана. Данные добавлены!";
                }
                catch (Exception e) {
                    messageError = "Произошла ошибка. Данные не были добавлены!";
                }
                return(new JsonResult {
                    Data = messageError, JsonRequestBehavior = JsonRequestBehavior.DenyGet
                });
            }
        }
コード例 #6
0
        public async Task <ActionResult> Create(Account account)
        {
            if (ModelState.IsValid)
            {
                db.Account.Add(account);

                //получить данные по роли и юзеру
                int accountId = (int)db.Account.AsEnumerable().Last().Id;
                int roleId    = db.Roles.FirstOrDefault(r => r.RoleName.Equals("member")).Id; //11
                db.RoleAccountLinks.Add(new RoleAccountLink {
                    RoleId = roleId, AccountId = accountId
                });                                                                                      //12- переприсваивается???!
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            else
            {
                return(View());
            }
        }
コード例 #7
0
 private async Task delete()
 {
     using (var context = new Model1())
     {
         Int32 idperson = Int32.Parse(textBox1.Text);
         var   manager  = context.Manager.FirstOrDefault(man => man.IdPerson == idperson);
         var   per      = context.Person.FirstOrDefault(person => person.Id == idperson);
         context.Manager.Remove(manager);
         context.Person.Remove(per);
         await context.SaveChangesAsync();
     }
 }
コード例 #8
0
        public async Task <bool> Delete(int id)
        {
            var emp = context.departments.FirstOrDefault(e => e.Id == id);

            if (emp != null)
            {
                context.departments.Remove(emp);
                await context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
コード例 #9
0
        private async Task Add()
        {
            using (var context = new Model1())
            {
                context.Person.Add(new Person
                {
                    FirstName  = FirstNameTextBox.Text,
                    SecondName = SecondNameTextBox.Text,
                    LastName   = LastNameTextBox.Text,
                    Login      = LoginTextBox.Text,
                    Password   = PasswordTextBox.Text
                });
                await context.SaveChangesAsync();

                context.Manager.Add(new Manager
                {
                    IdPerson      = context.Person.Last().Id,
                    CoefficientId = Int32.Parse(CoefficientComboBox.Text),
                    SalaryId      = Int32.Parse(SalaryComboBox.Text)
                });
                await context.SaveChangesAsync();
            }
        }
コード例 #10
0
        private async void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkExistId(tbId.Text))
                {
                    MessageBox.Show(DefineMessage.ID_INVALID, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                if (!validateInputEntered())
                {
                    MessageBox.Show(DefineMessage.INVALID_DATA, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                // Tạo product mới
                PRODUCT product = new PRODUCT();
                product.ID = tbId.Text;
                if (pbAvatar.Image != null)
                {
                    product.IMAGES = product.ID + avatarExtention;
                }
                product.MNAME        = tbName.Text;
                product.CATEGORY     = cbbCategory.SelectedItem.ToString();
                product.MANUFACTURER = tbManufactor.Text;
                product.NUMBER       = int.Parse(tbNumber.Text);
                product.PRICE        = int.Parse(tbPrice.Text);
                product.DESCRIPTIONS = tbDescription.Text;
                product.STATUSS      = 1;

                // Upload file ảnh avatar vào hệ thống
                if (avatarPath != "")
                {
                    File.Copy(avatarPath, CommonFunction.getProductImagePath() + product.IMAGES, true);
                }


                // Insert vào database
                db.PRODUCTs.Add(product);
                await db.SaveChangesAsync();

                // Thông báo thành công
                MessageBox.Show(DefineMessage.ADD_RECORD_SUCCESSFUL, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
                FmProduct fmProduct = new FmProduct();
                fmProduct.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show(DefineMessage.ERROR_OCCURED, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
コード例 #11
0
        // PUT: odata/KazakhBests(5)
        public async Task <IHttpActionResult> Put([FromODataUri] int key, Delta <KazakhBest> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            KazakhBest kazakhBest = await db.KazakhBests.FindAsync(key);

            if (kazakhBest == null)
            {
                return(NotFound());
            }

            patch.Put(kazakhBest);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!KazakhBestExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(kazakhBest));
        }
コード例 #12
0
        static void Main(string[] args)
        {
            using (var channel = MqHelper.GetConnection().CreateModel())
            {
                channel.QueueDeclare("NET", true, false, false, null);

                var consumber = new EventingBasicConsumer(channel);
                channel.BasicQos(0, 1, false);


                consumber.Received += (sender, e) =>
                {
                    try
                    {
                        var user = JsonConvert.DeserializeObject <User>(Encoding.UTF8.GetString(e.Body));
                        var flag = RedisHelper.GetRedisClient().Incr(user.Id.ToString());
                        if (flag == 1)
                        {
                            //用户的第一次请求,为有效请求
                            //下面开始入库,这里使用List做为模拟
                            Console.WriteLine($"{user.Id}标识为{flag} {user.Name}");
                            var dbContext = new Model1();
                            dbContext.Person.Add(new Person()
                            {
                                Id2 = user.Id.ToString(), Name = user.Name
                            });
                            Task ts = dbContext.SaveChangesAsync();
                            ts.Wait();
                            //添加入库标识
                            RedisHelper.GetRedisClient().Incr($"{user.Id.ToString()}入库");

                            Console.WriteLine("入库成功");
                        }

                        //用户的N次请求,为无效请求
                        channel.BasicAck(e.DeliveryTag, false);
                    }
                    catch (Exception ex)
                    {
                        File.AppendAllText($"{System.AppDomain.CurrentDomain.BaseDirectory}/bin/log.txt", ex.Message);
                    }
                };
                Console.WriteLine("开始工作");

                channel.BasicConsume("NET", false, consumber);
                Console.ReadKey();
            }
        }
コード例 #13
0
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var result = MessageBox.Show(DefineMessage.CONFIRM_DELETE_RECORD, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                ORDER order = db.ORDERS.Where(o => o.ID == Oid).FirstOrDefault();

                db.ORDERS.Remove(order);
                await db.SaveChangesAsync();

                MessageBox.Show(DefineMessage.DELETE_RECORD_SUCCESSFUL, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                FmSale fmSale = new FmSale();
                fmSale.Show();
                this.Close();
            }
        }
コード例 #14
0
        private async void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                var result = MessageBox.Show(DefineMessage.CONFIRM_EDIT, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    // Tạo product mới
                    PRODUCT product = db.PRODUCTs.Where(p => p.ID.Equals(this.product.ID)).FirstOrDefault();

                    product.MNAME        = tbName.Text;
                    product.CATEGORY     = cbbCategory.SelectedItem.ToString();
                    product.MANUFACTURER = tbManufactor.Text;
                    product.NUMBER       = int.Parse(tbNumber.Text);
                    product.PRICE        = int.Parse(tbPrice.Text);
                    product.DESCRIPTIONS = tbDescription.Text;
                    product.STATUSS      = 1;
                    if (!lbPhotoName.Text.Equals(this.product.ID))
                    {
                        product.IMAGES = product.ID + avatarExtention;
                    }

                    // Upload file ảnh avatar vào hệ thống
                    if (avatarPath != "")
                    {
                        File.Copy(avatarPath, CommonFunction.getProductImagePath() + product.IMAGES, true);
                    }

                    // Insert vào database
                    db.Entry(product).State = System.Data.Entity.EntityState.Modified;
                    await db.SaveChangesAsync();

                    // Thông báo thành công
                    MessageBox.Show(DefineMessage.MODIFY_SUCCESSFUL, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                    FmProduct fmProduct = new FmProduct();
                    fmProduct.Show();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(DefineMessage.ERROR_OCCURED, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
コード例 #15
0
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvList.Rows.Count == 0)
            {
                return;
            }
            var result = MessageBox.Show(DefineMessage.CONFIRM_DELETE_RECORD, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                string username = getSelectedUsername();
                USER   user     = db.USERS.Where(U => U.USERNAME.Equals(username)).FirstOrDefault();

                db.USERS.Remove(user);
                await db.SaveChangesAsync();

                dgvList.Rows.Remove(dgvList.CurrentRow);
                MessageBox.Show(DefineMessage.DELETE_RECORD_SUCCESSFUL, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
コード例 #16
0
ファイル: FmSale.cs プロジェクト: Devyduong/GuitarManagement
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvList.Rows.Count == 0)
            {
                return;
            }
            var result = MessageBox.Show(DefineMessage.CONFIRM_DELETE_RECORD, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                int   id    = int.Parse(getCurrentCode());
                ORDER order = db.ORDERS.Where(o => o.ID == id).FirstOrDefault();

                db.ORDERS.Remove(order);
                await db.SaveChangesAsync();

                dgvList.Rows.Remove(dgvList.CurrentRow);
                MessageBox.Show(DefineMessage.DELETE_RECORD_SUCCESSFUL, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
コード例 #17
0
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                var result = MessageBox.Show(DefineMessage.CONFIRM_DELETE_RECORD, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.Yes)
                {
                    db.PRODUCTs.Remove(product);
                    await db.SaveChangesAsync();

                    MessageBox.Show(DefineMessage.DELETE_RECORD_SUCCESSFUL, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    this.Close();
                    FmProduct fmProduct = new FmProduct();
                    fmProduct.Show();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(DefineMessage.ERROR_OCCURED, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
コード例 #18
0
        private async void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                var result = MessageBox.Show(DefineMessage.CONFIRM_DELETE_RECORD, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (result == DialogResult.Yes)
                {
                    string  currentId = getCurrentIdSelected();
                    PRODUCT product   = db.PRODUCTs.Where(p => p.ID.Equals(currentId)).FirstOrDefault();

                    db.PRODUCTs.Remove(product);
                    await db.SaveChangesAsync();

                    dgvList.Rows.Remove(dgvList.CurrentRow);
                    MessageBox.Show(DefineMessage.DELETE_RECORD_SUCCESSFUL, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                    File.Delete(CommonFunction.getProductImagePath() + product.IMAGES);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(DefineMessage.ERROR_OCCURED, CommonDefines.MESSAGEBOX_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
コード例 #19
0
        private async void Update(object o)
        {
            await _db.SaveChangesAsync();

            MessageBox.Show("Изменении сохранено");
        }
コード例 #20
0
 public Task <int> Save()
 {
     return(_dbContext.SaveChangesAsync());
 }
コード例 #21
0
ファイル: USers.cs プロジェクト: vheckthor/InventoryBilling
        private async void btnAdd_Click(object sender, EventArgs e)
        {
            //create mapper
            Mapper.CreateMap <UserDTO, User>();

            var  users   = new UserDTO();
            bool tracker = false;

            try
            {
                users.FirstName = boxFirstName.Text;
                users.LastName  = boxLastName.Text;
                users.Email     = boxEmail.Text;
                users.Address   = boxAddress.Text;
                users.Contact   = boxContact.Text;
                users.Gender    = comboBoxGender.SelectedItem.ToString();
                users.Password  = boxPassword.Text;
                users.UserName  = boxUsername.Text;
                users.UserType  = comboboxUserType.SelectedItem.ToString();
                users.AddedDate = DateTime.Now;
                users.AddedBy   = userId;

                if
                (
                    String.IsNullOrWhiteSpace(users.FirstName) ||
                    String.IsNullOrWhiteSpace(users.LastName) ||
                    String.IsNullOrWhiteSpace(users.Password) ||
                    String.IsNullOrWhiteSpace(users.UserName) ||
                    String.IsNullOrWhiteSpace(users.Email) ||
                    String.IsNullOrWhiteSpace(users.Address) ||
                    String.IsNullOrWhiteSpace(users.Contact) ||
                    String.IsNullOrWhiteSpace(users.UserType)

                )
                {
                    MessageBox.Show("The input field cannot be empty or whitespaces");
                    return;
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show("One or more errors occured please check your entries and retry");
                return;
            }


            ;
            using (var db = new Model1())
            {
                //mapped entities
                var userStored = Mapper.Map <User>(users);

                db.Users.Add(userStored);

                tracker = await db.SaveChangesAsync() > 0;
            }

            if (tracker)
            {
                MessageBox.Show("User Successfully Created");
                boxContact.Clear();
                boxFirstName.Clear();
                boxLastName.Clear();
                boxEmail.Clear();
                boxAddress.Clear();
                boxPassword.Clear();
                boxUsername.Clear();
            }
            else
            {
                MessageBox.Show("Failed to add new user");
            }
        }