示例#1
0
        /// <summary>
        /// Delete items from database by selecting datagrid row position. First checking if position isn't selected
        /// write show messagebox with "Zaznacz pozycję do usunięcia" ["Select position to delete"].
        /// If position to delete is selected then get agentData.ItemSource is checking as DatagridList
        /// as PolicyNumber, next to we have sql query by linq, where that query checking is policyNumber in database
        /// is equal deleteItem(PolicyNumber in selected item/list) if it's equal than deleting position in database
        /// and next to save changes in database. We have here one more thing like messagebox with question
        /// "Czy na pewno usunąć polisę" ("Ostrzeżenie") ["Are you sure to delete that policy?"] [("Warning")].
        /// </summary>
        /// <param name="agentDocument">Used as agentDocument.SelectedItem</param>
        /// <exception cref="NullReferenceException">Zaznacz pozycję do usunięcia</exception>
        public static void DeleteAfterSelectRowInDataGrid(object agentDocument)
        {
            if (agentDocument != null)
            {
                if (MessageBox.Show("Czy na pewno usunąć polisę?", "Ostrzeżenie", MessageBoxButton.YesNo
                                    , MessageBoxImage.Warning) == MessageBoxResult.No)
                {
                }
                else
                {
                    try
                    {
                        masterEntities dc = new masterEntities(SaveConnectionStringsAsStringToMethodParameter.connstringMasterEntitiesConnectionDatabase);

                        var            deleteItem   = (agentDocument as DatagridList).ID;
                        userPolicyData deletePolicy = dc.userPolicyData.Where(n => n.Id.Equals(deleteItem)).SingleOrDefault();
                        dc.userPolicyData.Remove(deletePolicy);
                        dc.SaveChanges();
                    }
                    catch (NullReferenceException)
                    {
                        MessageBox.Show("Zaznacz pozycję do usunięcia");
                    }
                }
            }
            else
            {
                MessageBox.Show("Zaznacz pozycję do usunięcia");
            }
        }
示例#2
0
        public ActionResult authenticate(Account users)
        {
            using (masterEntities db = new masterEntities()) {
                //Returns null if no such user exists, returns with attributes from user table in database otherwise
                var userDetails = db.Users.Where(x => x.username == users.username && x.pword == users.password).FirstOrDefault();

                if (userDetails == null)
                {
                    users.errorMessage = "Invalid Credentials";
                    return(View("login", users));
                }

                else
                {
                    //Set default session values to carry over into the other site functions
                    //NOTE: Session variables use cookies, so cookies must be enabled for this site to function
                    Session["username"]     = userDetails.username;
                    Session["building"]     = userDetails.associatedBuilding;
                    Session["adminAccess"]  = userDetails.isAdmin;
                    Session["guestCount"]   = 0;
                    Session["host"]         = null;
                    Session["guestIsFound"] = null;
                    Session["tabStatus"]    = "tabIn";
                    return(View("gmsHome"));
                }
            }
        }
