Exemplo n.º 1
0
        //add new product information to the DB
        private static void NewProduct(string prodName, TravelExpertsDataContext dbContext)
        {
            Product newItem = new Product();

            newItem.ProdName = prodName;
            dbContext.Products.InsertOnSubmit(newItem);
        }
        /// <summary>
        /// set up editing a new record -- shared between New and Reset buttons
        /// </summary>
        private void PrepareNew()
        {
            //start with a blank slate
            lbAssigned.Items.Clear();
            lbAvail.Items.Clear();
            txtSuppID.Text   = "";
            txtSuppName.Text = "";

            using (TravelExpertsDataContext db = new TravelExpertsDataContext()) //get the DB object
            {
                // populate available products list with all products first
                List <Product> availProducts = (from p in db.Products select p).ToList();

                foreach (Product p in availProducts)
                {
                    lbAvail.Items.Add(p);   // add the available products to the available list
                }

                int?maxID = (from s in db.Suppliers select s.SupplierId).Max(); // find the highest supplier ID
                txtSuppID.Text = (maxID + 1).ToString();                        // populate the supplier ID text box with that ID plus one
            }

            //activate the supplier ID field for entry
            txtSuppID.Enabled = true;
            txtSuppName.Focus(); // give the supplier name focus
        }
Exemplo n.º 3
0
        /// <summary>
        /// this method initializes the dataGridView, sets and formats columns
        /// and other options
        /// </summary>
        public void LoadDGV()
        {
            // setup DataAccess
            TravelExpertsDataContext dbContext = new TravelExpertsDataContext();

            // set the data source to the Packages table
            dataGridView1.DataSource = dbContext.Packages;
            // select full row instead of a single cell
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            // don't allow more than one row to be selected
            dataGridView1.MultiSelect = false;
            //do not allow inline editing
            dataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically;
            //remove blank row at the bottom
            dataGridView1.AllowUserToAddRows = false;
            //Prevent user from removing rows in the display
            dataGridView1.AllowUserToDeleteRows = false;
            // set column names and display format
            dataGridView1.Columns[0].HeaderText = "Package ID";
            dataGridView1.Columns[1].HeaderText = "Package Name";
            dataGridView1.Columns[2].HeaderText = "Start Date";
            dataGridView1.Columns[3].HeaderText = "End Date";
            dataGridView1.Columns[4].HeaderText = "Description";
            dataGridView1.Columns[5].HeaderText = "Base Price";
            dataGridView1.Columns[6].HeaderText = "Agency Commission";
            // set these two columns to display currency format
            dataGridView1.Columns[5].DefaultCellStyle.Format = "c";
            dataGridView1.Columns[6].DefaultCellStyle.Format = "c";
        }
