예제 #1
0
        /// <summary>
        /// For inserting user roles in database.
        /// </summary>
        /// <param name="objLocationEmailContact"></param>
        /// <returns></returns>
        public bool AddUserRole(RoleList objUserRole)
        {
            try
            {
                CommonDAL.logger.LogInfo(typeof(string), string.Format(CultureInfo.InvariantCulture, "Called {2} function ::{0} {1}.", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), MethodBase.GetCurrentMethod().Name));

                bool IsSuccessfull = false;

                using (PortalDbEntities portalEntities = new PortalDbEntities())
                {
                    RoleMember userrole = new RoleMember();
                    userrole.userId      = objUserRole.UserID;
                    userrole.roleId      = objUserRole.RoleID;
                    userrole.dateCreated = objUserRole.DateCreated;
                    userrole.whoUpdated  = objUserRole.WhoCreated;

                    portalEntities.RoleMembers.Add(userrole); /// Insert the Record in Respected Table.
                    portalEntities.SaveChanges();             /// Check the Chenges in Table After Record Insertion.
                    IsSuccessfull = true;
                }
                return(IsSuccessfull);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                CommonDAL.logger.LogInfo(typeof(string), string.Format(CultureInfo.InvariantCulture, "End {2} function ::{0} {1}.", DateTime.Now.ToShortDateString(), DateTime.Now.ToShortTimeString(), MethodBase.GetCurrentMethod().Name));
            }
        }
예제 #2
0
        public void ChangeRole(int memberId, RoleMember role)
        {
            var member = GetMemberById(memberId);

            member.Role = role;
            UpdateMember(member);
        }
        public ValidationResult AddRoleMember([FromBody] AddRoleMemberRequestModel requestModel)
        {
            var response = new ValidationResult();

            var existingRole = Context.Roles.Include(r => r.RoleMembers).FirstOrDefault(r => r.RoleId == requestModel.RoleId);

            if (existingRole == null)
            {
                response.InValidate("", "The role does not exist");
                return(response);
            }

            if (existingRole.RoleMembers.FirstOrDefault(r => r.Username.ToUpper() == requestModel.Username.ToUpper()) != null)
            {
                response.InValidate("", "The rolemember already exists");
                return(response);
            }

            var rolemember = new RoleMember
            {
                RoleId     = requestModel.RoleId,
                Username   = requestModel.Username,
                CreateDate = DateTime.Now,
                CreateUser = requestModel.CreateUser
            };

            existingRole.RoleMembers.Add(rolemember);
            Context.SaveChanges();

            return(response);
        }
예제 #4
0
        /// <summary>
        /// Adds new roleMmber to the database
        /// </summary>
        /// <param name="roleMember">RoleMmber information to be added. Instance of <see cref="RoleMemberDomain"/></param>
        /// <returns>RoleMemberID of the newly created module</returns>
        public int Add(RoleMemberDomain roleMember)
        {
            var roleMemberDb = new RoleMember().FromDomainModel(roleMember);

            _context.RoleMember.Add(roleMemberDb);
            _context.SaveChanges();
            return(roleMemberDb.RoleMemberId);
        }
예제 #5
0
        public void MemberAddRole(int memberId, int roleId)
        {
            RoleMember roleMember = new RoleMember()
            {
                RoleId   = roleId,
                MemberId = memberId
            };

            srv.Create(roleMember);
        }
예제 #6
0
        public static RoleMember CreateRoleMember(SecurityContext context, Role role, string username)
        {
            var roleMember = new RoleMember {
                Username = username, RoleId = role.RoleId, CreateDate = DateTime.Now, CreateUser = "******"
            };

            role.RoleMembers.Add(roleMember);

            context.SaveChanges();

            return(roleMember);
        }
예제 #7
0
 public static RoleMemberDomain ToDomainModel(this RoleMember obj)
 {
     return(obj == null ? null : new RoleMemberDomain()
     {
         Id = obj.RoleMemberId,
         UserId = obj.UserInfoId,
         RoleId = obj.RoleId,
         IsActive = obj.IsActive,
         TenantId = obj.TenantId,
         UserTenantId = obj.UserInfo.TenantId,
         Name = obj.Role.Name
     });
 }
예제 #8
0
        private bool AddProfileExpressionRoleMemberSync(string scenario)
        {
            HandleType srvHandle = new HandleType();

            srvHandle.ForeignId = "MyProfile";
            srvHandle.Id        = "0";
            srvHandle.Type      = ServiceName.Profile;
            if (NSMessageHandler.MSNTicket != MSNTicket.Empty)
            {
                MsnServiceState       serviceState   = new MsnServiceState(scenario, "AddMember", false);
                SharingServiceBinding sharingService = (SharingServiceBinding)CreateService(MsnServiceType.Sharing, serviceState);

                AddMemberRequestType addMemberRequest = new AddMemberRequestType();

                addMemberRequest.serviceHandle = srvHandle;

                Membership memberShip = new Membership();
                memberShip.MemberRole = RoleId.ProfileExpression;
                RoleMember roleMember = new RoleMember();
                roleMember.Type  = "Role";
                roleMember.Id    = RoleId.Allow;
                roleMember.State = MemberState.Accepted;
                roleMember.MaxRoleRecursionDepth = "0";
                roleMember.MaxDegreesSeparation  = "0";

                HandleType defService = new HandleType();
                defService.ForeignId = "";
                defService.Id        = "0";
                defService.Type      = ServiceName.Messenger;

                roleMember.DefiningService   = defService;
                memberShip.Members           = new RoleMember[] { roleMember };
                addMemberRequest.memberships = new Membership[] { memberShip };
                try
                {
                    ChangeCacheKeyAndPreferredHostForSpecifiedMethod(sharingService, MsnServiceType.Sharing, serviceState, addMemberRequest);
                    sharingService.AddMember(addMemberRequest);
                }
                catch (Exception ex)
                {
                    OnServiceOperationFailed(sharingService, new ServiceOperationFailedEventArgs("ShareItem", ex));
                    Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "AddMember error: " + ex.Message, GetType().Name);
                    return(false);
                }

                return(true);
            }

            return(false);
        }
예제 #9
0
        public static RoleMember FromDomainModel(this RoleMember obj, RoleMemberDomain roleMemberDomain)
        {
            if (obj == null)
            {
                obj = new RoleMember();
            }

            obj.RoleMemberId = roleMemberDomain.Id;
            obj.UserInfoId   = roleMemberDomain.UserId;
            obj.RoleId       = roleMemberDomain.RoleId;
            obj.IsActive     = roleMemberDomain.IsActive;
            obj.TenantId     = roleMemberDomain.TenantId;
            return(obj);
        }
예제 #10
0
        public async Task <IActionResult> RoleDetails(RoleMember roleMember)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    _repository.AddNewRole(Mapper.Map <models.RoleMember>(roleMember));
                    if (await _repository.SaveChangesAsyn())
                    {
                        ModelState.Clear();
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", "something wrong happend with db connection");
                    _logger.LogError($"cannot add RoleDetails: {ex.Message}");
                }
            }

            return(View());
        }
