private void btnSearchForCompany_Click(object sender, EventArgs e)
        {
            using (frmCompanySearch frm = new frmCompanySearch())
            {
                frm.ShowDialog();
                if (frm.CurrentCompany != null)
                {
                    //this.CurrentScheduleConfiguration.Clear();
                    CurrentlySelectedCompany = frm.CurrentCompany;

                    using (var Dbconnection = new MCDEntities())
                    {
                        Dbconnection.Companies.Attach(CurrentlySelectedCompany);

                        Dbconnection.Entry(CurrentlySelectedCompany).Collection(a => a.Addresses).Load();
                    };
                    companyBindingSource.DataSource = CurrentlySelectedCompany;

                    addressBindingSource.DataSource = (from a in CurrentlySelectedCompany.Addresses
                                                       select a).ToList <Data.Models.Address>();
                }
                else
                {
                    companyBindingSource.DataSource = null;

                    addressBindingSource.DataSource = null;
                    //this.CurrentScheduleConfiguration.Companies.Clear();
                }
            };
            this.refreshCompanyInfo();
        }
Exemplo n.º 2
0
        private void btnUpdateContact_Click(object sender, EventArgs e)
        {
            frmContacts frm = new frmContacts();

            var IndividualObj = individualBindingSource.Current;

            Data.Models.Company CompanyObj = (Data.Models.Company)companyBindingSource.Current;

            Individual IndividualToUpdate = null;

            foreach (Individual CurrentIndividualObj in CompanyObj.Individuals)
            {
                System.Type type = IndividualObj.GetType();
                if (CurrentIndividualObj.IndividualID == (int)type.GetProperty("IndividualID").GetValue(IndividualObj, null))
                {
                    IndividualToUpdate = CurrentIndividualObj;
                }
            }
            if (IndividualToUpdate != null)
            {
                frm.CurrentContact = IndividualToUpdate;
                frm.IndividualID   = IndividualToUpdate.IndividualID;
                frm.ShowDialog();
                this.refreshCompanyContacts();
            }
        }
Exemplo n.º 3
0
        private IResult SetCustomerRecord(Data.Models.Company company, CompanyKey brokerKey)
        {
            if (company == null)
            {
                throw new ArgumentNullException("company");
            }

            var customer = CompanyUnitOfWork.CustomerRepository.FindByKey(new CustomerKey(company));

            if (company.CompanyTypes.Any(t => t.CompanyTypeEnum == CompanyType.Customer))
            {
                if (customer == null)
                {
                    customer = CompanyUnitOfWork.CustomerRepository.Add(new Data.Models.Customer
                    {
                        Id      = company.Id,
                        Company = company,
                    });
                }

                var setBrokerResult = SetCustomerBroker(customer, brokerKey);
                if (!setBrokerResult.Success)
                {
                    return(setBrokerResult);
                }
            }

            return(new SuccessResult());
        }
Exemplo n.º 4
0
        private IResult SetCompanyTypes(Data.Models.Company company, IEnumerable <CompanyType> companyTypes, CompanyKey brokerKey)
        {
            if (company == null)
            {
                throw new ArgumentNullException("company");
            }

            company.CompanyTypes = company.CompanyTypes ?? new List <CompanyTypeRecord>();
            var setTypes      = companyTypes == null ? new List <CompanyType>() : companyTypes.Distinct().ToList();
            var typesToRemove = company.CompanyTypes.Where(t => !setTypes.Contains(t.CompanyTypeEnum)).ToList();

            setTypes.Where(t => company.CompanyTypes.All(e => e.CompanyTypeEnum != t)).Select(t => new CompanyTypeRecord
            {
                CompanyId       = company.Id,
                CompanyTypeEnum = t
            }).ToList().ForEach(n => company.CompanyTypes.Add(n));;
            typesToRemove.ForEach(t => company.CompanyTypes.Remove(t));

            var setCustomerRecordResult = SetCustomerRecord(company, brokerKey);

            if (!setCustomerRecordResult.Success)
            {
                return(setCustomerRecordResult);
            }

            return(new SuccessResult());
        }