示例#3
0
        public List <userinfo> getUserInfoByToken(int flag, string strToken, int commentid)
        {
            List <userinfo> retUserinfos = new List <userinfo>();

            if (strToken != null && strToken.Trim() != "")
            {
                switch (flag)
                {
                case 1:
                    using (dataserverEntities db = new dataserverEntities())
                    {
                        var strUserid = db.uts.FirstOrDefault(p => p.token == strToken).userid;
                        retUserinfos = db.userinfo.Where(p => p.userid == strUserid).ToList();
                    }
                    break;

                case 2:
                    using (organizeEntities db = new organizeEntities())
                    {
                        var strUserid = db.uts.FirstOrDefault(p => p.token == strToken).userid;
                        retUserinfos = db.userinfo.Where(p => p.userid == strUserid).ToList();
                    }
                    break;

                case 3:
                    using (masterEntities db = new masterEntities())
                    {
                        if (commentid > 0)
                        {
                            var           strUserid = db.uts.FirstOrDefault(p => p.token == strToken).userid;
                            List <String> userArry  = new List <string>();
                            userArry.Add(strUserid);

                            var ltmrcrinfo = db.mrcrinfo.Where(p => p.mrcrid == commentid).ToList();
                            var userid     = "";
                            if (ltmrcrinfo != null && ltmrcrinfo.Count > 0)
                            {
                                userid = ltmrcrinfo[0].suserid.ToString();
                                userArry.Add(userid);
                            }
                            foreach (var aa in userArry)
                            {
                                var tt = db.userinfo.Where(p => p.userid == aa).FirstOrDefault();
                                if (tt != null)
                                {
                                    retUserinfos.Add(tt);
                                }
                            }
                        }
                        else
                        {
                            var strUserid = db.uts.FirstOrDefault(p => p.token == strToken).userid;
                            retUserinfos = db.userinfo.Where(p => p.userid == strUserid).ToList();
                        }
                    }
                    break;
                }
            }
            return(retUserinfos);
        }
        // PUT: api/TaskAPI
        public string Put(TaskModel taskModel)
        {
            string success = string.Empty;

            using (masterEntities mstEntities = new masterEntities())
            {
                Task task = new Task();
                task = mstEntities.Tasks.Where(t => t.Task_ID == taskModel.TaskID).Select(x => x).FirstOrDefault();

                //TaskModel task = new TaskModel();
                //task = l_task1.Where(t => t.TaskID == taskModel.TaskID).Select(x => x).FirstOrDefault();

                if (task != null)
                {
                    task.EndDate    = taskModel.EndDate;
                    task.Parent_ID  = taskModel.ParentID;
                    task.Priority   = taskModel.Priority;
                    task.Project_ID = taskModel.ProjectID;
                    task.StartDate  = taskModel.StartDate;
                    task.Status     = taskModel.Status;
                    task.TaskName   = taskModel.TaskName;
                    task.Task_ID    = taskModel.TaskID;

                    //l_task1.Remove(task);
                    //l_task1.Add(task);

                    mstEntities.Entry(task).State = EntityState.Modified;
                    mstEntities.SaveChanges();
                }
            };

            success = "Task Details successfully Updated";
            return(success);
        }
 public IEnumerable <Event> Get()
 {
     using (masterEntities entities = new masterEntities())
     {
         return(entities.Events.ToList());
     }
 }
示例#6
0
        /// <summary>
        /// Gets data from selected insurance policy which is in database and display in window to edit.
        /// </summary>
        /// <param name="agentDocument">agentDocument.SelectedItem</param>
        /// <exception cref="NullReferenceException">Zaznacz pozycję do edycji</exception>
        public static void EditPolicyInDatabase(object agentDocument)
        {
            if (agentDocument != null)
            {
                try
                {
                    masterEntities dc = new masterEntities(SaveConnectionStringsAsStringToMethodParameter.connstringMasterEntitiesConnectionDatabase);

                    var            editItem   = (agentDocument as DatagridList).PolicyNumber;
                    userPolicyData editPolicy = dc.userPolicyData.Single(n => n.policyNumber.Equals(editItem));

                    CatchPolicyData.savedIdNumber     = editPolicy.Id;
                    CatchPolicyData.savedPolicyNumber = editPolicy.policyNumber;
                    CatchPolicyData.savedUserName     = editPolicy.userName;
                    CatchPolicyData.savedFullDate     = editPolicy.fullDate;
                    CatchPolicyData.savedBrokerName   = editPolicy.brokerName;

                    var editPolicyWindow = new EditPolicyDocument();
                    editPolicyWindow.ShowDialog();
                }
                catch (NullReferenceException)
                {
                    MessageBox.Show("Zaznacz pozycję do edycji");
                }
            }
            else
            {
                MessageBox.Show("Zaznacz pozycję do edycji");
            }
        }
 public static List <CompanyType> GetAll()
 {
     using (masterEntities context = new masterEntities())
     {
         return(context.CompanyType.OrderBy(x => x.Type).ToList());
     }
 }