예제 #11
0
        public override ActionResult Delete()
        {
            StrObjectDict      reqParam = GetParams();
            string             roleID   = reqParam.GetString("RoleID");
            IList <RoleMember> list     = new List <RoleMember>();


            List <Object> userIDs = ((Object[])reqParam.GetObject("UserIDs")).ToList();

            foreach (var item in userIDs)
            {
                RoleMember rm = new RoleMember()
                {
                    RoleID = roleID,
                    UserID = item.ToString()
                };
                list.Add(rm);
            }
            var result = RoleManager.Instance.DeleteBatchs(list);

            return(this.MyJson(1, result));
        }
예제 #12
0
        public ActionResult Edit(EditUserViewModel vm)
        {
            var selectedUser = _userRepository.Get(vm.Id, "Person");

            if (selectedUser != null)
            {
                selectedUser.EmployeeCode                = vm.EmployeeCode;
                selectedUser.Person.FirstName            = vm.Person.FirstName;
                selectedUser.Person.MiddleName           = vm.Person.MiddleName;
                selectedUser.Person.LastName             = vm.Person.LastName;
                selectedUser.Person.Gender               = vm.Person.Gender;
                selectedUser.Person.Email                = vm.Person.Email;
                selectedUser.Person.PhoneNo              = vm.Person.PhoneNo;
                selectedUser.Person.SecondaryEmail       = vm.Person.SecondaryEmail;
                selectedUser.Person.Address              = vm.Person.Address;
                selectedUser.Person.CommunicationAddress = vm.Person.CommunicationAddress;
                selectedUser.Person.PassportNo           = vm.Person.PassportNo;
                selectedUser.Person.DateOfBirth          = vm.Person.DateOfBirth;
                selectedUser.Person.BloodGroup           = vm.Person.BloodGroup;
                selectedUser.Person.MaritalStatus        = vm.Person.MaritalStatus;
                selectedUser.Person.MarriageAnniversary  = vm.Person.MarriageAnniversary;
                selectedUser.DepartmentId                = vm.DepartmentId;
                selectedUser.LocationId          = vm.LocationId;
                selectedUser.DesignationId       = vm.DesignationId;
                selectedUser.ShiftId             = vm.ShiftId;
                selectedUser.ReportingPersonId   = vm.ReportingPersonId;
                selectedUser.ManagerId           = vm.ManagerId;
                selectedUser.Experience          = vm.Experience;
                selectedUser.DateOfJoin          = vm.DateOfJoin;
                selectedUser.ConfirmationDate    = vm.ConfirmationDate;
                selectedUser.DateOfResignation   = vm.DateOfResignation;
                selectedUser.LastDate            = vm.LastDate;
                selectedUser.OfficialEmail       = vm.OfficialEmail;
                selectedUser.OfficialPhone       = vm.OfficialPhone;
                selectedUser.OfficialMessengerId = vm.OfficialMessengerId;
                selectedUser.EmployeeStatus      = vm.EmployeeStatus;
                selectedUser.RequiresTimeSheet   = vm.RequiresTimeSheet;
                selectedUser.Salary            = vm.Salary;
                selectedUser.Bank              = vm.Bank;
                selectedUser.BankAccountNumber = vm.BankAccountNumber;
                selectedUser.PANCard           = vm.PANCard;
                selectedUser.PaymentMode       = vm.PaymentMode;

                _userRepository.Update(selectedUser);
                _unitOfWork.Commit();

                // Remove the existing mapped Roles
                var existingRoles = _roleMemberRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                foreach (var map in existingRoles)
                {
                    _roleMemberRepository.Delete(map);
                }

                if (vm.RoleIds != null)
                {
                    //  Map the New Technologies
                    foreach (var roleId in vm.RoleIds)
                    {
                        var newMap = new RoleMember
                        {
                            UserId = vm.Id,
                            RoleId = roleId
                        };

                        _roleMemberRepository.Create(newMap);
                    }

                    _unitOfWork.Commit();
                }

                // Remove the existing mapped Technologies
                var existingMaps = _userTechnologyMapRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                foreach (var map in existingMaps)
                {
                    _userTechnologyMapRepository.Delete(map);
                }

                _unitOfWork.Commit();

                if (vm.TechnologyIds != null)
                {
                    // Map the New Technologies
                    foreach (var technologyId in vm.TechnologyIds)
                    {
                        var newMap = new UserTechnologyMap
                        {
                            UserId       = vm.Id,
                            TechnologyId = technologyId
                        };

                        _userTechnologyMapRepository.Create(newMap);
                    }

                    _unitOfWork.Commit();
                }


                // Remove the existing mapped Skills
                var existingSkillMaps = _userSkillRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                foreach (var map in existingSkillMaps)
                {
                    _userSkillRepository.Delete(map);
                }

                _unitOfWork.Commit();

                if (vm.SkillIds != null)
                {
                    // Map the New Technologies
                    foreach (var skillId in vm.SkillIds)
                    {
                        var newMap = new UserSkill
                        {
                            UserId  = vm.Id,
                            SkillId = skillId
                        };

                        _userSkillRepository.Create(newMap);
                    }

                    _unitOfWork.Commit();
                }

                // Remove the existing mapped Skills
                var existingHobbyMaps = _userHobbyRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                foreach (var map in existingHobbyMaps)
                {
                    _userHobbyRepository.Delete(map);
                }

                _unitOfWork.Commit();

                if (vm.HobbiesId != null)
                {
                    // Map the New Technologies
                    foreach (var hobbyId in vm.HobbiesId)
                    {
                        var newMap = new UserHobby
                        {
                            UserId  = vm.Id,
                            HobbyId = hobbyId
                        };

                        _userHobbyRepository.Create(newMap);
                    }

                    _unitOfWork.Commit();
                }

                // Remove the existing mapped Certifications
                var existingCertificationMaps = _userCertificationRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                foreach (var map in existingCertificationMaps)
                {
                    _userCertificationRepository.Delete(map);
                }

                _unitOfWork.Commit();

                if (vm.CertificationIds != null)
                {
                    // Map the New Technologies
                    foreach (var certificateId in vm.CertificationIds)
                    {
                        var newMap = new UserCertification
                        {
                            UserId          = vm.Id,
                            CertificationId = certificateId
                        };

                        _userCertificationRepository.Create(newMap);
                    }

                    _unitOfWork.Commit();
                }

                return(RedirectToAction("Index"));
            }

            var allErrors = ModelState.Values.SelectMany(v => v.Errors);

            ViewBag.Roles             = new MultiSelectList(_roleRepository.GetAll(), "Id", "Name", vm.RoleIds);
            ViewBag.DepartmentId      = new SelectList(_departmentRepository.GetAll(), "Id", "Title", vm.DepartmentId);
            ViewBag.DesignationId     = new SelectList(_designationRepository.GetAllBy(d => d.DepartmentId == vm.DepartmentId), "Id", "Title", vm.DesignationId);
            ViewBag.LocationId        = new SelectList(_locationRepository.GetAll(), "Id", "Title", vm.LocationId);
            ViewBag.ReportingPersonId = new SelectList(_userRepository.GetAllBy(u => u.EmployeeStatus != EmployeeStatus.Ex && u.Id != 1, "Person"), "Id", "Person.Name", vm.ReportingPersonId);
            ViewBag.ManagerId         = new SelectList(_userRepository.GetAllBy(u => u.EmployeeStatus != EmployeeStatus.Ex && u.Id != 1, "Person"), "Id", "Person.Name", vm.ManagerId);
            ViewBag.ShiftId           = new SelectList(_shiftRepository.GetAll(), "Id", "Title", vm.ShiftId);
            return(View(vm));
        }