Exemplo n.º 5
0
 public SwitchToPrivate(Data.Models.Company CurrentlySelectedCompany, Individual CurrentlySelectedIndividual, Boolean MustSwitchFromStudentToCompany = true)
 {
     this.MustSwitchFromStudentToCompany = MustSwitchFromStudentToCompany;
     this.CurrentlySelectedIndividual    = CurrentlySelectedIndividual;
     this.CurrentlySelectedCompany       = CurrentlySelectedCompany;
     InitializeComponent();
 }
Exemplo n.º 6
0
        private void btnAddStudentAddress_Click(object sender, EventArgs e)
        {
            frmAddUpdateAddresses frm = new frmAddUpdateAddresses(0);

            frm.ShowDialog();
            if (frm.CurrentAddress != null)
            {
                if (frm.CurrentAddress.AddressID != 0)
                {
                    using (var Dbconnection = new MCDEntities())
                    {
                        Data.Models.Company CurrentCompany = ((Data.Models.Company)companyBindingSource.Current);
                        Dbconnection.Companies.Attach(CurrentCompany);
                        Dbconnection.Addresses.Attach(frm.CurrentAddress);

                        CurrentCompany.Addresses.Add(frm.CurrentAddress);

                        Dbconnection.SaveChanges();
                        Dbconnection.Entry(frm.CurrentAddress).Reference("LookupAddressType").Load();
                        Dbconnection.Entry(frm.CurrentAddress).Reference("LookupProvince").Load();
                        Dbconnection.Entry(frm.CurrentAddress).Reference("LookupCountry").Load();
                    };
                    refreshCompanyAddresses();
                }
            }
        }
Exemplo n.º 7
0
        private void populateCompanyName()
        {
            Data.Models.Company CompanyObj = (from a in CurrentEnquiry.Companies
                                              select a).FirstOrDefault <Data.Models.Company>();

            txtContactInformationCompanyName.Text = CompanyObj.CompanyName;
            txtSummaryCompanyName.Text            = CompanyObj.CompanyName;
        }
        public ActionResult GetAll(string filter = "")
        {
            Data.Models.Company com = new Data.Models.Company()
            {
                Name = filter
            };
            var result = company.GetAll(com);

            return(new ResponseModel <IEnumerable <Data.Models.Company> >(ErrorCode.success, result, result.Count()));
        }
Exemplo n.º 9
0
        private void dgvCompanySearchResults_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;

            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewLinkColumn && e.RowIndex >= 0)
            {
                //TODO - Button Clicked - Execute Code Here
                CurrentCompany = (Data.Models.Company)(senderGrid.Rows[e.RowIndex].DataBoundItem);
                this.Close();
            }
        }
Exemplo n.º 10
0
        public ActionResult GetList(string filter = "", int pageIndex = 1, int pageSize = 10)
        {
            Data.Models.Company com = new Data.Models.Company()
            {
                Name      = filter,
                PageIndex = pageIndex,
                PageSize  = pageSize
            };
            var result = company.GetPageList <Data.Models.Company>(com);

            return(new ResponseModel <IEnumerable <Data.Models.Company> >(ErrorCode.success, result, result.Count() > 0 ? result.First().Total : 0));
        }
        public IResult <PackSchedule> Execute(DateTime timestamp, CreatePackScheduleCommandParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            var dateCreated    = parameters.Parameters.DateCreated?.Date ?? timestamp.Date;
            var sequence       = parameters.Parameters.Sequence ?? new EFUnitOfWorkHelper(_productionUnitOfWork).GetNextSequence <PackSchedule>(p => p.DateCreated == dateCreated, p => p.SequentialNumber);
            var employeeResult = new GetEmployeeCommand(_productionUnitOfWork).GetEmployee(parameters.Parameters);

            if (!employeeResult.Success)
            {
                return(employeeResult.ConvertTo <PackSchedule>());
            }

            Data.Models.Company customer = null;
            if (parameters.CustomerKey != null)
            {
                var companyResult = new GetCompanyCommand(_productionUnitOfWork).Execute(parameters.CustomerKey, CompanyType.Customer);
                if (!companyResult.Success)
                {
                    return(companyResult.ConvertTo <PackSchedule>());
                }
                customer = companyResult.ResultingObject;
            }

            var packSchedule = _productionUnitOfWork.PackScheduleRepository.Add(new PackSchedule
            {
                EmployeeId = employeeResult.ResultingObject.EmployeeId,
                TimeStamp  = timestamp,
                PackSchID  = DataConstants.SqlMinDate,
                PSNum      = parameters.Parameters.PSNum ?? _productionUnitOfWork.PackScheduleRepository.SourceQuery.Select(p => p.PSNum).Where(p => p != null).DefaultIfEmpty(0).Max().Value + 1,

                DateCreated      = dateCreated,
                SequentialNumber = sequence,

                WorkTypeId               = parameters.WorkTypeKey.WorkTypeKey_WorkTypeId,
                ChileProductId           = parameters.ChileProductKey.ChileProductKey_ProductId,
                PackagingProductId       = parameters.PackagingProductKey.PackagingProductKey_ProductId,
                ScheduledProductionDate  = parameters.Parameters.ScheduledProductionDate,
                ProductionDeadline       = parameters.Parameters.ProductionDeadline,
                ProductionLineLocationId = parameters.ProductionLocationKey.LocationKey_Id,
                SummaryOfWork            = parameters.Parameters.SummaryOfWork ?? "",
                CustomerId               = customer == null ? (int?)null : customer.Id,
                OrderNumber              = parameters.Parameters.OrderNumber.TrimTruncate(Constants.StringLengths.OrderNumber),

                DefaultBatchTargetParameters = new ProductionBatchTargetParameters(parameters.Parameters)
            });

            return(new SuccessResult <PackSchedule>(packSchedule));
        }
