/// <summary>
        /// Retrieves list of UserCompany objects from SqlCommand, after database query
        /// number of rows retrieved and returned depends upon the rows field value
        /// </summary>
        /// <param name="cmd">The command object to use for query</param>
        /// <param name="rows">Number of rows to process</param>
        /// <returns>A list of UserCompany objects</returns>
        private UserCompanyList GetList(SqlCommand cmd, long rows)
        {
            // Select multiple records
            SqlDataReader reader;
            long          result = SelectRecords(cmd, out reader);

            //UserCompany list
            UserCompanyList list = new UserCompanyList();

            using ( reader )
            {
                // Read rows until end of result or number of rows specified is reached
                while (reader.Read() && rows-- != 0)
                {
                    UserCompany userCompanyObject = new UserCompany();
                    FillObject(userCompanyObject, reader);

                    list.Add(userCompanyObject);
                }

                // Close the reader in order to receive output parameters
                // Output parameters are not available until reader is closed.
                reader.Close();
            }

            return(list);
        }
Пример #2
0
        // Create access Tokenm
        private async Task <TokenResponse> CreateAccessToken(User user, string refreshToken)
        {
            double             tokenExpiryTime = Convert.ToDouble(_appSettings.ExpireTime);
            var                key             = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_appSettings.Secret));
            var                tokenHandler    = new JwtSecurityTokenHandler();
            List <UserCompany> lstuserCompany  = await uow.UserCompanyRepository.GetUserCompanyByUserId(user.userId);

            List <UserCompanyList> userCompanyList = new List <UserCompanyList>();

            foreach (var item in lstuserCompany)
            {
                UserCompanyList lst = new UserCompanyList();
                lst.companyCode = item.CompanyCode;
                lst.companyName = item.CompanyName;
                userCompanyList.Add(lst);
            }

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(
                    new Claim[]
                {
                    new Claim(JwtRegisteredClaimNames.Sub, user.firstName + " " + user.lastName),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    new Claim(ClaimTypes.NameIdentifier, user.userId.ToString()),
                    new Claim("LoggedOn", DateTime.Now.ToString()),
                    new Claim("userId", user.userId.ToString()),
                    new Claim("firstName", Convert.ToString(user.firstName)),
                    new Claim("lastName", Convert.ToString(user.lastName))
                }
                    ),

                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature),
                Issuer             = _appSettings.Site,
                Audience           = _appSettings.Audience,
                Expires            = DateTime.UtcNow.AddMinutes(tokenExpiryTime)
            };

            // Generate token
            var newtoken     = tokenHandler.CreateToken(tokenDescriptor);
            var encodedToken = tokenHandler.WriteToken(newtoken);

            return(new TokenResponse()
            {
                token = encodedToken,
                expiration = newtoken.ValidTo,
                refresh_Token = refreshToken,
                firstName = user.firstName,
                lastName = user.lastName,
                userID = user.userId.ToString(),
                isAdmin = user.isAdmin,
                userCompanyList = userCompanyList
            });
        }
        /// <summary>
        /// Retrieves all UserCompany objects by PageRequest
        /// </summary>
        /// <returns>A list of UserCompany objects</returns>
        public UserCompanyList GetPaged(PagedRequest request)
        {
            using (SqlCommand cmd = GetSPCommand(GETPAGEDUSERCOMPANY))
            {
                AddParameter(cmd, pInt32Out("TotalRows"));
                AddParameter(cmd, pInt32("PageIndex", request.PageIndex));
                AddParameter(cmd, pInt32("RowPerPage", request.RowPerPage));
                AddParameter(cmd, pNVarChar("WhereClause", 4000, request.WhereClause));
                AddParameter(cmd, pNVarChar("SortColumn", 128, request.SortColumn));
                AddParameter(cmd, pNVarChar("SortOrder", 4, request.SortOrder));

                UserCompanyList _UserCompanyList = GetList(cmd, ALL_AVAILABLE_RECORDS);
                request.TotalRows = Convert.ToInt32(GetOutParameter(cmd, "TotalRows"));
                return(_UserCompanyList);
            }
        }