예제 #13
0
        public void Seed(DumaContext context)
        {
            //TODO: First variables.

            //var member = new Member
            //{
            //    Name = "Lesha",
            //    Surname = "Yurchak",
            //    Patronymic = "Vladimirovich",
            //    PassportData = "MP"
            //};

            //context.Members.Add(member);
            //context.SaveChanges();

            //var commission = new Commission {Name = "Hello", President = member};
            //context.Commissions.Add(commission);

            //var roleCom = new RoleCommission {Value = "Commandor"};
            //context.RoleCommissions.Add(roleCom);

            //context.SaveChanges();
            //commission.Consist.Add(member);


            //var record = new JournalRecord
            //{
            //    EntryDate = DateTime.Now,
            //    ExitDate = DateTime.Now.AddDays(3),
            //    Member = member,
            //    Commission = commission,
            //    Role = roleCom
            //};

            //commission.JournalRecords.Add(record);

            //context.SaveChanges();

            var role1 = new RoleMember {
                Value = "Инженер"
            };
            var role2 = new RoleMember {
                Value = "Депутат"
            };
            var role3 = new RoleMember {
                Value = "Уборщик"
            };
            var role4 = new RoleMember {
                Value = "Менеджер"
            };
            var role5 = new RoleMember {
                Value = "Охранник"
            };
            var role6 = new RoleMember {
                Value = "Бухгалтер"
            };
            var role7 = new RoleMember {
                Value = "Администратор"
            };

            context.RoleMembers.Add(role1);
            context.RoleMembers.Add(role2);
            context.RoleMembers.Add(role3);
            context.RoleMembers.Add(role4);
            context.RoleMembers.Add(role5);
            context.RoleMembers.Add(role6);
            context.RoleMembers.Add(role7);

            context.SaveChanges();

            var profiles = new List <ProfileCommission>()
            {
                new ProfileCommission {
                    Description = "По аграрным вопросам"
                },
                new ProfileCommission {
                    Description = "По обороне"
                },
                new ProfileCommission {
                    Description = "По физической культуре, спорту и делам молодежи"
                },
                new ProfileCommission {
                    Description = "По науке и наукоемким технологиям"
                },
                new ProfileCommission {
                    Description = "По образованию"
                },
                new ProfileCommission {
                    Description = "По транспорту"
                },
                new ProfileCommission {
                    Description = "По охране здоровья"
                },
                new ProfileCommission {
                    Description = "По промышленности"
                },
                new ProfileCommission {
                    Description = "По жилищной политике и жилищно-коммунальному хозяйству"
                },
                new ProfileCommission {
                    Description = "По культуре"
                },
                new ProfileCommission {
                    Description = "По энергетике"
                },
                new ProfileCommission {
                    Description = "По безопасности и противодействию коррупции"
                },
                new ProfileCommission {
                    Description = "По делам национальностей"
                },
                new ProfileCommission {
                    Description = "По вопросам семьи, женщин и детей"
                },
                new ProfileCommission {
                    Description = "По земельным отношениям и строительству"
                },
                new ProfileCommission {
                    Description = "По природным ресурсам, природопользованию и экологии"
                },
            };

            profiles.ForEach(e => context.ProfileCommissions.Add(e));

            var presidentRole = new RoleCommission {
                Value = "Президент"
            };
            var memberRole = new RoleCommission {
                Value = "Член"
            };

            context.RoleCommissions.Add(presidentRole);
            context.RoleCommissions.Add(memberRole);

            context.SaveChanges();
        }