示例#8
0
        //Method to mark a guest as prohibited
        public ActionResult markProhibited(History t)
        {
            using (masterEntities db = new masterEntities()) {
                Guest g = db.Guests.Where(x => x.guestID == t.Guest.guestID).FirstOrDefault();

                //Check if Guest ID did not match
                if (g == null)
                {
                    TempData["msg"]         = "<script>alert('Guest ID did not match. Please search for guest to try again.');</script>";
                    Session["guestIsFound"] = null;
                    return(View("admin", t));
                }

                //Otherwise, mark guest as prohibited
                else
                {
                    g.prohibited      = t.Guest.prohibited;
                    g.prohibitedDate  = DateTime.Now;
                    db.Entry(g).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();

                    //Since we return t, do not risk setting prohibited as true anywhere else in our model
                    t.Guest.prohibited      = false;
                    Session["guestIsFound"] = null;
                    Session["host"]         = "This guest has successfully been marked as prohibited.";
                    return(View("admin", t));
                }
            }
        }
示例#9
0
        public ActionResult SaveImages(IEnumerable <HttpPostedFileBase> files, Companies company)
        {
            // The Name of the Upload component is "files"
            if (files != null)
            {
                masterEntities db = new masterEntities();

                var file = files.First();

                // Some browsers send file names with full path.
                // We are only interested in the file name.
                var fileName     = Path.GetFileName(file.FileName);
                var webPath      = "DataImages/CompaniesLogos/" + company.Id;
                var physicalPath = Server.MapPath("/") + webPath;

                if (!System.IO.Directory.Exists(physicalPath))
                {
                    System.IO.Directory.CreateDirectory(physicalPath);
                }

                // The files are not actually saved in this demo
                physicalPath = physicalPath + "/logo." + file.FileName.Split('.')[1];
                webPath      = webPath + "/logo." + file.FileName.Split('.')[1];

                file.SaveAs(physicalPath);
                company.ImageURL = webPath;

                db.SaveChanges();
            }


            // Return an empty string to signify success
            return(Content(""));
        }
示例#10
0
        /// <summary>
        /// Create user. By this class we can add user to database, it's checking fields,
        /// they are must have values, can't be null, all three fields are requirement.
        /// If one of field is empty then we get message "Wprowadź dane użytkownika!" ["Enter users data!"].
        /// If all fields are filled method adds fields with values to database, and saves changes.
        /// </summary>
        /// <param name="userNameTextField">Used in AddUser as userNameTextField.Text</param>
        /// <param name="userSurnameTextField">Used in AddUser as userSurnameTextField.Text</param>
        /// <param name="passwordTextField">Used in AddUser as passwordTextField.Text</param>
        public static void AddClientToDatabase(string userNameTextField, string userSurnameTextField, string passwordTextField)
        {
            try
            {
                masterEntities dc = new masterEntities(SaveConnectionStringsAsStringToMethodParameter.connstringMasterEntitiesConnectionDatabase);

                if (userNameTextField != "" && userSurnameTextField != "" && passwordTextField != "")
                {
                    var person = new user {
                        Name = userNameTextField, Surname = userSurnameTextField, Password = passwordTextField
                    };

                    dc.user.Add(person);
                    dc.SaveChanges();
                }
                else
                {
                    MessageBox.Show("Wprowadź dane użytkownika!");
                }
            }
            catch (ArgumentException)
            {
                MessageBox.Show("Brak połączenia z bazą danych");
            }
        }
示例#11
0
        private void buttonEnter_Click(object sender, EventArgs e)
        {
            dir = labelDir.Text;
            des = textBoxDes.Text;
            //读取数据库
            masterEntities db     = new masterEntities();
            var            config = db.DbProfinet.AsNoTracking().ToList();
            var            temp   = config.FirstOrDefault(m => m.reg == regNum.ToString());

            if (temp != null)
            {
                //更新数据
                DbProfinet u = new DbProfinet()
                {
                    Id = temp.Id, reg = temp.reg, dir = dir, des = des
                };
                db.Entry <DbProfinet>(u).State = EntityState.Modified;
                db.SaveChanges();
            }
            else
            {
                temp = new DbProfinet
                {
                    reg = regNum.ToString(),
                    dir = dir,
                    des = des
                };
                db.DbProfinet.Add(temp);
                db.SaveChanges();
            }
            this.DialogResult = DialogResult.OK;
        }