Exemplo n.º 4
0
        /// <summary>
        /// Author Wade Grimm (WG)
        /// Method to compare the supplied user name and password against DB values
        /// </summary>
        public void Login()
        {// make sure data is present and button action is login not Logout
            if (txtUsername.Text != "" && txtPassword.Text != "" && btnLogin.Text == "&Login")
            {
                // set up data access entity
                TravelExpertsDataContext dbContext = new TravelExpertsDataContext();
                string uName, uPass;      // variables for username and password
                Agent  dbAgent;           // instatiate a Agent object
                uName = txtUsername.Text; // set the variables from textbox control values
                uPass = txtPassword.Text;
                try
                {// query the DB for a match
                    dbAgent = (Agent)(from agt in dbContext.Agents
                                      where agt.AgtFirstName == uName
                                      select agt).SingleOrDefault();

                    if (dbAgent.VerifyPassword(uPass)) // will be Null if no matches found
                    {
                        btnProducts.Enabled   = true;
                        btnSuppliers.Enabled  = true;
                        btnTravelPkgs.Enabled = true;
                        txtUsername.Text      = "";
                        txtPassword.Text      = "";
                        txtUsername.Visible   = false;
                        txtPassword.Visible   = false;
                        lblWelcome.Visible    = true;
                        lblWelcome.Text       = "Welcome " + uName;
                        btnLogin.Text         = "&Logout";// set the Button text so we can logout with same control
                        btnLogin.Enabled      = true;
                        btnClear.Enabled      = false;
                    }
                    else // no match
                    {
                        MessageBox.Show("Invaild Username or password.", "Login falied", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        ClearForm();// reset form to try again
                    }
                }
                catch (InvalidOperationException ioe)
                {
                    MessageBox.Show(ioe.Message + ": " + ioe.ToString());
                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("User does not exist.", "User lookup failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    ClearForm();// reset form to try again
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + ": " + ex.ToString());
                }
            }
            else
            {
                ClearForm(); // reset form
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Called from dataGridView double click event
        /// Method determines the package id of the selected item
        /// </summary>
        public void LoadEditRecordDetails()
        {
            // we are not adding a new package
            isAdd = false;
            // clear the product lists
            rmvProd.Clear();
            addProd.Clear();
            lbAvail.Items.Clear();
            lbAssigned.Items.Clear();
            prodAssigned.Clear();
            prodAvailable.Clear();
            // determine the package id of the selected dataGridView item
            int     rowNum = Convert.ToInt32(dataGridView1.CurrentCell.RowIndex);
            int     pkgNum = Convert.ToInt32(dataGridView1[0, rowNum].Value);
            Package tmpPackage; // create a temporary package object

            // set up DatAccess and retrieve package details for the provided pkgNum
            using (TravelExpertsDataContext dbContext = new TravelExpertsDataContext())
            {
                tmpPackage = (from p in dbContext.Packages
                              where p.PackageId == pkgNum
                              select p).Single();
                currPkg = tmpPackage; // assign the package to the glocal currPkg
                GetAssigned(pkgNum);  // get the assigned product of the package
                GetAvailable();       // get the available products that can be added to the package


                // iterate through prodAssigned and add it's name to the listbox lbAssigned
                foreach (Product item in prodAssigned)
                {
                    lbAssigned.Items.Add(item.ProdName);
                }
                // iterate through prodAvailable and add it's name to the listbox lbAvail
                foreach (Product item in prodAvailable)
                {
                    lbAvail.Items.Add(item.ProdName);
                }
                // set the listboxes to sort the entries
                lbAvail.Sorted    = true;
                lbAssigned.Sorted = true;
            }
            // set the other form controls to the corresponding package detail
            dtpPkgStart.Value = (DateTime)tmpPackage.PkgStartDate;
            dtpPkgEnd.Value   = (DateTime)tmpPackage.PkgEndDate;
            txtPackageID.Text = tmpPackage.PackageId.ToString();
            txtPkgName.Text   = tmpPackage.PkgName;
            txtPkgDesc.Text   = tmpPackage.PkgDesc;
            txtPkgBase.Text   = tmpPackage.PkgBasePrice.ToString("c");
            txtPakComm.Text   = ((decimal)(tmpPackage.PkgAgencyCommission)).ToString("c");
            // enable the GroupBox so the entries can be edited
            gbDetails.Enabled = true;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Get the Packages_Products_Suppliers details for each item in a list of Product_Supplier
        /// </summary>
        /// <param name="lstPS"></param>
        /// <returns>List of Package_Product_Supplier</returns>
        public List <Packages_Products_Supplier> GetPackages_Products_Suppliers(List <Products_Supplier> lstPS)
        {
            //setup DataAccess
            TravelExpertsDataContext          dbContext = new TravelExpertsDataContext();
            Packages_Products_Supplier        ppsd;                                               // temp object
            List <Packages_Products_Supplier> ppsdList = new List <Packages_Products_Supplier>(); // temp list

            //iterate through the list and the the details for each item
            foreach (Products_Supplier prodsup in lstPS)
            {
                ppsd = new Packages_Products_Supplier();            // new object for each iteration
                ppsd.ProductSupplierId = prodsup.ProductSupplierId; // set the ProductSupplierId
                if (txtPackageID.Text != "")
                {
                    ppsd.PackageId = Convert.ToInt32(txtPackageID.Text); // set the PackageID
                }
                ppsdList.Add(ppsd);                                      // add item to the list
            }
            return(ppsdList);                                            // return the list
        }
Exemplo n.º 7
0
        /// <summary>
        /// Get Products and Suppliers details from a list of Products
        /// </summary>
        /// <param name="lstProd"></param>
        /// <returns>List of Products_Suppilers</returns>
        public List <Products_Supplier> GetProducts_Suppliers(List <Product> lstProd)
        {
            // set up DataAccess
            TravelExpertsDataContext dbContext = new TravelExpertsDataContext();
            Products_Supplier        ps;                                     // temp Product_Supplier object
            List <Products_Supplier> lstPS = new List <Products_Supplier>(); // temp list

            // get ProductSupplierID based on ProductID
            foreach (Product pd in lstProd)
            {
                ps = new Products_Supplier(); // create a new object each iteration
                // get the ProductSupplierId based on the ProductID of the current item
                ps.ProductSupplierId = Convert.ToInt32((from p in dbContext.Products_Suppliers
                                                        where p.ProductId == pd.ProductId
                                                        select p.ProductSupplierId).First());
                ps.ProductId = pd.ProductId; // set ProductID
                lstPS.Add(ps);               // add it to the list
            }
            return(lstPS);                   //return the list of Product_Supplier
        }
Exemplo n.º 8
0
        /// <summary>
        /// Fill the data grid view with a fresh view of the products table
        /// used by form load and save buttons
        /// </summary>
        private void LoadProducts()
        {
            //set db access
            TravelExpertsDataContext dbContext = new TravelExpertsDataContext();

            //populate datagridview
            dgvProducts.DataSource = dbContext.Products;
            //select full row
            dgvProducts.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //do not allow multiselect
            dgvProducts.MultiSelect = false;
            //do not allow inline editing
            dgvProducts.EditMode = DataGridViewEditMode.EditProgrammatically;
            //do not allow user to add in data grid view
            dgvProducts.AllowUserToAddRows = false;
            //do not allow user to remove rows in data grid view
            dgvProducts.AllowUserToDeleteRows = false;
            //add column names
            dgvProducts.Columns[0].HeaderText = "Product ID";
            dgvProducts.Columns[1].HeaderText = "Product Type";
        } //edn LoadProducts
        /// <summary>
        /// Get the details (the list of available products) of the supplier matching an ID
        /// </summary>
        /// <param name="SupplierId">The supplier ID of the details to retrieve in Products_Suppliers table</param>
        private void LoadSupplierDetails(int SupplierId)
        {
            using (TravelExpertsDataContext db = new TravelExpertsDataContext()) //get the DB object
            {
                // get the selected supplier
                Supplier currentSupplier = db.Suppliers.Where(supplier => supplier.SupplierId == SupplierId).Single();

                // fill in its fields
                txtSuppID.Text   = currentSupplier.SupplierId.ToString();
                txtSuppName.Text = currentSupplier.SupName;

                // get all products with that supplier ID
                originalProdList = (from p in db.Products
                                    join ps in db.Products_Suppliers on p.ProductId equals ps.ProductId
                                    where ps.SupplierId == SupplierId
                                    select p).ToList();

                // populate available products list with all products first
                List <Product> availProducts = (from p in db.Products select p).ToList();

                //start with a blank slate
                lbAssigned.Items.Clear();
                lbAvail.Items.Clear();

                foreach (Product p in originalProdList)
                {
                    availProducts.Remove(p); // get rid of the available products that the supplier already has
                    lbAssigned.Items.Add(p); // add the product they do have to their assigned list
                }

                foreach (Product p in availProducts)
                {
                    lbAvail.Items.Add(p);   // add the available products to the available list
                }

                //deactivate the ID so it can't be changed
                txtSuppID.Enabled = false;
            }
        }
Exemplo n.º 10
0
        //function to load the information and edit the record
        private void EditRecords()
        {
            isAdd = false;
            int     rowNum  = Convert.ToInt32(dgvProducts.CurrentCell.RowIndex);
            int     prodNum = Convert.ToInt32(dgvProducts[0, rowNum].Value);
            Product tempProd;

            using (TravelExpertsDataContext dbContext = new TravelExpertsDataContext())
            {
                tempProd = (from p in dbContext.Products
                            where p.ProductId == prodNum
                            select p).Single();
                currentProduct = tempProd;
            }

            txtProdID.Text           = tempProd.ProductId.ToString();
            txtProdName.Text         = tempProd.ProdName;
            gbProductDetails.Enabled = true;
            txtProdName.Enabled      = true;
            txtProdName.Focus();
            btnEdit.Enabled = false;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Searchs the DB for a Product that match the provided string
        /// </summary>
        /// <param name="s">search string</param>
        /// <returns>returns a product object</returns>
        public Product GetProductByName(string s)
        {
            // setup DataAccess
            TravelExpertsDataContext dbContext = new TravelExpertsDataContext();
            Product        p = new Product();        // new Product object
            List <Product> c = new List <Product>(); // temp list to store the product
            // dump results to a var
            var x = (from pd in dbContext.Products
                     where pd.ProdName == s
                     select pd).Distinct();

            // transfer results to List<Product>
            // list is required because var only has a .ToList() method
            // and I was getting all kinds of type casting issues doing it in any other way
            c = x.ToList();
            //set product attributes from item in list
            foreach (Product item in c)
            {
                p.ProdName  = item.ProdName;
                p.ProductId = item.ProductId;
            }
            return(p); // return the Product
        }
Exemplo n.º 12
0
        //deletes a product from the database and reloads the grid view to show as removed
        private void btnDelete_Click(object sender, EventArgs e)
        {
            isAdd = false;
            int rowNum  = Convert.ToInt32(dgvProducts.CurrentCell.RowIndex);
            int prodNum = Convert.ToInt32(dgvProducts[0, rowNum].Value);

            //Product tempProd;

            using (TravelExpertsDataContext dbContext = new TravelExpertsDataContext())
            {
                try
                {
                    DeleteProduct(prodNum, dbContext);
                    dbContext.SubmitChanges();
                    MessageBox.Show("Product Deleted");
                    LoadProducts();
                }
                catch (Exception)
                {
                    MessageBox.Show("Delete product fail, item not in Database");
                }
            }
        }
Exemplo n.º 13
0
        //checked to see if the product is new or edited, saves the data to the DB and reloads the grid view
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtProdName.Text != "")
            {
                using (TravelExpertsDataContext dbContext = new TravelExpertsDataContext())
                {
                    if (isAdd == true)
                    {
                        NewProduct(txtProdName.Text, dbContext);
                    }
                    else
                    {
                        EditProduct(Convert.ToInt32(txtProdID.Text), txtProdName.Text, dbContext);
                    }

                    try
                    {
                        dbContext.SubmitChanges();
                        LoadProducts();
                        MessageBox.Show("Product saved successfully");
                        txtProdName.Text         = "";
                        gbProductDetails.Enabled = false;
                        btnNew.Enabled           = true;
                        //btnEdit.Enabled = true;
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Save failed, please try again");
                    }
                }
            }
            else
            {
                MessageBox.Show("No information in Product Name field, save cancelled");
            }
        }
        /// <summary>
        /// Fill the data grid view with a fresh view of the suppliers table
        /// Used by form load and save buttons
        /// </summary>
        private void LoadSuppliers()
        {
            // get the database object
            TravelExpertsDataContext db = new TravelExpertsDataContext();

            // set the data grid view source to the supplier table
            dgvSuppliers.DataSource = db.Suppliers;

            //restrict actions in the data grid: select whole rows, only one row, and don't edit within the grid
            dgvSuppliers.SelectionMode         = DataGridViewSelectionMode.FullRowSelect;
            dgvSuppliers.MultiSelect           = false;
            dgvSuppliers.EditMode              = DataGridViewEditMode.EditProgrammatically;
            dgvSuppliers.AllowUserToAddRows    = false;
            dgvSuppliers.AllowUserToDeleteRows = false;

            //make the column names pretty
            dgvSuppliers.Columns[0].HeaderText = "Supplier ID";
            dgvSuppliers.Columns[1].HeaderText = "Supplier Name";

            // choose the first column and use it to sort by supplier ID ascending
            DataGridViewColumn sortCol = dgvSuppliers.Columns[0];

            dgvSuppliers.Sort(sortCol, ListSortDirection.Ascending);
        } // end LoadSuppliers()
Exemplo n.º 15
0
        /// <summary>
        /// Method GetProducts populates the products list
        /// with all available products
        /// </summary>
        public List <Product> GetProducts()
        {
            // setup DataAcess
            TravelExpertsDataContext dbContext = new TravelExpertsDataContext();
            Product tmpProd; // temporary Product object
            //products.Clear(); // clear the products list
            List <Product> products = new List <Product>();
            // get all products and dump into a var list
            var listProducts = dbContext.Products.GroupBy(item => item.ProductId,
                                                          (key, group) => new {
                ProductId = key,
                prodName  = group.First().ProdName
            }).ToList();

            // convert the var list items to Product objects and assign them to products list
            for (int i = 0; i < listProducts.Count; i++)
            {
                tmpProd           = new Product();
                tmpProd.ProdName  = listProducts[i].prodName;
                tmpProd.ProductId = listProducts[i].ProductId;
                products.Add(tmpProd);
            }
            return(products);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Get the currently assigned products for a package based on the supplied 'id'
        /// add items to prodAssigned list
        /// </summary>
        /// <param name="id"></param>
        public void GetAssigned(int id)
        {
            // setup DatAccess
            TravelExpertsDataContext dbContext = new TravelExpertsDataContext();
            List <Product>           tmplist   = new List <Product>(); // create a temporary list
            // get all products from DB based on Package id, dump results into a var list
            var names = (from pd in dbContext.Products
                         join ps in dbContext.Products_Suppliers on pd.ProductId equals ps.ProductId
                         join pps in dbContext.Packages_Products_Suppliers on ps.ProductSupplierId equals pps.ProductSupplierId
                         join pkg in dbContext.Packages on pps.PackageId equals pkg.PackageId
                         where pkg.PackageId == id
                         select pd).Distinct();

            // convert varlist into a Product list
            tmplist = names.ToList();
            // iterate through the tmplist, set attributes of tmpProd object and assign it to the prodAssigned list
            for (int i = 0; i < tmplist.Count; i++)
            {
                Product tmpProd = new Product();
                tmpProd.ProdName  = tmplist[i].ProdName;
                tmpProd.ProductId = tmplist[i].ProductId;
                prodAssigned.Add(tmpProd);
            }
        }
        /// <summary>
        /// When Save button clicked, proceed based on whether add or edit, validate inputs, then store in DB
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            int suppID; // to hold the supplier ID later

            // global validations: are there assigned products? is there a name?
            if (lbAssigned.Items.Count == 0) // if no products are assigned
            {
                MessageBox.Show("The supplier must have at least one assigned product", "Missing data");
                return;
            }
            else if (txtSuppName.Text.Length == 0) // if no name
            {
                MessageBox.Show("The supplier must have a name", "Missing data");
                txtSuppName.Focus();
                return;
            }
            else if (!Int32.TryParse(txtSuppID.Text, out suppID)) // if the ID isn't a valid integer
            {
                MessageBox.Show("The supplier ID must be a number without decimals", "Incorrect data");
                txtSuppID.Text = "";
                txtSuppID.Focus();
                return;
            }
            try
            {
                using (TravelExpertsDataContext db = new TravelExpertsDataContext())
                {
                    if (isNew) // if we're adding a new record
                    {
                        // new record validations
                        if (txtSuppID.Text.Length == 0) // if no ID
                        {
                            MessageBox.Show("The supplier must have an ID", "Missing data");
                            txtSuppID.Focus();
                            return;
                        }

                        // check if the supplier ID is already used
                        // look in the DB for the number of records with that ID -- expecting 0 or 1
                        int checkID = (from s in db.Suppliers where s.SupplierId == suppID select s).Count();
                        if (checkID > null) // if it found something, do an error
                        {
                            MessageBox.Show("The supplier ID is already in use. Please use another", "Incorrect data");
                            txtSuppID.Text = "";
                            txtSuppID.Focus();
                            return;
                        }

                        // make a new supplier object and give it the properties the user entered
                        Supplier newSupp = new Supplier();
                        newSupp.SupplierId = suppID;
                        newSupp.SupName    = txtSuppName.Text;

                        // put it in the DB
                        db.Suppliers.InsertOnSubmit(newSupp);

                        // add the products to the Products_Suppliers table
                        foreach (Product p in lbAssigned.Items)
                        {
                            // create a new product-supplier record and give it the product and supplier IDs
                            Products_Supplier ps = new Products_Supplier();
                            ps.ProductId  = p.ProductId;
                            ps.SupplierId = suppID;

                            // put it in the table
                            db.Products_Suppliers.InsertOnSubmit(ps);
                        }
                    }
                    else  // if we're editing an existing record
                    {
                        // delete removed entries
                        foreach (Product p in originalProdList)
                        {
                            if (!lbAssigned.Items.Contains(p))
                            {
                                // find the record to delete
                                Products_Supplier deletedRecord = (Products_Supplier)db.Products_Suppliers.Where(ps => (ps.SupplierId == suppID && ps.ProductId == p.ProductId)).Single();


                                // delete it from the DB
                                db.Products_Suppliers.DeleteOnSubmit(deletedRecord);
                            }
                        }

                        // add new entries
                        foreach (Product p in lbAssigned.Items)
                        {
                            if (!originalProdList.Contains(p))
                            {
                                // create the record to add, with product ID and supplier ID
                                Products_Supplier addedRecord = new Products_Supplier();
                                addedRecord.ProductId  = p.ProductId;
                                addedRecord.SupplierId = suppID;

                                // add it to the DB
                                db.Products_Suppliers.InsertOnSubmit(addedRecord);
                            }
                        }

                        // update the name in suppliers table (ID can't be changed)
                        Supplier curSupp = db.Suppliers.Single(s => s.SupplierId == suppID);
                        curSupp.SupName = txtSuppName.Text;
                    }
                    db.SubmitChanges(); // make the changes happen if we've got to this point with no problems.
                }
            }
            catch (SqlException) // this will be thrown if there's a foreign key constraint problem
            {
                MessageBox.Show("Problem Saving Changes: One of the products you're trying to remove from this supplier is assigned to a package. " +
                                "Please remove this supplier's product from the package first, then try again", "Product In Use");
                return;
            }
            catch (Exception ex) // generic exception catching
            {
                MessageBox.Show("Problem saving to database: " + ex.Message, ex.GetType().ToString());
            }
            finally
            {
                // update the DGV
                LoadSuppliers();

                if (!isNew) // if completing an edit, reload the details
                {
                    LoadSupplierDetails(suppID);
                }
                else // if completing an add, clear to prepare for the next new supplier
                {
                    PrepareNew();
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Method for saving the Package_Product_Supplier information
        /// </summary>
        /// <param name="lstPPS"></param> list of Package_Product_Supplier
        /// <param name="adding"></param> iadding items or removing items
        /// <returns>true if save was successful</returns>
        public bool Save_Packages_Products_Suppliers(List <Packages_Products_Supplier> lstPPS, bool adding)
        {
            //setup DataAccess
            TravelExpertsDataContext dbContext = new TravelExpertsDataContext();
            bool status = false;                                  // initalize the return value

            if (adding)                                           // if this is a new item
            {
                foreach (Packages_Products_Supplier pw in lstPPS) // iterate through the list add a record for each
                {
                    try
                    {   // search for any existing items, if not then save
                        if ((from ppst in dbContext.Packages_Products_Suppliers
                             where ppst.PackageId == pw.PackageId && ppst.ProductSupplierId == pw.ProductSupplierId
                             select ppst.ProductSupplierId).Count() < 1)
                        {
                            Packages_Products_Supplier insItem = new Packages_Products_Supplier();
                            if (isAdd)
                            {
                                insItem.PackageId = currPkg.PackageId;
                            }
                            else
                            {
                                insItem.PackageId = Convert.ToInt32(txtPackageID.Text);
                            }
                            insItem.ProductSupplierId = pw.ProductSupplierId;
                            dbContext.Packages_Products_Suppliers.InsertOnSubmit(insItem);
                            dbContext.SubmitChanges();
                            status = true;
                        }
                    }
                    catch (Exception)
                    {
                        status = false;
                        //MessageBox.Show("Error encounctered saving data: \n" + ex.Message);
                        break;
                    }
                }
            }
            else // removing items form the table
            {
                foreach (Packages_Products_Supplier pw in lstPPS)
                {
                    //List<Packages_Products_Supplier> c = new List<Packages_Products_Supplier>();
                    Packages_Products_Supplier delItem = new Packages_Products_Supplier();// temp object to hold search results
                    // get record details based on PackageID & ProductSupplierID
                    delItem = (from ppst in dbContext.Packages_Products_Suppliers
                               where ppst.PackageId == pw.PackageId && ppst.ProductSupplierId == pw.ProductSupplierId
                               select ppst).Single();
                    // delete the record
                    dbContext.Packages_Products_Suppliers.DeleteOnSubmit(delItem);
                    try
                    {
                        //Execute the delete
                        dbContext.SubmitChanges();
                        status = true; // set the return value
                    }
                    catch
                    {
                        status = false; // error in saving
                    }
                }
            }
            return(status);
        }
Exemplo n.º 19
0
        //delete product from the DB
        private void DeleteProduct(int prodID, TravelExpertsDataContext dbContext)
        {
            var prod = dbContext.Products.Where(x => x.ProductId == prodID).SingleOrDefault();

            dbContext.Products.DeleteOnSubmit(prod);
        }
Exemplo n.º 20
0
        //edit product information in the DB
        private static void EditProduct(int prodID, string prodName, TravelExpertsDataContext dbContext)
        {
            var prod = dbContext.Products.Where(x => x.ProductId == prodID).SingleOrDefault();

            prod.ProdName = prodName;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Fires when Save is clicked
        /// </summary>
        private void btnSave_Click(object sender, EventArgs e)
        {
            // set booleans for various checks later on
            bool allGoodAdd = false; // True when adding Packages_Products_Suppliers records succesfully
            bool allGoodRmv = false; // True when deleting Packages_Products_Suppliers records succesfully
            bool noItems    = false; // set to true if we have no items (no changes in Products of package)
            // temporary lists and objects
            List <Products_Supplier>          prodsToAdd = new List <Products_Supplier>();
            Packages_Products_Supplier        ppsd       = new Packages_Products_Supplier();
            List <Packages_Products_Supplier> ppsdList   = new List <Packages_Products_Supplier>();
            Products_Supplier ps = new Products_Supplier();
            // setup DataAccess
            TravelExpertsDataContext dbContext = new TravelExpertsDataContext();

            // if we are not adding a new record
            if (!isAdd)
            {
                try
                {
                    // Add new products to existing record

                    if (addProd.Count > 0)
                    {
                        // create lists for Products_Suppliers, Packages_Products_Suppliers
                        prodsToAdd = GetProducts_Suppliers(addProd);
                        ppsdList   = GetPackages_Products_Suppliers(prodsToAdd);
                        // call the Save method, indicating true for save
                        allGoodAdd = Save_Packages_Products_Suppliers(ppsdList, true);
                    }
                    else
                    {
                        noItems = true; // no items to save
                    }
                    //Remove products from existing package

                    if (rmvProd.Count > 0)
                    {
                        // create lists for Products_Suppliers, Packages_Products_Suppliers
                        prodsToAdd = GetProducts_Suppliers(rmvProd);
                        ppsdList   = GetPackages_Products_Suppliers(prodsToAdd);
                        // call the Save method, indicating false for delete
                        allGoodRmv = Save_Packages_Products_Suppliers(ppsdList, false);
                    }
                    else
                    {
                        noItems = true; // no items to remove
                    }
                    // Save main record detail
                    // if there are noItems or Add/Remove methods were successful
                    if (noItems || allGoodAdd || allGoodRmv)
                    {
                        // setup variables for later use
                        decimal basePrice, agcyComm;
                        // create a Package object with detail from DB based on PackageID
                        Package pkg = dbContext.Packages.Single(p => p.PackageId == Convert.ToInt32(txtPackageID.Text));
                        // set the various attributes of the object from form controls
                        pkg.PkgName      = txtPkgName.Text;
                        pkg.PkgDesc      = txtPkgDesc.Text;
                        pkg.PkgStartDate = dtpPkgStart.Value.Date;
                        pkg.PkgEndDate   = dtpPkgEnd.Value.Date;
                        //if (pkg.PkgStartDate < pkg.PkgEndDate)
                        //{
                        if (txtPkgBase.Text.StartsWith("$"))     // remove the leading $ if it exists
                        {
                            basePrice = Convert.ToDecimal(txtPkgBase.Text.Remove(0, 1));
                        }
                        else
                        {
                            basePrice = Convert.ToDecimal(txtPkgBase.Text);
                        }
                        if (txtPakComm.Text.StartsWith("$"))     // remove the leading $ if it exists
                        {
                            agcyComm = Convert.ToDecimal(txtPakComm.Text.Remove(0, 1));
                        }
                        else
                        {
                            agcyComm = Convert.ToDecimal(txtPakComm.Text);
                        }
                        //set the object attributes
                        pkg.PkgBasePrice        = basePrice;
                        pkg.PkgAgencyCommission = agcyComm;

                        if (basePrice > agcyComm)      // check the Commision is not more than the base price
                        {
                            dbContext.SubmitChanges(); // save the changes
                        }
                        else
                        {
                            MessageBox.Show("Agency Commision is too high");
                        }
                        //}
                    }
                    else
                    {
                        MessageBox.Show("An error occurred saving the data, tasks cancelled");
                    }
                }
                catch (ChangeConflictException)
                {
                    // if we have concurency exceptions, resolve them and contine the save
                    dbContext.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
                    dbContext.SubmitChanges();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message + " - " + ex.ToString());
                }
            }
            else // this is a new Package
            {
                // create lists, objects and variables needed later
                prodsToAdd = GetProducts_Suppliers(addProd);
                ppsdList   = GetPackages_Products_Suppliers(prodsToAdd);
                allGoodAdd = Save_Packages_Products_Suppliers(ppsdList, true);
                decimal basePrice, agcyComm;
                Package pkg = new Package(); // create a new Package object
                // set object attributes based on form controls
                pkg.PkgName      = txtPkgName.Text;
                pkg.PkgDesc      = txtPkgDesc.Text;
                pkg.PkgStartDate = dtpPkgStart.Value.Date;
                pkg.PkgEndDate   = dtpPkgEnd.Value.Date;
                if (txtPkgBase.Text.StartsWith("$")) // remove the leading $ if it exists
                {
                    basePrice = Convert.ToDecimal(txtPkgBase.Text.Remove(0, 1));
                }
                else
                {
                    basePrice = Convert.ToDecimal(txtPkgBase.Text);
                }
                if (txtPakComm.Text.StartsWith("$")) // remove the leading $ if it exists
                {
                    agcyComm = Convert.ToDecimal(txtPakComm.Text.Remove(0, 1));
                }
                else
                {
                    agcyComm = Convert.ToDecimal(txtPakComm.Text);
                }
                // set object attributes
                pkg.PkgBasePrice        = basePrice;
                pkg.PkgAgencyCommission = agcyComm;
                if (basePrice > agcyComm) // ensure commision is less than base price
                {
                    dbContext.Packages.InsertOnSubmit(pkg);
                    dbContext.SubmitChanges(); // submit the changes to the DB

                    currPkg = (from pk in dbContext.Packages
                               where pk.PkgName == pkg.PkgName
                               select pk).Single();
                }
                else
                {
                    MessageBox.Show("Agency Commision is too high");
                }
                // need to retrieve the newly created package ID
                prodsToAdd = GetProducts_Suppliers(addProd);
                ppsdList   = GetPackages_Products_Suppliers(prodsToAdd);
                allGoodAdd = Save_Packages_Products_Suppliers(ppsdList, true);
                NewOrClear();
            }
            LoadDGV();
            lbAvail.Items.Clear();
            gbDetails.Enabled = false;
        }