예제 #14
0
        public override bool Execute(ProgramOptions programOptions)
        {
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();

            StepTiming stepTimingFunction = new StepTiming();

            stepTimingFunction.JobFileName = programOptions.ReportJobFilePath;
            stepTimingFunction.StepName    = programOptions.ReportJob.Status.ToString();
            stepTimingFunction.StepID      = (int)programOptions.ReportJob.Status;
            stepTimingFunction.StartTime   = DateTime.Now;
            stepTimingFunction.NumEntities = 0;

            this.DisplayJobStepStartingStatus(programOptions);

            this.FilePathMap = new FilePathMap(programOptions);

            try
            {
                FileIOHelper.CreateFolder(this.FilePathMap.Data_FolderPath());
                FileIOHelper.CreateFolder(this.FilePathMap.Data_Role_FolderPath());

                FileIOHelper.CreateFolder(this.FilePathMap.Report_FolderPath());
                FileIOHelper.CreateFolder(this.FilePathMap.Report_Grant_FolderPath());
                FileIOHelper.CreateFolder(this.FilePathMap.Report_Role_FolderPath());

                #region Grants ON and Grants TO grants for everything

                loggerConsole.Info("Process Grants ON and TO");

                List <RoleMember> grantsOfRolesList = new List <RoleMember>();

                List <Grant> grantsOnRolesList = FileIOHelper.ReadListFromCSVFile <Grant>(FilePathMap.Input_RoleShowGrantsToAndOn_FilePath(), new GrantGrantToRolesMap(), new string[] { "Initiating login request with your identity provider" });

                if (grantsOnRolesList != null)
                {
                    loggerConsole.Info("Loaded {0} ON and TO grants", grantsOnRolesList.Count);

                    // Unescape special names of objects
                    foreach (Grant grant in grantsOnRolesList)
                    {
                        grant.GrantedTo = grant.GrantedTo.Trim('"');
                        grant.GrantedBy = grant.GrantedBy.Trim('"');
                        // Apparently the ACCOUNT_USAGE casts 'NOTIFICATION_SUBSCRIPTION' to 'NOTIFICATION SUBSCRIPTION'
                        // And for others that have space
                        if (grant.ObjectType.Contains(' ') == true)
                        {
                            grant.ObjectType = grant.ObjectType.Replace(' ', '_');
                        }

                        // Escape periods
                        if (grant.EntityName.Contains('.') == true)
                        {
                            grant.EntityName = String.Format("\"{0}\"", grant.EntityName);
                        }
                        if (grant.DBName.Contains('.') == true)
                        {
                            grant.DBName = String.Format("\"{0}\"", grant.DBName);
                        }
                        if (grant.SchemaName.Contains('.') == true)
                        {
                            grant.SchemaName = String.Format("\"{0}\"", grant.SchemaName);
                        }
                        // Come up with ObjectName from combination of EntityName, etc.
                        if (grant.DBName.Length == 0)
                        {
                            // Account level object
                            grant.ObjectName = grant.EntityName;
                        }
                        else
                        {
                            if (grant.SchemaName.Length == 0)
                            {
                                // DATABASE
                                grant.ObjectName = grant.EntityName;
                                grant.DBName     = grant.EntityName;
                            }
                            else
                            {
                                if (grant.ObjectType == "SCHEMA")
                                {
                                    grant.ObjectName = String.Format("{0}.{1}", grant.DBName, grant.EntityName);
                                }
                                else
                                {
                                    grant.ObjectName = String.Format("{0}.{1}.{2}", grant.DBName, grant.SchemaName, grant.EntityName);
                                }
                            }
                        }
                    }

                    grantsOnRolesList.RemoveAll(g => g.DeletedOn.HasValue == true);

                    grantsOnRolesList = grantsOnRolesList.OrderBy(g => g.ObjectType).ThenBy(g => g.ObjectName).ThenBy(g => g.GrantedTo).ToList();
                    FileIOHelper.WriteListToCSVFile <Grant>(grantsOnRolesList, new GrantMap(), FilePathMap.Report_RoleGrant_FilePath());

                    List <Grant> roleUsageGrantsList = grantsOnRolesList.Where(g => g.ObjectType == "ROLE" && g.Privilege == "USAGE").ToList();
                    if (roleUsageGrantsList != null)
                    {
                        foreach (Grant grant in roleUsageGrantsList)
                        {
                            RoleMember roleMember = new RoleMember();
                            roleMember.CreatedOn  = grant.CreatedOn;
                            roleMember.Name       = grant.ObjectName;
                            roleMember.GrantedBy  = grant.GrantedBy;
                            roleMember.GrantedTo  = grant.GrantedTo;
                            roleMember.ObjectType = grant.ObjectType;

                            grantsOfRolesList.Add(roleMember);
                        }

                        grantsOfRolesList = grantsOfRolesList.OrderBy(g => g.Name).ToList();
                    }

                    #region Individual Object Types

                    loggerConsole.Info("Processing individual Object Types");

                    // Break them up by the type
                    var groupObjectTypesGrouped            = grantsOnRolesList.GroupBy(g => g.ObjectType);
                    List <SingleStringRow> objectTypesList = new List <SingleStringRow>(groupObjectTypesGrouped.Count());
                    foreach (var group in groupObjectTypesGrouped)
                    {
                        loggerConsole.Info("Processing grants for {0}", group.Key);

                        SingleStringRow objectType = new SingleStringRow();
                        objectType.Value = group.Key;
                        objectTypesList.Add(objectType);

                        #region Save this set of grants for Object Type

                        List <Grant> grantsOfObjectTypeList = group.ToList();

                        // Save this set as is for one of the tables in report
                        FileIOHelper.WriteListToCSVFile <Grant>(grantsOfObjectTypeList, new GrantMap(), FilePathMap.Report_RoleGrant_ObjectType_FilePath(group.Key));

                        // Pivot each section into this kind of table
                        //
                        // ObjectType | ObjectName | GrantedTo | OWNERSHIP | USAGE | REFERENCE | GrantN
                        // DATABASE   | SomeDB     | SomeRole  | X         | x+    |           |
                        // Where X+ means WithGrantOption=True
                        //       X  means WithGrantOption=False
                        List <ObjectTypeGrant>   objectGrantsList            = new List <ObjectTypeGrant>(grantsOfObjectTypeList.Count / 5);
                        Dictionary <string, int> privilegeToColumnDictionary = new Dictionary <string, int>(20);

                        #endregion

                        #region Convert this set into pivot

                        List <string> listOfPrivileges = grantsOfObjectTypeList.Select(g => g.Privilege).Distinct().OrderBy(g => g).ToList();

                        // Make USAGE and OWNERSHIP be the first columns
                        switch (group.Key)
                        {
                        case "ACCOUNT":
                            break;

                        case "DATABASE":
                        case "FILE_FORMAT":
                        case "FUNCTION":
                        case "INTEGRATION":
                        case "PROCEDURE":
                        case "ROLE":
                        case "SCHEMA":
                        case "SEQUENCE":
                        case "WAREHOUSE":
                            listOfPrivileges.Remove("OWNERSHIP");
                            listOfPrivileges.Insert(0, "OWNERSHIP");
                            listOfPrivileges.Remove("USAGE");
                            listOfPrivileges.Insert(1, "USAGE");
                            break;

                        case "EXTERNAL_TABLE":
                        case "MANAGED_ACCOUNT":
                        case "MASKING_POLICY":
                        case "MATERIALIZED_VIEW":
                        case "NETWORK_POLICY":
                        case "NOTIFICATION_SUBSCRIPTION":
                        case "PIPE":
                        case "RESOURCE_MONITOR":
                        case "SHARE":
                        case "STAGE":
                        case "STREAM":
                        case "TABLE":
                        case "TASK":
                        case "USER":
                        case "VIEW":
                            listOfPrivileges.Remove("OWNERSHIP");
                            listOfPrivileges.Insert(0, "OWNERSHIP");
                            break;

                        default:
                            break;
                        }
                        for (int i = 0; i < listOfPrivileges.Count; i++)
                        {
                            privilegeToColumnDictionary.Add(listOfPrivileges[i], i);
                        }

                        ObjectTypeGrant latestGrantRow = new ObjectTypeGrant();
                        foreach (Grant grant in grantsOfObjectTypeList)
                        {
                            // Loop through rows, starting new objects for each combination of ObjectType+ObjectName+GrantedTo when necessary
                            // ObjectType is always the same in this grouping
                            // ObjectName
                            if (latestGrantRow.ObjectType != grant.ObjectType ||
                                latestGrantRow.ObjectName != grant.ObjectName ||
                                latestGrantRow.GrantedTo != grant.GrantedTo)
                            {
                                // Need to start new row
                                latestGrantRow            = new ObjectTypeGrant();
                                latestGrantRow.ObjectType = grant.ObjectType;
                                latestGrantRow.ObjectName = grant.ObjectName;
                                latestGrantRow.DBName     = grant.DBName;
                                latestGrantRow.SchemaName = grant.SchemaName;
                                latestGrantRow.EntityName = grant.EntityName;
                                latestGrantRow.GrantedTo  = grant.GrantedTo;

                                objectGrantsList.Add(latestGrantRow);
                            }

                            // Find out which column to use
                            int privilegeColumnNumber = privilegeToColumnDictionary[grant.Privilege];

                            switch (privilegeColumnNumber)
                            {
                            case 0:
                                latestGrantRow.Privilege0 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 1:
                                latestGrantRow.Privilege1 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 2:
                                latestGrantRow.Privilege2 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 3:
                                latestGrantRow.Privilege3 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 4:
                                latestGrantRow.Privilege4 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 5:
                                latestGrantRow.Privilege5 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 6:
                                latestGrantRow.Privilege6 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 7:
                                latestGrantRow.Privilege7 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 8:
                                latestGrantRow.Privilege8 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 9:
                                latestGrantRow.Privilege9 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 10:
                                latestGrantRow.Privilege10 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 11:
                                latestGrantRow.Privilege11 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 12:
                                latestGrantRow.Privilege12 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 13:
                                latestGrantRow.Privilege13 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 14:
                                latestGrantRow.Privilege14 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 15:
                                latestGrantRow.Privilege15 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 16:
                                latestGrantRow.Privilege16 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 17:
                                latestGrantRow.Privilege17 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 18:
                                latestGrantRow.Privilege18 = grant.DisplaySettingWithGrantOption;
                                break;

                            case 19:
                                latestGrantRow.Privilege19 = grant.DisplaySettingWithGrantOption;
                                break;

                            default:
                                // Can't fit more than 20 privileges
                                logger.Warn("More then 20 Privileges reached with {0} privilege for object type {1}", grant.Privilege, grant.ObjectType);
                                break;
                            }
                        }

                        List <string> privilegeColumnNames = new List <string>(privilegeToColumnDictionary.Count);
                        for (int i = 0; i < privilegeToColumnDictionary.Count; i++)
                        {
                            privilegeColumnNames.Add(String.Empty);
                        }
                        foreach (var entry in privilegeToColumnDictionary)
                        {
                            privilegeColumnNames[entry.Value] = entry.Key;
                        }

                        // Save the pivot
                        FileIOHelper.WriteListToCSVFile <ObjectTypeGrant>(objectGrantsList, new ObjectTypeGrantMap(privilegeColumnNames), FilePathMap.Report_RoleGrant_ObjectType_Pivoted_FilePath(group.Key));

                        #endregion
                    }

                    FileIOHelper.WriteListToCSVFile <SingleStringRow>(objectTypesList, new SingleStringRowMap(), FilePathMap.Report_RoleGrant_ObjectTypes_FilePath());

                    #endregion
                }

                #endregion


                #region Grants OF - Members of Roles (Roles and Users)

                loggerConsole.Info("Process Grants OF Users");

                List <RoleMember> grantsOfUsersList = FileIOHelper.ReadListFromCSVFile <RoleMember>(FilePathMap.Input_RoleShowGrantsOf_FilePath(), new RoleMemberGrantsToUsersMap(), new string[] { "Initiating login request with your identity provider" });
                if (grantsOfUsersList != null)
                {
                    foreach (RoleMember roleMember in grantsOfUsersList)
                    {
                        // Unescape special names of roles
                        roleMember.Name      = roleMember.Name.Trim('"');
                        roleMember.GrantedTo = roleMember.GrantedTo.Trim('"');
                        roleMember.GrantedBy = roleMember.GrantedBy.Trim('"');
                    }

                    // Remove deleted items
                    grantsOfUsersList.RemoveAll(g => g.DeletedOn.HasValue == true);

                    grantsOfUsersList = grantsOfUsersList.OrderBy(g => g.Name).ToList();

                    List <RoleMember> grantsOfRolesAndUsersList = new List <RoleMember>();
                    grantsOfRolesAndUsersList.AddRange(grantsOfRolesList);
                    grantsOfRolesAndUsersList.AddRange(grantsOfUsersList);

                    FileIOHelper.WriteListToCSVFile <RoleMember>(grantsOfRolesAndUsersList, new RoleMemberMap(), FilePathMap.Report_RoleMember_FilePath());
                }

                #endregion

                // Come up with roles list for later steps too
                if (grantsOnRolesList == null)
                {
                    grantsOnRolesList = new List <Grant>();
                }

                List <Role>   rolesList = new List <Role>();
                List <string> rolesInThisAccountList = grantsOnRolesList.Where(g => g.ObjectType == "ROLE").Select(g => g.ObjectName).Distinct().ToList();
                foreach (string roleName in rolesInThisAccountList)
                {
                    Role role = new Role();
                    role.CreatedOn = DateTime.Now;
                    role.Name      = roleName;

                    rolesList.Add(role);
                }

                if (rolesList.Where(r => r.Name == "ACCOUNTADMIN").Count() == 0)
                {
                    Role role = new Role();
                    role.CreatedOn = DateTime.Now;
                    role.Name      = "ACCOUNTADMIN";

                    rolesList.Add(role);
                }

                if (rolesList.Where(r => r.Name == "PUBLIC").Count() == 0)
                {
                    Role role = new Role();
                    role.CreatedOn = DateTime.Now;
                    role.Name      = "PUBLIC";

                    rolesList.Add(role);
                }

                FileIOHelper.WriteListToCSVFile <Role>(rolesList, new RoleShowRolesMap(), FilePathMap.Data_ShowRoles_FilePath());

                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                loggerConsole.Error(ex);

                return(false);
            }
            finally
            {
                stopWatch.Stop();

                this.DisplayJobStepEndedStatus(programOptions, stopWatch);

                stepTimingFunction.EndTime    = DateTime.Now;
                stepTimingFunction.Duration   = stopWatch.Elapsed;
                stepTimingFunction.DurationMS = stopWatch.ElapsedMilliseconds;

                List <StepTiming> stepTimings = new List <StepTiming>(1);
                stepTimings.Add(stepTimingFunction);
                FileIOHelper.WriteListToCSVFile(stepTimings, new StepTimingReportMap(), FilePathMap.StepTimingReportFilePath(), true);
            }
        }