示例#12
0
        // PUT: api/ProjectAPI
        public string Put(ProjectModel projectModel)
        {
            string success = string.Empty;

            using (masterEntities mstEntities = new masterEntities())
            {
                Project project = new Project();
                project = mstEntities.Projects.Where(t => t.Project_ID == projectModel.Project_ID).Select(x => x).FirstOrDefault();

                //ProjectModel project = new ProjectModel();
                //project = l_project.Where(t => t.Project_ID == projectModel.Project_ID).Select(x => x).FirstOrDefault();

                if (project != null)
                {
                    project.User_ID     = projectModel.UserID;
                    project.Priority    = projectModel.Priority;
                    project.ProjectName = projectModel.Project;
                    project.Project_ID  = projectModel.Project_ID;
                    project.StartDate   = projectModel.StartDate;

                    //l_project.Remove(project);
                    //l_project.Add(project);

                    mstEntities.Entry(project).State = EntityState.Modified;
                    mstEntities.SaveChanges();
                }
            };

            success = "Project Details successfully Updated";
            return(success);
        }
示例#13
0
        // POST: api/ProjectAPI
        public string Post(ProjectModel projectModel)
        {
            string success = string.Empty;

            using (masterEntities mstEntities = new masterEntities())
            {
                Project project = new Project();

                //ProjectModel project = new ProjectModel();

                project.User_ID     = projectModel.UserID;
                project.Priority    = projectModel.Priority;
                project.ProjectName = projectModel.Project;
                project.Project_ID  = projectModel.Project_ID;
                project.StartDate   = projectModel.StartDate;
                project.EndDate     = projectModel.EndDate;

                //l_project.Add(project);

                mstEntities.Projects.Add(project);
                mstEntities.SaveChanges();
            }

            success = "Project Details successfully saved";

            return(success);
        }
示例#14
0
        /// <summary>
        ///  Login user, check if user and password is equal values in database, if true - login, open new window
        ///  with program and close login window.If false - show message box with message "Błędne hasło lub login!"
        /// ["Wrong password or login"].
        /// </summary>
        /// <param name="user">nameData.SelectedValue in combobox</param>
        /// <param name="password">passwordField.Password text field where need to enter password to login</param>
        /// <exception cref="InvalidOperationException">Throws if login or password field or both are empty / wrong</exception>
        public static void CheckIdentity(string user, string password)
        {
            masterEntities dc = new masterEntities(SaveConnectionStringsAsStringToMethodParameter.connstringMasterEntitiesConnectionDatabase);

            try
            {
                var checkLogin = dc.user.Where(n => password.Equals(n.Password) && user.Equals(n.Name + " " + n.Surname)).First();

                if (checkLogin != null)
                {
                    var menagerWindow = new LocalDatabaseApplication.MenagerWindow();
                    menagerWindow.Show();
                    LocalDatabaseApplication.MainWindow loginWindow = App.Current.Windows.OfType <LocalDatabaseApplication.MainWindow>().FirstOrDefault();
                    loginWindow.Close();

                    var menagerWindowUserName = new LocalDatabaseApplication.MenagerWindow();
                    menagerWindow.Welcome(user);

                    UserInformation.CurrentLoggedInUser = user;
                }
                else
                {
                    MessageBox.Show("Błędne hasło lub login!");
                }
            }
            catch (InvalidOperationException)
            {
                MessageBox.Show("Błędne hasło lub login!");
            }
        }
 public static CompanyType GetByID(int id)
 {
     using (masterEntities context = new masterEntities())
     {
         return(context.CompanyType.Where(x => x.Id == id).First());
     }
 }