Пример #4
0
        /// <summary>
        /// Retrieve list of UserCompany.
        /// </summary>
        /// <param name="fillChild"></param>
        /// <returns>List of UserCompany</returns>
        public UserCompanyList GetAll(bool fillChild)
        {
            UserCompanyList userCompanyList = new UserCompanyList();

            using (UserCompanyDataAccess data = new UserCompanyDataAccess(ClientContext))
            {
                userCompanyList = data.GetAll();
            }
            if (fillChild)
            {
                foreach (UserCompany userCompanyObject in userCompanyList)
                {
                    FillUserCompanyWithChilds(userCompanyObject, fillChild);
                }
            }
            return(userCompanyList);
        }
        public async Task <IActionResult> GetUsers()
        {
            UserResDto  responseResult = new UserResDto();
            List <User> lstUsers       = new List <User>();

            try
            {
                lstUsers = await uow.UserRepository.GetUsersAsync();

                List <UserReqDto> lstreqDto = new List <UserReqDto>();
                foreach (var item in lstUsers)
                {
                    UserReqDto reqDto = new UserReqDto();
                    reqDto = mapper.Map <UserReqDto>(item);
                    List <UserCompanyList> lstUserCompany = new List <UserCompanyList>();
                    List <UserCompany>     lstcom         = await uow.UserCompanyRepository.GetUserCompanyByUserId(reqDto.userId);

                    foreach (var userCompany in lstcom)
                    {
                        UserCompanyList lst = new UserCompanyList();
                        lst.companyCode = userCompany.CompanyCode;
                        lst.companyName = userCompany.CompanyName;
                        lstUserCompany.Add(lst);
                    }
                    reqDto.userCompanyList = lstUserCompany;
                    lstreqDto.Add(reqDto);
                }
                responseResult.UserReqDto  = lstreqDto;
                responseResult.messageType = "S";
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Error, ex.Message);
            }

            return(Ok(new { responseDto = responseResult }));
        }
        public async Task <IActionResult> AddEditUser([FromBody] UserReqDto userData)
        {
            ResponseResultDto res = new ResponseResultDto();

            UserResDto responseResult = new UserResDto();

            try
            {
                var identity = User.Identity as ClaimsIdentity;
                if (identity != null)
                {
                    IEnumerable <Claim> claims = identity.Claims;
                    var CompanyId = claims.Where(p => p.Type == "companyId").FirstOrDefault()?.Value;
                    int companyID = Convert.ToInt32(CompanyId);
                    var UserId    = claims.Where(p => p.Type == "userId").FirstOrDefault()?.Value;
                    int userID    = Convert.ToInt32(UserId);

                    if (uow.UserRepository.IsUserNameExists(userData.userName, userData.userId))
                    {
                        res.MessageType = "E";
                        res.Message     = String.Format(MessageConstant.RecordAlreadyExists, "username '" + userData.userName + "'");
                        return(Ok(new { ResponseResultDto = res }));
                    }

                    var user = mapper.Map <User>(userData);


                    user.ModifiedOn = DateTime.Now;
                    user.ModifiedBy = userID;

                    if (user.userId == 0)
                    {
                        user.CreatedOn = DateTime.Now;
                        user.CreatedBy = userID;
                        user.password  = CommonFuntions.Encrypt(user.password);
                        uow.UserRepository.AddUser(user);
                    }
                    else
                    {
                        User objUser = (await uow.UserRepository.FindUser(userData.userId)).FirstOrDefault();
                        user.password  = CommonFuntions.Encrypt(user.password);
                        user.CreatedOn = objUser.CreatedOn;
                        user.CreatedBy = objUser.CreatedBy;
                        uow.UserRepository.UpdateUser(user);
                        uow.UserCompanyRepository.DeleteUserCompanyByUserId(user.userId);
                    }
                    List <UserCompany> lstuserCompany = new List <UserCompany>();
                    foreach (var item in userData.userCompanyList)
                    {
                        UserCompany userCompany = new UserCompany();
                        userCompany.CompanyCode = item.companyCode;
                        userCompany.CompanyName = item.companyName;
                        userCompany.CreatedBy   = userID;
                        userCompany.CreatedOn   = DateTime.Now;
                        userCompany.userID      = user.userId;
                        lstuserCompany.Add(userCompany);
                    }
                    user.Usercompany = lstuserCompany;

                    uow.UserCompanyRepository.AddUserCompany(lstuserCompany);
                    await uow.SaveAsync();

                    List <User> lstUsers = new List <User>();
                    lstUsers = await uow.UserRepository.GetUsersAsync();

                    List <UserReqDto> lstreqDto = new List <UserReqDto>();
                    foreach (var item in lstUsers)
                    {
                        UserReqDto reqDto = new UserReqDto();
                        reqDto = mapper.Map <UserReqDto>(item);
                        List <UserCompanyList> lstUserCompany = new List <UserCompanyList>();
                        List <UserCompany>     lstcom         = await uow.UserCompanyRepository.GetUserCompanyByUserId(reqDto.userId);

                        foreach (var userCompany in lstcom)
                        {
                            UserCompanyList lst = new UserCompanyList();
                            lst.companyCode = userCompany.CompanyCode;
                            lst.companyName = userCompany.CompanyName;
                            lstUserCompany.Add(lst);
                        }
                        reqDto.userCompanyList = lstUserCompany;
                        lstreqDto.Add(reqDto);
                    }



                    responseResult.UserReqDto  = lstreqDto;
                    responseResult.messageType = "S";
                    if (userData.userId == 0)
                    {
                        responseResult.message = MessageConstant.RecordAdded;
                    }
                    else
                    {
                        responseResult.message = MessageConstant.RecordUpdated;
                    }
                }
                else
                {
                    responseResult.messageType = "E";
                    responseResult.message     = MessageConstant.Something_went_wrong;
                }
            }
            catch (Exception ex)
            {
                responseResult.messageType = "E";
                if (userData.userId == 0)
                {
                    responseResult.message = MessageConstant.FailedToAddRecord;
                }
                else
                {
                    responseResult.message = MessageConstant.FailedToUpdateRecord;
                }

                logger.Log(LogLevel.Error, ex.Message);
            }

            return(Ok(new { responseDto = responseResult }));
        }