예제 #15
0
 public EntityEntry <RoleMember> AddNewRole(RoleMember newRoleMember)
 {
     return(_context.Add(newRoleMember));
 }
예제 #16
0
        public ActionResult Update(NewUserViewModel vm)
        {
            ApiResult <User> apiResult;

            if (ModelState.IsValid)
            {
                if (vm.Id > 0)
                {
                    apiResult = TryExecute(() =>
                    {
                        var selectedUser                         = _userRepository.Get(vm.Id, "Person");
                        selectedUser.EmployeeCode                = vm.EmployeeCode;
                        selectedUser.Person.FirstName            = vm.Person.FirstName;
                        selectedUser.Person.MiddleName           = vm.Person.MiddleName;
                        selectedUser.Person.LastName             = vm.Person.LastName;
                        selectedUser.Person.Gender               = vm.Person.Gender;
                        selectedUser.Person.Email                = vm.Person.Email;
                        selectedUser.Person.PhoneNo              = vm.Person.PhoneNo;
                        selectedUser.Person.SecondaryEmail       = vm.Person.SecondaryEmail;
                        selectedUser.Person.Address              = vm.Person.Address;
                        selectedUser.Person.CommunicationAddress = vm.Person.CommunicationAddress;
                        selectedUser.Person.PassportNo           = vm.Person.PassportNo;
                        selectedUser.Person.DateOfBirth          = vm.Person.DateOfBirth;
                        selectedUser.Person.BloodGroup           = vm.Person.BloodGroup;
                        selectedUser.Person.MaritalStatus        = vm.Person.MaritalStatus;
                        selectedUser.Person.MarriageAnniversary  = vm.Person.MarriageAnniversary;
                        selectedUser.DepartmentId                = vm.DepartmentId;
                        selectedUser.LocationId                  = vm.LocationId;
                        selectedUser.DesignationId               = vm.DesignationId;
                        selectedUser.ShiftId                     = vm.ShiftId;
                        selectedUser.ReportingPersonId           = vm.ReportingPersonId;
                        selectedUser.Experience                  = vm.Experience;
                        selectedUser.DateOfJoin                  = vm.DateOfJoin;
                        selectedUser.ConfirmationDate            = vm.ConfirmationDate;
                        selectedUser.DateOfResignation           = vm.DateOfResignation;
                        selectedUser.LastDate                    = vm.LastDate;
                        selectedUser.OfficialEmail               = vm.OfficialEmail;
                        selectedUser.OfficialPhone               = vm.OfficialPhone;
                        selectedUser.OfficialMessengerId         = vm.OfficialMessengerId;
                        selectedUser.EmployeeStatus              = vm.EmployeeStatus;
                        selectedUser.RequiresTimeSheet           = vm.RequiresTimeSheet;
                        selectedUser.Salary                      = vm.Salary;
                        selectedUser.Bank                        = vm.Bank;
                        selectedUser.BankAccountNumber           = vm.BankAccountNumber;
                        selectedUser.PANCard                     = vm.PANCard;
                        selectedUser.PaymentMode                 = vm.PaymentMode;

                        _userRepository.Update(selectedUser);
                        _unitOfWork.Commit();

                        // Remove the existing mapped Roles
                        var existingRoles = _roleMemberRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                        foreach (var map in existingRoles)
                        {
                            _roleMemberRepository.Delete(map);
                        }

                        if (vm.RoleIds != null)
                        {
                            // Map the New Technologies
                            foreach (var roleId in vm.RoleIds)
                            {
                                var newMap = new RoleMember
                                {
                                    UserId = vm.Id,
                                    RoleId = roleId
                                };

                                _roleMemberRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }

                        // Remove the existing mapped Technologies
                        var existingMaps = _userTechnologyMapRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                        foreach (var map in existingMaps)
                        {
                            _userTechnologyMapRepository.Delete(map);
                        }

                        _unitOfWork.Commit();

                        if (vm.TechnologyIds != null)
                        {
                            // Map the New Technologies
                            foreach (var technologyId in vm.TechnologyIds)
                            {
                                var newMap = new UserTechnologyMap
                                {
                                    UserId       = vm.Id,
                                    TechnologyId = technologyId
                                };

                                _userTechnologyMapRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }


                        // Remove the existing mapped Skills
                        var existingSkillMaps = _userSkillRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                        foreach (var map in existingSkillMaps)
                        {
                            _userSkillRepository.Delete(map);
                        }

                        _unitOfWork.Commit();

                        if (vm.SkillIds != null)
                        {
                            // Map the New Technologies
                            foreach (var skillId in vm.SkillIds)
                            {
                                var newMap = new UserSkill
                                {
                                    UserId  = vm.Id,
                                    SkillId = skillId
                                };

                                _userSkillRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }

                        // Remove the existing mapped Skills
                        var existingHobbyMaps = _userHobbyRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                        foreach (var map in existingHobbyMaps)
                        {
                            _userHobbyRepository.Delete(map);
                        }

                        _unitOfWork.Commit();

                        if (vm.HobbiesId != null)
                        {
                            // Map the New Technologies
                            foreach (var hobbyId in vm.HobbiesId)
                            {
                                var newMap = new UserHobby
                                {
                                    UserId  = vm.Id,
                                    HobbyId = hobbyId
                                };

                                _userHobbyRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }

                        // Remove the existing mapped Certifications
                        var existingCertificationMaps =
                            _userCertificationRepository.GetAllBy(m => m.UserId == selectedUser.Id);
                        foreach (var map in existingCertificationMaps)
                        {
                            _userCertificationRepository.Delete(map);
                        }

                        _unitOfWork.Commit();

                        if (vm.CertificationIds != null)
                        {
                            // Map the New Technologies
                            foreach (var certificateId in vm.CertificationIds)
                            {
                                var newMap = new UserCertification
                                {
                                    UserId          = vm.Id,
                                    CertificationId = certificateId
                                };

                                _userCertificationRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }

                        return(selectedUser);
                    }, "User updated sucessfully");
                }
                else
                {
                    apiResult = TryExecute(() =>
                    {
                        var newUser = new User
                        {
                            EmployeeCode        = vm.EmployeeCode,
                            Username            = vm.Username,
                            Password            = HashHelper.Hash(vm.Password),
                            AccessRule          = AccessRule.CreateNewUserAccessRule(true),
                            Person              = vm.Person,
                            DepartmentId        = vm.DepartmentId,
                            LocationId          = vm.LocationId,
                            DesignationId       = vm.DesignationId,
                            ShiftId             = vm.ShiftId,
                            ReportingPersonId   = vm.ReportingPersonId,
                            Experience          = vm.Experience,
                            DateOfJoin          = vm.DateOfJoin,
                            ConfirmationDate    = vm.ConfirmationDate,
                            DateOfResignation   = vm.DateOfResignation,
                            LastDate            = vm.LastDate,
                            OfficialEmail       = vm.OfficialEmail,
                            OfficialPhone       = vm.OfficialPhone,
                            OfficialMessengerId = vm.OfficialMessengerId,
                            EmployeeStatus      = vm.EmployeeStatus,
                            RequiresTimeSheet   = vm.RequiresTimeSheet,
                            Salary              = vm.Salary,
                            Bank = vm.Bank,
                            BankAccountNumber = vm.BankAccountNumber,
                            PANCard           = vm.PANCard,
                            PaymentMode       = vm.PaymentMode
                        };

                        _userRepository.Create(newUser);
                        _unitOfWork.Commit();

                        // Map the Technologies
                        if (vm.TechnologyIds != null)
                        {
                            foreach (var technologyId in vm.TechnologyIds)
                            {
                                var newMap = new UserTechnologyMap
                                {
                                    UserId       = newUser.Id,
                                    TechnologyId = technologyId
                                };
                                _userTechnologyMapRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }


                        // Map the Technologies
                        if (vm.RoleIds != null)
                        {
                            foreach (var roleId in vm.RoleIds)
                            {
                                var newMap = new RoleMember
                                {
                                    UserId = newUser.Id,
                                    RoleId = roleId
                                };

                                _roleMemberRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }

                        return(newUser);
                    }, "User created sucessfully");
                }
            }
            else
            {
                apiResult = ApiResultFromModelErrors <User>();
            }

            return(Json(apiResult, JsonRequestBehavior.AllowGet));
        }
예제 #17
0
 public RoleMember AddRoleParent(int roleId, RoleMember obj) => CheckResult(GetHttpClient($"Roles/{roleId}/Parents").Post <OperationResult <RoleMember> >());
예제 #18
0
 public RoleMember AddRoleParent(RoleMember obj)
 {
     return(Run(() => Add(obj), saveChanges: true));
 }
예제 #19
0
        public void MemberRemoveRole(int roleMemberId)
        {
            RoleMember roleMember = srv.Get(rm => rm.RMNum == roleMemberId);

            srv.Delete(roleMember);
        }
예제 #20
0
 public OperationResult <RoleMember> AddMember(int id, [FromBody] RoleMember obj)
 {
     obj.BaseId = id;
     return(Controller.AddRoleMember(obj));
 }
예제 #21
0
        public JsonResult Create(EmployeeModel model)
        {
            ApiResult <Employee> apiResult;

            if (ModelState.IsValid)
            {
                if (model.Id > 0)
                {
                    apiResult = TryExecute(() =>
                    {
                        var newPerson = new Person
                        {
                            Id                   = model.PersonId,
                            FirstName            = model.FirstName,
                            MiddleName           = model.MiddleName,
                            LastName             = model.LastName,
                            Gender               = model.Gender,
                            Email                = model.Email,
                            SecondaryEmail       = model.SecondaryEmail,
                            PhoneNo              = model.PhoneNo,
                            Address              = model.Address,
                            CommunicationAddress = model.CommunicationAddress,
                            PassportNo           = model.PassportNo,
                            DateOfBirth          = model.DateOfBirth,
                            BloodGroup           = model.BloodGroup,
                            MaritalStatus        = model.MaritalStatus,
                            MarriageAnniversary  = model.MarriageAnniversary,
                            PhotoPath            = model.PhotoPath
                        };

                        _personRepository.Update(newPerson);
                        var user = _userRepository.GetBy(i => i.Id == model.UserId);

                        user.Id                  = model.UserId;
                        user.PersonId            = model.PersonId;
                        user.Username            = model.Username;
                        user.EmployeeCode        = model.EmployeeCode;
                        user.DepartmentId        = model.DepartmentId;
                        user.LocationId          = model.LocationId;
                        user.DesignationId       = model.DesignationId;
                        user.ShiftId             = model.ShiftId;
                        user.Salary              = model.Salary;
                        user.Bank                = model.Bank;
                        user.BankAccountNumber   = model.BankAccountNumber;
                        user.PANCard             = model.PANCard;
                        user.PaymentMode         = model.PaymentMode;
                        user.Experience          = model.Experience;
                        user.DateOfJoin          = model.DateOfJoin;
                        user.ConfirmationDate    = model.ConfirmationDate;
                        user.DateOfResignation   = model.DateOfResignation;
                        user.LastDate            = model.LastDate;
                        user.OfficialEmail       = model.OfficialEmail;
                        user.OfficialPhone       = model.OfficialPhone;
                        user.OfficialMessengerId = model.OfficialMessengerId;
                        user.EmployeeStatus      = model.EmployeeStatus;
                        user.RequiresTimeSheet   = model.RequiresTimeSheet;
                        user.SeatNo              = model.SeatNo;
                        user.AccessRuleId        = model.AccessRuleId;


                        _userRepository.Update(user);

                        var newEmployee = new Employee
                        {
                            Id                  = model.EmployeeId,
                            UserId              = model.UserId,
                            EmployeeCode        = model.EmployeeCode,
                            DepartmentId        = model.DepartmentId,
                            LocationId          = model.LocationId,
                            DesignationId       = model.DesignationId,
                            ShiftId             = model.ShiftId,
                            Salary              = model.Salary,
                            Bank                = model.Bank,
                            BankAccountNumber   = model.BankAccountNumber,
                            PANCard             = model.PANCard,
                            PaymentMode         = model.PaymentMode,
                            ReportingPersonId   = model.ReportingPersonId,
                            ManagerId           = model.ManagerId,
                            Experience          = model.Experience,
                            DateOfJoin          = model.DateOfJoin,
                            ConfirmationDate    = model.ConfirmationDate,
                            DateOfResignation   = model.DateOfResignation,
                            LastDate            = model.LastDate,
                            OfficialEmail       = model.OfficialEmail,
                            OfficialPhone       = model.OfficialPhone,
                            OfficialMessengerId = model.OfficialMessengerId,
                            EmployeeStatus      = model.EmployeeStatus,
                            RequiresTimeSheet   = model.RequiresTimeSheet,
                            SeatNo              = model.SeatNo
                        };
                        _employeeRepository.Update(newEmployee);
                        _unitOfWork.Commit();


                        var User = _userRepository.Get(model.UserId);
                        if (User != null)
                        {
                            var reportingPerson = _employeeRepository.Get(newEmployee.ReportingPersonId.Value);
                            var manager         = _employeeRepository.Get(newEmployee.ManagerId.Value);

                            User.ReportingPersonId = reportingPerson.UserId;
                            User.ManagerId         = manager.UserId;

                            _userRepository.Update(User);
                            _unitOfWork.Commit();
                        }

                        // Remove the existing mapped Roles
                        var existingRoles = _roleMemberRepository.GetAllBy(m => m.UserId == user.Id);
                        foreach (var map in existingRoles)
                        {
                            _roleMemberRepository.Delete(map);
                        }

                        if (model.RoleIds != null)
                        {
                            // Map the New Technologies
                            foreach (var roleId in model.RoleIds)
                            {
                                var newMap = new RoleMember
                                {
                                    UserId = model.UserId,
                                    RoleId = roleId
                                };

                                _roleMemberRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }

                        // Remove the existing mapped Technologies
                        var existingMaps = _userTechnologyMapRepository.GetAllBy(m => m.UserId == model.UserId);
                        foreach (var map in existingMaps)
                        {
                            _userTechnologyMapRepository.Delete(map);
                        }

                        _unitOfWork.Commit();

                        if (model.TechnologyIds != null)
                        {
                            // Map the New Technologies
                            foreach (var technologyId in model.TechnologyIds)
                            {
                                var newMap = new UserTechnologyMap
                                {
                                    UserId       = model.UserId,
                                    TechnologyId = technologyId
                                };

                                _userTechnologyMapRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }

                        return(newEmployee);
                    }, "Employee updated sucessfully");
                }
                else
                {
                    apiResult = TryExecute(() =>
                    {
                        var newPerson = new Person
                        {
                            FirstName            = model.FirstName,
                            MiddleName           = model.MiddleName,
                            LastName             = model.LastName,
                            Gender               = model.Gender,
                            Email                = model.Email,
                            SecondaryEmail       = model.SecondaryEmail,
                            PhoneNo              = model.PhoneNo,
                            Address              = model.Address,
                            CommunicationAddress = model.CommunicationAddress,
                            PassportNo           = model.PassportNo,
                            DateOfBirth          = model.DateOfBirth,
                            BloodGroup           = model.BloodGroup,
                            MaritalStatus        = model.MaritalStatus,
                            MarriageAnniversary  = model.MarriageAnniversary,
                            PhotoPath            = model.PhotoPath
                        };
                        var person = _personRepository.Create(newPerson);

                        var newUser = new User
                        {
                            PersonId            = person.Id,
                            Username            = model.Username,
                            Password            = HashHelper.Hash(model.Password),
                            AccessRule          = AccessRule.CreateNewUserAccessRule(true),
                            EmployeeCode        = model.EmployeeCode,
                            DepartmentId        = model.DepartmentId,
                            LocationId          = model.LocationId,
                            DesignationId       = model.DesignationId,
                            ShiftId             = model.ShiftId,
                            Salary              = model.Salary,
                            Bank                = model.Bank,
                            BankAccountNumber   = model.BankAccountNumber,
                            PANCard             = model.PANCard,
                            PaymentMode         = model.PaymentMode,
                            Experience          = model.Experience,
                            DateOfJoin          = model.DateOfJoin,
                            ConfirmationDate    = model.ConfirmationDate,
                            DateOfResignation   = model.DateOfResignation,
                            LastDate            = model.LastDate,
                            OfficialEmail       = model.OfficialEmail,
                            OfficialPhone       = model.OfficialPhone,
                            OfficialMessengerId = model.OfficialMessengerId,
                            EmployeeStatus      = model.EmployeeStatus,
                            RequiresTimeSheet   = model.RequiresTimeSheet,
                            SeatNo              = model.SeatNo,
                        };
                        var user = _userRepository.Create(newUser);

                        var newEmployee = new Employee
                        {
                            UserId              = user.Id,
                            EmployeeCode        = model.EmployeeCode,
                            DepartmentId        = model.DepartmentId,
                            LocationId          = model.LocationId,
                            DesignationId       = model.DesignationId,
                            ShiftId             = model.ShiftId,
                            Salary              = model.Salary,
                            Bank                = model.Bank,
                            BankAccountNumber   = model.BankAccountNumber,
                            PANCard             = model.PANCard,
                            PaymentMode         = model.PaymentMode,
                            ReportingPersonId   = model.ReportingPersonId,
                            ManagerId           = model.ManagerId,
                            Experience          = model.Experience,
                            DateOfJoin          = model.DateOfJoin,
                            ConfirmationDate    = model.ConfirmationDate,
                            DateOfResignation   = model.DateOfResignation,
                            LastDate            = model.LastDate,
                            OfficialEmail       = model.OfficialEmail,
                            OfficialPhone       = model.OfficialPhone,
                            OfficialMessengerId = model.OfficialMessengerId,
                            EmployeeStatus      = model.EmployeeStatus,
                            RequiresTimeSheet   = model.RequiresTimeSheet,
                            SeatNo              = model.SeatNo
                        };
                        _employeeRepository.Create(newEmployee);
                        _unitOfWork.Commit();


                        var User = _userRepository.Get(newUser.Id);
                        if (User != null)
                        {
                            var reportingPerson = _employeeRepository.Get(newEmployee.ReportingPersonId.Value);
                            var manager         = _employeeRepository.Get(newEmployee.ManagerId.Value);

                            User.ReportingPersonId = reportingPerson.UserId;
                            User.ManagerId         = manager.UserId;

                            _userRepository.Update(User);
                            _unitOfWork.Commit();
                        }

                        // Map the Technologies
                        if (model.TechnologyIds != null)
                        {
                            foreach (var technologyId in model.TechnologyIds)
                            {
                                var newMap = new UserTechnologyMap
                                {
                                    UserId       = newUser.Id,
                                    TechnologyId = technologyId
                                };
                                _userTechnologyMapRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }

                        // Map the Roles
                        if (model.RoleIds != null)
                        {
                            foreach (var roleId in model.RoleIds)
                            {
                                var newMap = new RoleMember
                                {
                                    UserId = newUser.Id,
                                    RoleId = roleId
                                };

                                _roleMemberRepository.Create(newMap);
                            }

                            _unitOfWork.Commit();
                        }



                        return(newEmployee);
                    }, "Employee created sucessfully");
                }
            }
            else
            {
                apiResult = ApiResultFromModelErrors <Employee>();
                var data = ApiResultFromModelErrors <Employee>();
            }
            return(Json(apiResult, JsonRequestBehavior.AllowGet));
        }
예제 #22
0
        public ActionResult Seed(Tenant tenant)
        {
            var selectedTenant = db.Tenants.Find(tenant.Id);

            if (selectedTenant != null)
            {
                var connectionString = selectedTenant.ConnectionString;
                if (!string.IsNullOrEmpty(connectionString))
                {
                    using (var context = new GridDataContext(connectionString))
                    {
                        var accessRule = AccessRule.CreateNewUserAccessRule(true);
                        context.AccessRules.Add(accessRule);
                        context.SaveChanges();

                        var person = new Person();
                        context.Persons.Add(person);
                        context.SaveChanges();

                        var manageCompany = new Permission {
                            Title = "Manage Company", PermissionCode = 200
                        };
                        context.Permissions.Add(manageCompany);
                        var manageHRMS = new Permission {
                            Title = "Manage HRMS", PermissionCode = 210
                        };
                        context.Permissions.Add(manageHRMS);
                        var manageSales = new Permission {
                            Title = "Manage Sales", PermissionCode = 220
                        };
                        context.Permissions.Add(manageSales);
                        var manageIT = new Permission {
                            Title = "Manage IT", PermissionCode = 230
                        };
                        context.Permissions.Add(manageIT);
                        var managePMS = new Permission {
                            Title = "Manage PMS", PermissionCode = 240
                        };
                        context.Permissions.Add(managePMS);
                        var manageInventory = new Permission {
                            Title = "Manage Inventory", PermissionCode = 250
                        };
                        context.Permissions.Add(manageInventory);
                        var manageLMS = new Permission {
                            Title = "Manage LMS", PermissionCode = 215
                        };
                        context.Permissions.Add(manageLMS);
                        var manageTimeSheet = new Permission {
                            Title = "Manage TimeSheet", PermissionCode = 300
                        };
                        context.Permissions.Add(manageTimeSheet);
                        var manageRecruit = new Permission {
                            Title = "Manage Recruit", PermissionCode = 500
                        };
                        context.Permissions.Add(manageRecruit);
                        var superPermission = new Permission {
                            Title = "Super Permission", PermissionCode = 9999
                        };
                        context.Permissions.Add(superPermission);
                        var manageTMS = new Permission {
                            Title = "Manage TMS", PermissionCode = 550
                        };
                        context.Permissions.Add(manageTMS);
                        var manageKBS = new Permission {
                            Title = "Manage KBS", PermissionCode = 700
                        };
                        context.Permissions.Add(manageKBS);
                        var viewSettings = new Permission {
                            Title = "View Settings", PermissionCode = 909
                        };
                        context.Permissions.Add(viewSettings);
                        var manageCRM = new Permission {
                            Title = "Manage CRM", PermissionCode = 222
                        };
                        context.Permissions.Add(manageCRM);
                        var manageTicketDesk = new Permission {
                            Title = "Manage Ticket Desk", PermissionCode = 1100
                        };
                        context.Permissions.Add(manageTicketDesk);
                        context.SaveChanges();

                        var adminRole = new Role {
                            Name = "Admin"
                        };
                        context.Roles.Add(adminRole);
                        context.SaveChanges();

                        // Role Permission Mapping
                        var permissions = context.Permissions.ToList();
                        foreach (var permission in permissions)
                        {
                            var newMap = new RolePermission
                            {
                                RoleId       = adminRole.Id,
                                PermissionId = permission.Id
                            };

                            context.RolePermissions.Add(newMap);
                        }
                        context.SaveChanges();

                        // Create User
                        var user = new User
                        {
                            EmployeeCode = "Code",
                            Username     = selectedTenant.Email,
                            Password     = HashHelper.Hash("123456"),
                            AccessRuleId = accessRule.Id,
                            PersonId     = person.Id
                        };

                        context.Users.Add(user);
                        context.SaveChanges();

                        // Role Member Mapping
                        var newMember = new RoleMember
                        {
                            RoleId = adminRole.Id,
                            UserId = user.Id
                        };

                        context.RoleMembers.Add(newMember);
                        context.SaveChanges();

                        return(RedirectToAction("Index"));
                    }
                }
            }
            return(View(tenant));
        }
예제 #23
0
 public OperationResult <RoleMember> AddParent(int id, [FromBody] RoleMember obj)
 {
     obj.MemberId = id;
     return(Controller.AddRoleParent(obj));
 }