示例#16
0
        //Method to check out a set of guests
        public ActionResult checkOutSet(History t, int[] set)
        {
            using (masterEntities db = new masterEntities()) {
                List <List <History> > actives = new List <List <History> >();
                for (int i = 0; i < set.Count(); i++)
                {
                    //LINQ does not support array index values, so use a temporary variable here
                    var temp = set[i];
                    actives.Add(db.Histories.Where(x => x.guestID == temp.ToString() && x.outTime == null).ToList());
                }

                for (int i = 0; i < actives.Count(); i++)
                {
                    for (int j = 0; j < actives.ElementAt(i).Count(); j++)
                    {
                        actives.ElementAt(i).ElementAt(j).outTime         = DateTime.Now;
                        db.Entry(actives.ElementAt(i).ElementAt(j)).State = System.Data.Entity.EntityState.Modified;

                        //Since Guest and Resident are virtual members, do not add a row for the foreign keys
                        db.Entry(actives.ElementAt(i).ElementAt(j).Guest).State    = System.Data.Entity.EntityState.Unchanged;
                        db.Entry(actives.ElementAt(i).ElementAt(j).Resident).State = System.Data.Entity.EntityState.Unchanged;
                        db.SaveChanges();
                    }
                }

                //Reset form values after successful checkout
                int activeGuests = db.Histories.Where(x => x.hostID == t.Resident.studentID && x.outTime == null).Count();
                Session["guestIsFound"] = null;
                Session["guestCount"]   = activeGuests;

                return(View("gmsHome", t));
            }
        }
 public static List <CompanyType> GetForType(int id)
 {
     using (masterEntities context = new masterEntities())
     {
         return(context.Companies.Where(x => x.Id == id).First().CompanyType.ToList());
     }
 }
        public List <DuesMember> getListOfDuesMemeberUnderSelectedStates(List <string> states)
        {
            List <DuesMember> members = new List <DuesMember>();

            using (masterEntities db = new masterEntities())
            {
                foreach (string state in states)
                {
                    var results = db.Table1.Where(p => (p.DuesMembState.Equals(state.Trim()))).Select(p => new DuesMember
                    {
                        DuesMemberFirstName    = p.DuesMembFirstName,
                        DuesMemberLastName     = p.DuesMembLastName,
                        DuesMemberAddress1     = p.DuesMembAddress1,
                        DuesMemberAddress2     = p.DuesMembAddress2,
                        DuesMemberCity         = p.DuesMembCity,
                        DuesMemberState        = p.DuesMembState,
                        DuesMemberZipCode      = p.DuesMembZipCode,
                        DuesMemberEmailAddress = p.DuesMembEmailAddress,
                        DuesMemberBirthDate    = p.DuesMembBirthDate,
                        DuesMemberPhone        = p.DuesMembPhone,
                        DuesMemberSSN          = p.DuesMembSSN
                    }).ToList <DuesMember>();

                    members.AddRange(results);
                }
            }
            foreach (DuesMember m in members)
            {
                m.MailingAddress = m.getMailingAddressDuesMember(m.DuesMemberAddress1, m.DuesMemberAddress2, m.DuesMemberCity, m.DuesMemberState, m.DuesMemberZipCode);
            }
            return(members);
        }
        public ActionResult InicioSesion(string correo, string contrasena)
        {
            if (!string.IsNullOrEmpty(correo) && !string.IsNullOrEmpty(contrasena))
            {
                masterEntities db   = new masterEntities();
                usuario        user = db.usuario.FirstOrDefault(e => e.usuarioCorreo == correo &&
                                                                e.usuarioContrasenia == contrasena);

                if (user != null)
                {
                    @HttpCookie cookie1 = new @HttpCookie("usuarioNombre", user.usuarioNombre);
                    @Response.Cookies.Add(cookie1);
                    FormsAuthentication.SetAuthCookie(user.usuarioId + "|" + user.usuarioNombre, true);
                    return(RedirectToAction("perfilCliente", "Home"));
                }
                else
                {
                    return(RedirectToAction("InicioSesion", new { message = "Usario/Contraseña inválidos" }));
                }
            }
            else
            {
                return(RedirectToAction("InicioSesion", new { message = "Escribe tu usuario y contraseña" }));
            }
        }
 public Event Get(int Id)
 {
     using (masterEntities entities = new masterEntities())
     {
         return(entities.Events.FirstOrDefault(e => e.Id == Id));
     }
 }
        // POST: api/TaskAPI
        public string Post(TaskModel taskModel)
        {
            string success = string.Empty;

            using (masterEntities mstEntities = new masterEntities())
            {
                Task task = new Task();

                //TaskModel task = new TaskModel();
                task.EndDate    = taskModel.EndDate;
                task.Parent_ID  = taskModel.ParentID;
                task.Priority   = taskModel.Priority;
                task.Project_ID = taskModel.ProjectID;
                task.StartDate  = taskModel.StartDate;
                task.Status     = taskModel.Status;
                task.TaskName   = taskModel.TaskName;
                task.Task_ID    = taskModel.TaskID;

                //l_task1.Add(task);

                mstEntities.Tasks.Add(task);
                mstEntities.SaveChanges();
            }

            success = "Project Details successfully saved";

            return(success);
        }