Exemplo n.º 12
0
        private void btnUpdateCompanyInfo_Click(object sender, EventArgs e)
        {
            using (var Dbconnection = new MCDEntities())
            {
                using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                {
                    try
                    {
                        //CRUD Operations
                        Data.Models.Company UpdateCompany = (from a in Dbconnection.Companies

                                                             where a.CompanyID == CurrentlySelectedCompany.CompanyID
                                                             select a)

                                                            .FirstOrDefault <Data.Models.Company>();

                        UpdateCompany.CompanyName       = txtCompanyName.Text;
                        UpdateCompany.CompanySETANumber = txtSETANumber.Text;
                        UpdateCompany.CompanySicCode    = txtSiCode.Text;
                        UpdateCompany.CompanySARSLevyRegistrationNumber = txtSARSLevyReg.Text;
                        Dbconnection.Entry(UpdateCompany).State         = EntityState.Modified;



                        ////saves all above operations within one transaction
                        Dbconnection.SaveChanges();

                        //commit transaction
                        dbTran.Commit();
                    }
                    catch (Exception ex)
                    {
                        if (ex is DbEntityValidationException)
                        {
                            foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                            {
                                foreach (DbValidationError error in entityErr.ValidationErrors)
                                {
                                    MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        //Rollback transaction if exception occurs
                        dbTran.Rollback();
                    }
                }
            };
        }
Exemplo n.º 13
0
        private void btnUpdateCompanyDetails_Click(object sender, EventArgs e)
        {
            Data.Models.Company CompanyToUpdate = (Data.Models.Company)companyBindingSource.Current;
            CompanyToUpdate.CompanySARSLevyRegistrationNumber = this.txtSARSLevyRegistration.Text.ToString();
            CompanyToUpdate.CompanySETANumber = this.txtCompanySETANumber.Text.ToString();
            CompanyToUpdate.CompanySicCode    = this.txtSicCode.Text.ToString();
            this.UpdateCompanyContactDetails(CompanyToUpdate);

            using (var Dbconnection = new MCDEntities())
            {
                Dbconnection.Companies.Attach(CompanyToUpdate);
                Dbconnection.Entry(CompanyToUpdate).State = System.Data.Entity.EntityState.Modified;
                foreach (ContactDetail contactDetailToUpdate in CompanyToUpdate.ContactDetails)
                {
                    Dbconnection.Entry(contactDetailToUpdate).State = System.Data.Entity.EntityState.Modified;
                }
                Dbconnection.SaveChanges();
            };
        }
Exemplo n.º 14
0
        private void btnAddContact_Click(object sender, EventArgs e)
        {
            frmContacts frm = new frmContacts();

            frm.ShowDialog();
            Data.Models.Company CompanyObj = (Data.Models.Company)companyBindingSource.Current;

            if (frm.CurrentContact.IndividualID != 0)
            {
                using (var Dbconnection = new MCDEntities())
                {
                    Dbconnection.Companies.Attach(CompanyObj);
                    Dbconnection.Individuals.Attach(frm.CurrentContact);
                    CompanyObj.Individuals.Add(frm.CurrentContact);
                    Dbconnection.SaveChanges();
                };
            }
            // CompanyObj.Individuals.Add(NewContact);
            this.refreshCompanyContacts();
        }
Exemplo n.º 15
0
 public ActionResult Update(UpdateCompanyModel updateCompanyModel)
 {
     Data.Models.Company com = new Data.Models.Company()
     {
         Id          = updateCompanyModel.Id,
         Code        = updateCompanyModel.Code,
         Name        = updateCompanyModel.Name,
         Description = updateCompanyModel.Description,
         Order       = updateCompanyModel.Order,
         UpdateTime  = DateTime.Now
     };
     if (company.Update(com) > 0)
     {
         return(new ResponseModel <string>(ErrorCode.success, ""));
     }
     else
     {
         return(new ResponseModel <string>(ErrorCode.record_exist, ""));
     }
 }
Exemplo n.º 16
0
 private void UpdateCompanyContactDetails(Data.Models.Company CurrentSelectedCOmpany)
 {
     foreach (ContactDetail CompContactDetial in CurrentSelectedCOmpany.ContactDetails)
     {
         if (CompContactDetial.ContactTypeID == (int)EnumContactTypes.Email_Address)
         {
             CompContactDetial.ContactDetailValue = txtCompanyEmailAddress.Text;
         }
         ;
         if (CompContactDetial.ContactTypeID == (int)EnumContactTypes.Office_Number)
         {
             CompContactDetial.ContactDetailValue = txtCompanyOfficeNumber.Text;
         }
         ;
         if (CompContactDetial.ContactTypeID == (int)EnumContactTypes.Fax_Number)
         {
             CompContactDetial.ContactDetailValue = txtCompanyFaxNumber.Text;
         }
         ;
     }
 }
Exemplo n.º 17
0
 public ActionResult Add(CompanyModel companyModel)
 {
     if (company.GetByCode(companyModel.Code) != null)
     {
         return(new ResponseModel <string>(ErrorCode.record_exist, ""));
     }
     Data.Models.Company com = new Data.Models.Company()
     {
         Code        = companyModel.Code,
         Name        = companyModel.Name,
         Description = companyModel.Description,
         Order       = companyModel.Order
     };
     if (company.Insert(com) > 0)
     {
         return(new ResponseModel <string>(ErrorCode.success, ""));
     }
     else
     {
         return(new ResponseModel <string>(ErrorCode.server_exception, ""));
     }
 }
Exemplo n.º 18
0
        protected IResult <Data.Models.Company> SetCompany <T>(Data.Models.Company company, DateTime timestamp, SetCompanyCommandParameters <T> parameters)
            where T : ISetCompanyParameters
        {
            var employeeResult = new GetEmployeeCommand(CompanyUnitOfWork).GetEmployee(parameters.Parameters);

            if (!employeeResult.Success)
            {
                return(employeeResult.ConvertTo <Data.Models.Company>());
            }

            company.EmployeeId = employeeResult.ResultingObject.EmployeeId;
            company.TimeStamp  = timestamp;
            company.Active     = parameters.Parameters.Active;

            var setTypesResult = SetCompanyTypes(company, parameters.Parameters.CompanyTypes, parameters.BrokerKey);

            if (!setTypesResult.Success)
            {
                return(setTypesResult.ConvertTo <Data.Models.Company>());
            }

            return(new SuccessResult <Data.Models.Company>(company));
        }
        public IResult <PackSchedule> Execute(DateTime timestamp, UpdatePackScheduleCommandParameters parameters)
        {
            if (parameters == null)
            {
                throw new ArgumentNullException("parameters");
            }

            var packSchedule = _productionUnitOfWork.PackScheduleRepository.FindByKey(parameters.PackScheduleKey,
                                                                                      p => p.ChileProduct,
                                                                                      p => p.ProductionBatches.Select(b => b.Production.ResultingChileLot.Lot));

            if (packSchedule == null)
            {
                return(new InvalidResult <PackSchedule>(null, string.Format(UserMessages.PackScheduleNotFound, parameters.PackScheduleKey.KeyValue)));
            }

            var employeeResult = new GetEmployeeCommand(_productionUnitOfWork).GetEmployee(parameters.Parameters);

            if (!employeeResult.Success)
            {
                return(employeeResult.ConvertTo <PackSchedule>());
            }

            Data.Models.Company customer = null;
            if (parameters.CustomerKey != null)
            {
                var companyResult = new GetCompanyCommand(_productionUnitOfWork).Execute(parameters.CustomerKey, CompanyType.Customer);
                if (!companyResult.Success)
                {
                    return(companyResult.ConvertTo <PackSchedule>());
                }
                customer = companyResult.ResultingObject;
            }

            if (!parameters.ChileProductKey.Equals(packSchedule))
            {
                if (packSchedule.ProductionBatches.Any())
                {
                    var chileProduct = _productionUnitOfWork.ChileProductRepository.FindByKey(parameters.ChileProductKey);
                    if (chileProduct == null)
                    {
                        return(new InvalidResult <PackSchedule>(null, string.Format(UserMessages.ChileProductNotFound, parameters.ChileProductKey)));
                    }

                    if (chileProduct.ChileState.ToLotType() != packSchedule.ChileProduct.ChileState.ToLotType())
                    {
                        return(new InvalidResult <PackSchedule>(null, UserMessages.ChileProductDifferentLotType));
                    }

                    var completedBatch = packSchedule.ProductionBatches.FirstOrDefault(b => b.ProductionHasBeenCompleted);
                    if (completedBatch != null)
                    {
                        return(new InvalidResult <PackSchedule>(null, string.Format(UserMessages.ProductionBatchAlreadyComplete, new LotKey(completedBatch))));
                    }

                    foreach (var batch in packSchedule.ProductionBatches)
                    {
                        batch.Production.ResultingChileLot.ChileProductId = parameters.ChileProductKey.ChileProductKey_ProductId;
                    }
                }
                packSchedule.ChileProductId = parameters.ChileProductKey.ChileProductKey_ProductId;
            }

            if (!parameters.PackagingProductKey.Equals(packSchedule))
            {
                foreach (var batch in packSchedule.ProductionBatches)
                {
                    batch.Production.ResultingChileLot.Lot.ReceivedPackagingProductId = parameters.PackagingProductKey.PackagingProductKey_ProductId;
                }
                packSchedule.PackagingProductId = parameters.PackagingProductKey.PackagingProductKey_ProductId;
            }

            packSchedule.EmployeeId = employeeResult.ResultingObject.EmployeeId;
            packSchedule.TimeStamp  = timestamp;

            packSchedule.ScheduledProductionDate  = parameters.Parameters.ScheduledProductionDate;
            packSchedule.ProductionDeadline       = parameters.Parameters.ProductionDeadline;
            packSchedule.ProductionLineLocationId = parameters.ProductionLocationKey.LocationKey_Id;
            packSchedule.SummaryOfWork            = parameters.Parameters.SummaryOfWork;
            packSchedule.WorkTypeId  = parameters.WorkTypeKey.WorkTypeKey_WorkTypeId;
            packSchedule.CustomerId  = customer == null ? (int?)null : customer.Id;
            packSchedule.OrderNumber = parameters.Parameters.OrderNumber.TrimTruncate(Constants.StringLengths.OrderNumber);

            packSchedule.DefaultBatchTargetParameters = new ProductionBatchTargetParameters(parameters.Parameters);

            return(new SuccessResult <PackSchedule>(packSchedule));
        }
Exemplo n.º 20
0
        private void btnAddCompmayContactDetail_Click(object sender, EventArgs e)
        {
            using (frmAddUpdateContactDetails frm = new frmAddUpdateContactDetails(0))
            {
                frm.ShowDialog();
                if (frm.CurrentDetail != null)
                {
                    using (var Dbconnection = new MCDEntities())
                    {
                        using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                        {
                            try
                            {
                                //CRUD Operations

                                /*
                                 * this steps follow to both entities
                                 *
                                 * 1 - create instance of entity with relative primary key
                                 *
                                 * 2 - add instance to context
                                 *
                                 * 3 - attach instance to context
                                 */

                                // 1
                                Data.Models.Company c = new Data.Models.Company {
                                    CompanyID = CurrentlySelectedCompany.CompanyID
                                };
                                // 2
                                Dbconnection.Companies.Add(c);
                                // 3
                                Dbconnection.Companies.Attach(c);

                                // 1
                                ContactDetail cd = new ContactDetail {
                                    ContactDetailID = frm.CurrentDetail.ContactDetailID
                                };
                                // 2
                                Dbconnection.ContactDetails.Add(cd);
                                // 3
                                Dbconnection.ContactDetails.Attach(cd);

                                // like previous method add instance to navigation property
                                c.ContactDetails.Add(cd);
                                ////saves all above operations within one transaction
                                Dbconnection.SaveChanges();

                                //commit transaction
                                dbTran.Commit();
                            }
                            catch (Exception ex)
                            {
                                if (ex is DbEntityValidationException)
                                {
                                    foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                                    {
                                        foreach (DbValidationError error in entityErr.ValidationErrors)
                                        {
                                            MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        }
                                    }
                                }
                                else
                                {
                                    MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                //Rollback transaction if exception occurs
                                dbTran.Rollback();
                            }
                        }
                    };

                    using (var Dbconnection = new MCDEntities())
                    {
                        Dbconnection.ContactDetails.Attach(frm.CurrentDetail);
                        Dbconnection.Entry(frm.CurrentDetail).Reference(a => a.LookupContactType).Load();
                    };
                    CurrentlySelectedCompany.ContactDetails.Add(frm.CurrentDetail);
                    refreshCompanyContactDetails();
                }
            }
        }
Exemplo n.º 21
0
        private void btnAddContact_Click(object sender, EventArgs e)
        {
            //CompanyContacts CC = (CompanyContacts)companyContactsBindingSource.Current;
            //Individual CCFromCache = CurrentlySelectedCompany.Individuals.Where(a => a.IndividualID == CC.IndividualID).First();

            using (frmContactsAddUpdateContacts frm = new frmContactsAddUpdateContacts(0))
            {
                frm.ShowDialog();
                if (frm.CurrentContact != null)
                {
                    using (var Dbconnection = new MCDEntities())
                    {
                        using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                        {
                            try
                            {
                                //CRUD Operations

                                /*
                                 * this steps follow to both entities
                                 *
                                 * 1 - create instance of entity with relative primary key
                                 *
                                 * 2 - add instance to context
                                 *
                                 * 3 - attach instance to context
                                 */

                                // 1
                                Data.Models.Company C = new Data.Models.Company {
                                    CompanyID = CurrentlySelectedCompany.CompanyID
                                };
                                // 2
                                Dbconnection.Companies.Add(C);
                                // 3
                                Dbconnection.Companies.Attach(C);

                                // 1
                                Individual I = new Individual {
                                    IndividualID = frm.CurrentContact.IndividualID
                                };
                                // 2
                                Dbconnection.Individuals.Add(I);
                                // 3
                                Dbconnection.Individuals.Attach(I);

                                // like previous method add instance to navigation property
                                C.Individuals.Add(I);

                                ////saves all above operations within one transaction
                                Dbconnection.SaveChanges();

                                //commit transaction
                                dbTran.Commit();
                                // Dbconnection.Entry(I).Collection(a => a.ContactDetails).Load();
                            }
                            catch (Exception ex)
                            {
                                if (ex is DbEntityValidationException)
                                {
                                    foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                                    {
                                        foreach (DbValidationError error in entityErr.ValidationErrors)
                                        {
                                            MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        }
                                    }
                                }
                                else
                                {
                                    MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                //Rollback transaction if exception occurs
                                dbTran.Rollback();
                            }
                        }
                    };

                    using (var Dbconnection = new MCDEntities())
                    {
                        Dbconnection.Individuals.Attach(frm.CurrentContact);
                        Dbconnection.Entry(frm.CurrentContact).Reference(a => a.LookupTitle).Load();
                        CurrentlySelectedCompany.Individuals.Add(frm.CurrentContact);
                        this.refreshCompanyContacts();
                    };
                }
            }
        }
Exemplo n.º 22
0
        private void btnAddCompanyAddress_Click(object sender, EventArgs e)
        {
            frmAddUpdateAddresses frm = new frmAddUpdateAddresses(0);

            frm.ShowDialog();
            if (frm.CurrentAddress != null)
            {
                if (frm.CurrentAddress.AddressID != 0)
                {
                    if (frm.CurrentAddress.AddressIsDefault)
                    {
                        resetAdressDefaults();
                    }
                    else if (CurrentlySelectedCompany.Addresses.Count == 0)
                    {
                        frm.CurrentAddress.AddressIsDefault = true;
                    }
                    using (var Dbconnection = new MCDEntities())
                    {
                        using (System.Data.Entity.DbContextTransaction dbTran = Dbconnection.Database.BeginTransaction())
                        {
                            try
                            {
                                //CRUD Operations
                                CompanyAddresses CurrentCompanyAddress = ((CompanyAddresses)companyAddressesBindingSource.Current);

                                /*
                                 * this steps follow to both entities
                                 *
                                 * 1 - create instance of entity with relative primary key
                                 *
                                 * 2 - add instance to context
                                 *
                                 * 3 - attach instance to context
                                 */

                                // 1
                                Data.Models.Company C = new Data.Models.Company {
                                    CompanyID = CurrentlySelectedCompany.CompanyID
                                };
                                // 2
                                Dbconnection.Companies.Add(C);
                                // 3
                                Dbconnection.Companies.Attach(C);

                                // 1
                                Address A = new Address {
                                    AddressID = frm.CurrentAddress.AddressID
                                };
                                // 2
                                Dbconnection.Addresses.Add(A);
                                // 3
                                Dbconnection.Addresses.Attach(A);

                                // like previous method add instance to navigation property
                                C.Addresses.Add(A);



                                ////saves all above operations within one transaction
                                Dbconnection.SaveChanges();

                                //commit transaction
                                dbTran.Commit();
                            }
                            catch (Exception ex)
                            {
                                if (ex is DbEntityValidationException)
                                {
                                    foreach (DbEntityValidationResult entityErr in ((DbEntityValidationException)ex).EntityValidationErrors)
                                    {
                                        foreach (DbValidationError error in entityErr.ValidationErrors)
                                        {
                                            MessageBox.Show(error.ErrorMessage, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        }
                                    }
                                }
                                else
                                {
                                    MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                                //Rollback transaction if exception occurs
                                dbTran.Rollback();
                            }
                        }
                    };

                    using (var Dbconnection = new MCDEntities())
                    {
                        Dbconnection.Addresses.Attach(frm.CurrentAddress);
                        Dbconnection.Entry(frm.CurrentAddress).Reference(a => a.LookupAddressType).Load();
                        Dbconnection.Entry(frm.CurrentAddress).Reference(a => a.LookupProvince).Load();
                        Dbconnection.Entry(frm.CurrentAddress).Reference(a => a.LookupCountry).Load();
                        CurrentlySelectedCompany.Addresses.Add(frm.CurrentAddress);
                    };
                    refreshCompanyAddresses();
                }
            }
        }
Exemplo n.º 23
0
        private void btnInProgressSwitchBetweenCompanyANdPrivate_Click(object sender, EventArgs e)
        {
            if (((Data.Models.Enquiry)enquiryInprogressBindingSource.Current).Companies.Count == 0)
            {
                using (frmSelectCompanyContact frm = new frmSelectCompanyContact())
                {
                    Data.Models.Enquiry CurrentEnquiry = (Data.Models.Enquiry)enquiryInprogressBindingSource.Current;
                    Individual          CurrentContact = CurrentEnquiry.Individuals.FirstOrDefault <Individual>();
                    //frm.CurrentCompany = CurrentEnquiry.Companies.FirstOrDefault<Data.Models.Company>();
                    //frm.SelectedIndividual = CurrentEnquiry.Individuals.FirstOrDefault<Individual>();
                    frm.ShowDialog();


                    if (frm.CurrentCompany != null)
                    {
                        using (var Dbconnection = new MCDEntities())
                        {
                            Dbconnection.Enquiries.Attach(CurrentEnquiry);
                            //REmova Current Contact from tthe Enquiry
                            Dbconnection.Enquiries.Attach(CurrentEnquiry);

                            CurrentEnquiry.Individuals.Clear();
                            CurrentEnquiry.Companies.Clear();
                            Dbconnection.SaveChanges();
                        }
                        //Link Company That Is responible for the Enquiry
                        using (var Dbconnection = new MCDEntities())
                        {
                            Dbconnection.Enquiries.Attach(CurrentEnquiry);
                            Data.Models.Company CompanyToLink = new Data.Models.Company
                            {
                                CompanyID = frm.CurrentCompany.CompanyID
                            };
                            Dbconnection.Companies.Attach(CompanyToLink);
                            CurrentEnquiry.Companies.Add(CompanyToLink);
                            Dbconnection.SaveChanges();
                        };

                        using (var Dbconnection = new MCDEntities())
                        {
                            Dbconnection.Enquiries.Attach(CurrentEnquiry);
                            Individual NewContact = new Individual
                            {
                                IndividualID = frm.SelectedIndividual.IndividualID
                            };
                            Dbconnection.Individuals.Attach(NewContact);
                            CurrentEnquiry.Individuals.Add(NewContact);
                            Dbconnection.SaveChanges();
                        };

                        //Link the Copmpany Contact
                        // Dbconnection.Individuals.Add(frm.SelectedIndividual);


                        //Remove the current Contact

                        //Dbconnection.Entry(CompanyToLink).Reload();
                        //CurrentEnquiry.Companies.Add(frm.CurrentCompany);
                    }
                }
                refreshInProgressEnquiry(CurrentSelectedEnquiryID);
            }
            else
            {
                //Selects From List Of All Students from the Custom Student Search Form
                using (frmSelectIndividualContact frm = new frmSelectIndividualContact())
                {
                    frm.ShowDialog();
                    //get the Individual Selected Which represents the Student Selected.

                    if (frm.SelectedIndividual.IndividualID != 0)
                    {
                        using (var Dbconnection = new MCDEntities())
                        {
                            /*1. Removes the current Slected Company Contact*/
                            Data.Models.Enquiry CurrentEnquiry = ((Data.Models.Enquiry)enquiryInprogressBindingSource.Current);

                            Dbconnection.Enquiries.Attach(CurrentEnquiry);

                            List <Individual>          temp          = ((Data.Models.Enquiry)enquiryInprogressBindingSource.Current).Individuals.ToList <Individual>();
                            List <Data.Models.Company> tempCompanies = ((Data.Models.Enquiry)enquiryInprogressBindingSource.Current).Companies.ToList <Data.Models.Company>();
                            foreach (Individual individ in temp)
                            {
                                ((Data.Models.Enquiry)enquiryInprogressBindingSource.Current).Individuals.Remove(individ);
                            }
                            foreach (Data.Models.Company comp in tempCompanies)
                            {
                                ((Data.Models.Enquiry)enquiryInprogressBindingSource.Current).Companies.Remove(comp);
                            }
                            // Dbconnection.Entry(CurrentEnquiry).State = EntityState.Modified;
                            Dbconnection.SaveChanges();
                            /*1. End Removal of Current Enquiry Contact*/


                            /*2. Adds The Cuurentlty Selected Student Contact to be linked with the Enquiry for future contacting*/
                            Individual IndividualToLink = (from a in Dbconnection.Individuals
                                                           where a.IndividualID == frm.SelectedIndividual.IndividualID
                                                           select a).FirstOrDefault <Individual>();
                            CurrentEnquiry.Individuals.Add(IndividualToLink);
                            Dbconnection.SaveChanges();
                            /*2. End Adding the Student Contact Details To the Enquiry.*/
                        };
                    }
                    this.refreshInProgressEnquiry(CurrentSelectedEnquiryID);
                }
            }
        }