示例#22
0
 public UserDashboard(Form login, Users usr)
 {
     InitializeComponent();
     db     = new masterEntities();
     _login = login;
     _usr   = usr;
 }
示例#23
0
        //Method to check out a guest
        public ActionResult checkOut(History t)
        {
            using (masterEntities db = new masterEntities()) {
                //Check this guest out of all buildings, not just the one where they scanned out
                List <History> activeTransactions = db.Histories.Where(x => x.guestID == t.guestID && x.outTime == null).ToList();
                for (int i = 0; i < activeTransactions.Count(); i++)
                {
                    //Set the check out time to right now
                    activeTransactions.ElementAt(i).outTime         = DateTime.Now;
                    db.Entry(activeTransactions.ElementAt(i)).State = System.Data.Entity.EntityState.Modified;

                    //Since Guest and Resident are virtual members, do not add a row for the foreign keys
                    db.Entry(activeTransactions.ElementAt(i).Guest).State    = System.Data.Entity.EntityState.Unchanged;
                    db.Entry(activeTransactions.ElementAt(i).Resident).State = System.Data.Entity.EntityState.Unchanged;
                    db.SaveChanges();

                    //Set success message through Session object
                    Session["guestIsFound"] = "Guest successfully checked out!";
                }
            }

            t.guestID             = "";
            Session["guestCount"] = -1;
            Session["tabStatus"]  = "tabOut";
            return(View("gmsHome", t));
        }
示例#24
0
        // PUT: api/UserAPI
        public string Put(UserModel userModel)
        {
            string success = string.Empty;

            using (masterEntities mstEntities = new masterEntities())
            {
                User user = new User();

                user = mstEntities.Users.Where(t => t.User_ID == userModel.UserID).Select(x => x).FirstOrDefault();

                //user = l_user.Where(t => t.UserID == userModel.UserID).Select(x => x).FirstOrDefault();

                if (user != null)
                {
                    user.EmployeeID = userModel.EmployeeID;
                    user.FirstName  = userModel.FirstName;
                    user.LastName   = userModel.LastName;
                    user.Role       = userModel.Role;

                    //l_user.Remove(user);
                    //l_user.Add(user);

                    mstEntities.Entry(user).State = EntityState.Modified;
                    mstEntities.SaveChanges();
                }
            };

            success = "User Details successfully Updated";
            return(success);
        }
        public bool AuthUser(string username, string password)
        {
            masterEntities h = new masterEntities();

            try
            {
                if (username != "" && password != null)
                {
                    logintable l = h.logintables.Where(p => p.username == username && p.pass == password).Single();
                    if (l != null)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch { return(false); }
        }
示例#26
0
        // GET: api/UserAPI
        public List <UserModel> Get()
        {
            //List<UserModel> l_user = new List<UserModel>()
            //        {
            //            new UserModel(){ UserID = 1,  EmployeeID = "A64", FirstName = "Senthil", LastName = "Kumar", Role = "M" },
            //            new UserModel(){ UserID = 2,  EmployeeID = "A61", FirstName = "Goutham", LastName = "K", Role = "M" },
            //            new UserModel(){ UserID = 3,  EmployeeID = "A62", FirstName = "Krishna", LastName = "A", Role = "M" },
            //        };

            List <UserModel> l_UserModels = new List <UserModel>();

            using (masterEntities mstEntities = new masterEntities())
            {
                List <User> l_user = new List <User>();
                l_user = mstEntities.Users.Select(x => x).ToList();

                if (l_user?.Count > 0)
                {
                    foreach (var user in l_user)
                    {
                        UserModel userModel = new UserModel();
                        userModel.EmployeeID = user.EmployeeID;
                        userModel.FirstName  = user.FirstName;
                        userModel.LastName   = user.LastName;
                        userModel.Role       = user.Role;
                        userModel.UserID     = user.User_ID;

                        l_UserModels.Add(userModel);
                    }
                }
            };

            return(l_UserModels);
        }
        public ActionResult DeleteCustomer(string CustomerID)
        {
            //1. ORM

            masterEntities ORM = new masterEntities();

            //2. Find the customer you want to delete
            Customer Found = ORM.Customers.Find(CustomerID);



            if (Found != null)
            {    //3. Remove the customer
                // TODO: Delete all orders for that customer first!
                ORM.Customers.Remove(Found);
                //4. Save to the DB
                ORM.SaveChanges();

                return(RedirectToAction("About"));// execute the About Action again
            }
            else
            {
                ViewBag.ErrorMessage = "User not found!";
                return(View("Error"));
            }
        }
        public ActionResult SaveCustomerUpdates(Customer updatedCustomer)
        {
            //1. create the ORM
            masterEntities ORM = new masterEntities();

            //2. Find the customer

            Customer OldCustomerRecord = ORM.Customers.Find(updatedCustomer.CustomerID);

            if (OldCustomerRecord != null && ModelState.IsValid)
            {
                //3. Update the existing customer

                OldCustomerRecord.CompanyName = updatedCustomer.CompanyName;
                OldCustomerRecord.City        = updatedCustomer.City;

                ORM.Entry(OldCustomerRecord).State = System.Data.Entity.EntityState.Modified;

                //4. save back to the DB
                ORM.SaveChanges();

                return(RedirectToAction("About"));
            }
            else
            {
                ViewBag.ErrorMessage = "Oops! Something went wrong!";
                return(View("Error"));
            }
        }
示例#29
0
        /// <summary>
        /// Thanks to AddPoliy class You can add policy document to database. First it's checking policy number
        /// if this number is in database already it's return message "Polisa jest już w bazie!",
        /// ["Policy is already in database!"]. Otherwise going forward and checking fields like policyNumber,
        /// dateMonth, dateYear, userName, if they are filled, after click button alghoritm add that fields to database.
        /// If one of fields are empty then You get message "Wprowadź dane do polisy!" ["Enter policy data!"
        /// + Adding name of logged user to policy position in database. After that clearing text fields.
        /// </summary>
        /// <param name="policyNumber">Used as policyNumberTextField.Text</param>
        /// <param name="fullDate">Used as addDate.DisplayDate</param>
        /// <param name="brokerName">Used as brokerNameTextField.Text</param>
        public static void UserPolicyToDatabase(string policyNumber, DateTime?fullDate, string brokerName)
        {
            masterEntities dc = new masterEntities(SaveConnectionStringsAsStringToMethodParameter.connstringMasterEntitiesConnectionDatabase);

            var checkIfPolicyInDatabase = dc.userPolicyData.Where(n => policyNumber.Equals(n.policyNumber)).FirstOrDefault();

            if (checkIfPolicyInDatabase != null)

            {
                MessageBox.Show("Polisa jest już w bazie!");
            }
            else
            {
                if (policyNumber != "")
                {
                    var documentData = new userPolicyData
                    {
                        policyNumber = policyNumber,
                        fullDate     = fullDate
                        ,
                        userName = UserInformation.CurrentLoggedInUser
                        ,
                        brokerName = brokerName
                    };

                    dc.userPolicyData.Add(documentData);
                    dc.SaveChanges();
                }
                else
                {
                    MessageBox.Show("Wprowadź dane polisy!");
                }
            }
        }
 public List <Employee> getPersonelList()
 {
     using (masterEntities ctx = new masterEntities())
     {
         var personelList = ctx.Employees.ToList();;
         return(personelList);
     }
 }