public JsonResult Create(UsersDto item, FormCollection coll)
        {
            OperationResult r = new OperationResult();

            try
            {
                List <UsersDto> list = SqlHelp.GetUsers();
                if (list.Exists(p => p.LoginName.Equals(item.LoginName)))
                {
                    r.ResultType = OperationResultType.ValidError;
                    r.Message    = "该登录名已存在";
                }
                else
                {
                    string role = coll["role"] == null ? "" : coll["role"].ToString();
                    item.Password = Zhongyu.Common.EncryptHelper.MD5Encrypt(item.Password, 32);
                    item.Id       = Guid.NewGuid().ToString();
                    SqlHelp.InsertUsers(item, role);
                    r.ResultType = OperationResultType.Success;
                }
            }
            catch (Exception ex)
            {
                r.Message    = "新增失败,请检查所填数据是否正确。";
                r.ResultType = OperationResultType.Error;
            }

            return(Json(r));
        }
Example #2
0
        public async Task <IActionResult> Authenticate(UsersDto userDto)
        {
            _logger.LogInformation($"Authenticate {userDto.userName}@{userDto.password}");

            var user = await _userService.AuthenticateAysnc(userDto.userName, userDto.password);

            if (user == null)
            {
                return(BadRequest(new { Message = "用户名或密码错误" }));
            }
            if (!user.status)
            {
                return(BadRequest(new { Message = "该用户被禁用,请联系管理员" }));
            }

            var claims      = new[] { new Claim(ClaimTypes.Name, user.userName), new Claim(ClaimTypes.Role, user.userType) };
            var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
            var token       = new JwtSecurityToken("WebAPIServer", "WebAPIClients", claims, expires: DateTime.Now.AddDays(1), signingCredentials: credentials);
            var tokenString = JwtTokenHandler.WriteToken(token);

            var returnData = new
            {
                tokenType   = "Bearer",
                accessToken = tokenString
            };

            return(Ok(new
            {
                code = 20000,
                data = returnData
            }));
        }
Example #3
0
        public ActionResult AddNewUser(UsersDto usersDto)
        {
            if (usersDto != null)
            {
                var user = usersDto.GetUser(usersDto);
                if (user != null)
                {
                    try
                    {
                        userService.InsertUser(user);
                    }
                    catch (Exception e)
                    {
                        Program.Logger.Error(e);
                        return(Ok(GetResponse(ResponseType.FAIL, ResponseStatusCode.FAIL, GetError(ErrorCodes.dataNotFound, "Failed", "Error occurred while adding new user"))));
                    }

                    return(Ok(GetResponse(ResponseType.ACK, ResponseStatusCode.SUCCESS)));
                }
                else
                {
                    return(Ok(GetResponse(ResponseType.FAIL, ResponseStatusCode.FAIL, GetError(ErrorCodes.dataNotFound, "Failed", "Something went wrong."))));
                }
            }
            else
            {
                return(BadRequest(GetResponse(ResponseType.ERROR, ResponseStatusCode.ERROR, GetError(ErrorCodes.invalidData, "Invalid input", "Please enter proper user details"))));
            }
        }
        public ActionResult Edit(string id)
        {
            ViewBag.Role = SqlHelp.GetRoles();
            UsersDto      item   = SqlHelp.GetUserById(id);
            List <string> userid = new List <string>();
            List <string> roleid = new List <string>();

            SqlHelp.GetUserRoles().ForEach(
                p1 =>
            {
                userid.Add(p1.UserId);
            });
            List <RolesDto> roles = new List <RolesDto>();

            if (userid.Contains(item.Id))
            {
                //把获取这个用户下的所有角色id
                roleid.Clear();
                foreach (var userRolese in SqlHelp.GetUserRoles().Where(p3 => p3.UserId.Equals(item.Id)))
                {
                    roleid.Add(userRolese.RoleId);
                    //roleid
                }

                //roles.Clear();
                roleid.ForEach(p4 => { roles.Add(SqlHelp.GetRoles().Where(p5 => p5.Id.Equals(p4)).FirstOrDefault()); }

                               );
            }
            item.Roles = roles;
            return(View(item));
        }
        public async Task <ActionResult> CustomerProductsCreate(UsersDto customer, ProductsDto product)
        {
            var customerResult = await _customersRepository.GetAsync(customer.Id);

            TempData["customer"] = customerResult.Data;

            var productResult = await _productsRepository.GetAllAsync();

            ViewBag.Products = productResult.Data;

            var customerProducts = await _customersProductsRepository.GetAllByCustomerIdAsync(customer.Id);

            var customerAlreadyHasProduct = customerProducts.Data.Exists(e => e.ProductsId == product.Id);

            if (customerAlreadyHasProduct)
            {
                var modelResult = new TaskResult <CustomersProductsDto>
                {
                    Message = "El cliente ya tiene este producto",
                    Success = false
                };
                return(View("CustomerProductsCreate", modelResult));
            }

            var customerProduct = new CustomersProductsDto
            {
                ProductsId        = product.Id,
                ApplicationUserId = customer.Id
            };

            var relResult = await _customersProductsRepository.SaveAsync(customerProduct);

            return(View("CustomerProductsCreate", relResult));
        }
Example #6
0
        public void SaveUser(UsersDto user)
        {
            var userId   = user.UserId;
            var fullName = user.Name;
            var surname  = user.Surname;

            if (string.IsNullOrEmpty(fullName) && string.IsNullOrEmpty(surname))
            {
                return;
            }
            if (userId == 0)
            {
                var userTable = new Users()
                {
                    Name    = fullName,
                    Surname = surname
                };

                _context.UsersRepository.Add(userTable);
            }
            else
            {
                var getUser = _context.UsersRepository.SingleOrDefault(u => u.UserId == userId);
                if (getUser == null)
                {
                    return;
                }

                getUser.Name    = fullName;
                getUser.Surname = surname;
            }

            _context.saveChanges();
        }
Example #7
0
        public async Task <ActionResult> Login(UsersDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(View(dto));
            }

            var data = await _usersService.GetLoginUser(dto);

            if (data != null)
            {
                if (data.UserTypeId == 2 && data.UserStatusId == 1)
                {
                    return(RedirectToAction("Index", "Dashboard"));
                }
                else if (data.UserStatusId == 2)
                {
                    dto.Message = "Your Account is not active";
                }

                else if (data.UserStatusId == 3)
                {
                    dto.Message = "You are suspended,Please contact to admin for further information";
                }
            }
            else
            {
                dto.Message = "User name or password is not correct";
            }
            string url = string.Format(@"/Login?message={0}", dto.Message);

            return(Redirect(url));
        }
Example #8
0
        private static void GetUsersAndProducts(ProductShopDbContext context)
        {
            var users = new UsersDto()
            {
                UsersCount    = context.Users.Where(u => u.ProductsSold.Count >= 1).Count(),
                UsersProducts = context.Users.Include(u => u.ProductsSold)
                                .Where(u => u.ProductsSold.Count >= 1)
                                .OrderByDescending(u => u.ProductsSold.Count)
                                .ThenBy(u => u.LastName)
                                .Select(u => new UserSoldProductsDto()
                {
                    FirstName    = u.FirstName,
                    LastName     = u.LastName,
                    Age          = u.Age.ToString(),
                    SoldProducts = new SoldProductsDto()
                    {
                        ProductsCounts = u.ProductsSold.Count,
                        Products       = u.ProductsSold.Select(p => new ProductPriceDto()
                        {
                            Name  = p.Name,
                            Price = p.Price
                        }).ToArray(),
                    }
                })
                                .ToArray()
            };
            var serializerNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
            var serializer           = new XmlSerializer(typeof(UsersDto), new XmlRootAttribute("users"));

            using (StreamWriter writer = new StreamWriter(@"..\..\..\Output\users-and-products.xml", false))
            {
                serializer.Serialize(writer, users, serializerNamespaces);
            }
        }
        public async Task <Guid> AddAsync(Guid identityUserId)
        {
            UsersDto userDto = new UsersDto()
            {
                Id = identityUserId
            };


            using (var uow = UowProvider.CreateUnitOfWork())
            {
                try
                {
                    Users userEntity     = Mapper.Map <UsersDto, Users>(userDto);
                    var   repositoryUser = uow.GetRepository <Users, Guid>();
                    await repositoryUser.AddAsync(userEntity);

                    await uow.SaveChangesAsync();

                    return(userEntity.Id);
                }
                catch (Exception e)
                {
                    Console.Write(e);
                    throw;
                }
            }
        }
Example #10
0
        public ResponseModel AddUser(UsersDto user)
        {
            Users         user_    = ClassMapping.ClassMemberMapping <UsersDto, Users>(user);
            ResponseModel response = new ResponseModel();

            if (user_.UserAccount.ToLower().Equals("admin") ||
                user_.UserAccount.ToLower().Equals("administrator"))
            {
                response.Code    = 0;
                response.Message = "User Account is Invalid";
            }
            else
            {
                Users entity = db_.Users.AsNoTracking().Where(p => p.UserAccount.Equals(user_.UserAccount)).FirstOrDefault();
                if (entity != null)
                {
                    response.Code    = 0;
                    response.Message = "User already Existed";
                }
                else
                {
                    db_.Users.Add(user_);
                    db_.SaveChanges();
                    response.Code    = 1;
                    response.Data    = user;
                    response.Message = "User create Success";
                }
            }
            return(response);
        }
Example #11
0
        public IdentityResult Register([FromBody] UsersDto userDto)
        {
            #region MinaMakram
            //var userStore = new UserStore<ApplicationUser>(new ApplicationDbContext());
            //var manager = new UserManager<ApplicationUser>(userStore);
            //var user = new ApplicationUser() { UserName = userDto.UserName, Email = userDto.Email, FirstName = userDto.FirstName, LastName = userDto.LastName, PhoneNumber = userDto.Phone };
            //user.FirstName = userDto.FirstName;
            //user.LastName = userDto.LastName;
            //manager.PasswordValidator = new PasswordValidator
            //{
            //    RequiredLength = 3
            //};
            //IdentityResult result = manager.Create(user, userDto.Password);
            //manager.AddToRoles(user.Id, userDto.TypeRegistration);
            //return result;

            //ApplicationDbContext context = new ApplicationDbContext();
            //if (!ModelState.IsValid)
            //{
            //    return BadRequest(ModelState);
            //}
            #endregion
            AuthBusinessLayer auth   = new AuthBusinessLayer();
            IdentityResult    result = auth.Create(userDto);

            if (result.Succeeded)
            {
                return(result);
            }
            return(result);
        }
Example #12
0
        public static void UsersAndProducts(ProductsShopContext context)
        {
            //Всичко стана паприкаш...

            var users = new UsersDto()
            {
                Count = context.Users.Count(),
                Users = context.Users.Select(x => new UsersProductsDto
                {
                    FirstName = x.FirstName,
                    LastName  = x.LastName,
                    Age       = x.Age.ToString(),
                    Products  = new ProductExerciseFourDto()
                    {
                        Count        = x.SellingProducts.Count,
                        SoldProducts = x.SellingProducts.Select(y => new SoldProductExerciseFourDto()
                        {
                            Name  = y.Name,
                            Price = y.Price
                        })
                                       .ToArray()
                    }
                })
                        .ToArray()
            };

            var sb         = new StringBuilder();
            var serializer = new XmlSerializer(typeof(UsersDto), new XmlRootAttribute("users"));
            var namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });

            serializer.Serialize(new StringWriter(sb), users, namespaces);

            File.WriteAllText("../../../Export/users-and-products.xml", sb.ToString());
        }
Example #13
0
        public async Task <int> InsertUpdateUser(UsersDto model)
        {
            try
            {
                using (connection = Get_Connection())
                {
                    var param = new DynamicParameters();
                    param.Add("id", model.id, DbType.Int32, ParameterDirection.Input);
                    param.Add("UserName", model.UserName, DbType.String, ParameterDirection.Input);
                    param.Add("Email", model.Email, DbType.String, ParameterDirection.Input);
                    param.Add("Contact", model.Contact, DbType.String, ParameterDirection.Input);
                    param.Add("Gender", model.Gender, DbType.String, ParameterDirection.Input);
                    param.Add("QualificationId", model.QualificationId, DbType.Int32, ParameterDirection.Input);
                    param.Add("MainStreamId", model.MainStreamId, DbType.Int32, ParameterDirection.Input);
                    param.Add("SubStreamId", model.SubStreamId, DbType.Int32, ParameterDirection.Input);
                    param.Add("IsDelete", model.IsDelete, DbType.Boolean, ParameterDirection.Input);

                    var userid = await connection.ExecuteScalarAsync <int>("sp_InsertUpdateUsers", param, commandType : CommandType.StoredProcedure);

                    return(userid);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #14
0
        public Task <List <UsersDto> > GetUserList()
        {
            List <UsersDto> listUsers = new List <UsersDto>();

            using (SqlConnection con = new SqlConnection(ConnectionString))
            {
                SqlCommand cmd = new SqlCommand("usp_getUserList", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();

                while (rdr.Read())
                {
                    UsersDto objUserDto = new UsersDto();
                    objUserDto.id           = Convert.ToInt32(rdr["id"]);
                    objUserDto.Username     = Convert.ToString(rdr["Username"]);
                    objUserDto.PasswordHash = (byte[])rdr["PasswordHash"];
                    objUserDto.PasswordSalt = (byte[])rdr["PasswordSalt"];
                    objUserDto.PhotoUrl     = Convert.ToString(rdr["MainUrl"]);

                    listUsers.Add(objUserDto);
                }
                con.Close();
            }

            return(Task.FromResult(listUsers));
        }
Example #15
0
        public IActionResult Authenticate([FromBody] UsersDto userDto)
        {
            var user = _usersService.Authenticate(userDto.Username, userDto.Password);

            if (user == null)
            {
                return(Unauthorized());
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            // return basic user info (without password) and token to store client side
            return(Ok(new { Id = user.Id,
                            Username = user.Username,
                            FullName = user.FullName,
                            ImgUrl = user.ImgUrl,
                            Level = user.Level,
                            Points = user.Points,
                            UsersChallenges = user.UsersChallenges,
                            Token = tokenString }));
        }
Example #16
0
        public bool Insert(UsersDto item)
        {
            using (IDbConnection db = new SqlConnection(ConnectionString))
            {
                Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
                if (db.State == ConnectionState.Closed)
                {
                    db.Open();
                }

                int result = db.Execute(@"INSERT INTO USERS(NAME, AVATAR, EMAIL, ID_DEPARTMENT, ID_PROCESS, IS_LEADER_DEPARTMENT,
                                                IS_LEADER_PROCESS, REMOVED,PASSWORD_HASH,PASSWORD_SALT)
		                                VALUES(@Name, @Avatar, @Email, @IdDepartment, @IdProcess, @IsLeaderDepartment, @IsLeaderProcess, 0,@PassHash, @PassSalt)"        ,
                                        new {
                    Name               = item.Name,
                    Avatar             = item.Avatar,
                    Email              = item.Email,
                    IdDepartment       = item.Department,
                    IdProcess          = item.Process,
                    IsLeaderDepartment = item.IsLeaderDepartment,
                    IsLeaderProcess    = item.IsLeaderProcess,
                    PassHash           = item.PasswordHash,
                    PassSalt           = item.PasswordSalt
                }
                                        );
                return(result > 0);
            }
        }
Example #17
0
        public async Task <IActionResult> Update(int id, [FromBody] UsersDto userDto)
        {
            // Map dto to entity and set id
            var user = _mapper.Map <Users>(userDto);

            user.Id = id.ToString();

            // Allow only admins to update other user records
            var currentUserId = int.Parse(User.Identity.Name);

            if (id != currentUserId && !User.IsInRole("Admin"))
            {
                return(Forbid());
            }

            try
            {
                // Save
                _userServices.Update(user, userDto.Password);
                return(Ok());
            }
            catch (AppException ex)
            {
                // Return error message if there was an exception
                return(BadRequest(new { message = ex.Message }));
            }
        }
Example #18
0
        public async Task <ActionResult <UsersDto> > AuthenticateUser(UsersDto userDetails)
        {
            //Recives User with only Username and Password Values
            //Get the user that matches these and return it
            if (userDetails.username == null || userDetails.password == null)
            {
                return(BadRequest());
            }

            var query = _context.Users.Where(u => u.Username == userDetails.username)
                        .Select(u => new UsersDto
            {
                id       = u.UserID,
                username = u.Username,
                password = u.Password,
                type     = u.UserType.UType
            });

            var user = await query.FirstOrDefaultAsync();

            //Return the user
            //Password validation (TEMPORARY)
            if (user == null)
            {
                return(NotFound());
            }
            else if (user.password == userDetails.password)
            {
                return(user);
            }
            else
            {
                return(NotFound());
            }
        }
Example #19
0
        public ActionResult UpdateUser(UsersDto usersDto)
        {
            if (usersDto != null)
            {
                try
                {
                    var userFromDb = userService.GetUser(usersDto.Id);
                    if (userFromDb != null)
                    {
                        var convertedUser = usersDto.GetUser(userFromDb, usersDto);
                        userService.UpdateUser(convertedUser);
                    }
                    else
                    {
                        throw new Exception("The user does not exist");
                    }
                }
                catch (Exception e)
                {
                    Program.Logger.Error(e);
                    return(Ok(GetResponse(ResponseType.FAIL, ResponseStatusCode.FAIL, GetError(ErrorCodes.dataNotFound, "Failed", "Error occurred while updating the user"))));
                }

                return(Ok(GetResponse(ResponseType.ACK, ResponseStatusCode.SUCCESS)));
            }
            else
            {
                return(BadRequest(GetResponse(ResponseType.ERROR, ResponseStatusCode.ERROR, GetError(ErrorCodes.invalidData, "Invalid input", "Please enter proper user details"))));
            }
        }
Example #20
0
        //[Authorize(Roles = "Admin")]    //Admin角色才可以访问该接口
        //[Authorize(Policy = "CustomPolicy")]   //自定义授权
        public async Task <IActionResult> GetUserInfo([FromBody] UsersDto usersDto)
        {
            var name = usersDto.Username ?? throw new ArgumentNullException("Username不能为Null");

            //测试日志
            this.logger.LogInformation("this is logInfo");
            this.logger.LogError("this is logerror");
            this.logger.LogDebug("this is debug");
            this.logger.LogWarning("this is warning");
            this.logger.LogTrace("this is trace");


            //Parallel.For 可以并行循环执行https://blog.csdn.net/woaipangruimao/article/details/79800587
            //ConcurrentDictionary<string, UsersDto> dict = new ConcurrentDictionary<string, UsersDto>();
            //ParallelLoopResult paraResult = Parallel.For(0, 100, async (i, state) =>
            //{
            //    log.Debug($"迭代次数:{i},任务ID:{Task.CurrentId},线程ID:{Thread.CurrentThread.ManagedThreadId}");
            //    dict.GetOrAdd(i.ToString(), await userService.QueryUserInfoAsync(name));
            //});
            //if (paraResult.IsCompleted) return Ok(dict);

            var result = await userService.QueryUserInfoAsync(name);

            return(Ok(result));
        }
        private static void UsersAndProducts()
        {
            using (var db = new ProductShopContext())
            {
                var users = db.Users
                            .Where(x => x.SoldProducts.Count > 0)
                            .OrderByDescending(x => x.SoldProducts.Count)
                            .ThenBy(x => x.LastName)
                            .Select(x => new UserSoldDto()
                {
                    FirstName    = x.FirstName,
                    LastName     = x.LastName,
                    Age          = x.Age.ToString(),
                    SoldProducts = x.SoldProducts
                                   .Select(p => new ProductSoldDto()
                    {
                        Name  = p.Name,
                        Price = p.Price
                    }).ToArray()
                })
                            .ToArray();

                var rootUsers = new UsersDto()
                {
                    Count = users.Length,
                    Users = users
                };

                var sb         = new StringBuilder();
                var serializer = new XmlSerializer(typeof(UsersDto));
                var namespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
                serializer.Serialize(new StringWriter(sb), rootUsers, namespaces);
                File.WriteAllText("../../../Xml/users-and-products.xml", sb.ToString());
            }
        }
        public void GetUsersAndProducts()
        {
            var usersDto = new UsersDto
            {
                Count = this.context.Users.Count(),
                Users = this.context.Users
                        .Where(u => u.ProductsSold.Count > 0)
                        .Select(u => new UsersAndProductsDto
                {
                    FirstName   = u.FirstName,
                    LastName    = u.LastName,
                    Age         = u.Age,
                    SoldProduct = new SoldProductsDto
                    {
                        Count    = u.ProductsSold.Count(),
                        Products = u.ProductsSold.Select(p => new ProductUserDto
                        {
                            Name  = p.Name,
                            Price = p.Price
                        }).ToList()
                    }
                }).ToList()
            };


            var path      = "../../../JSON/users-and-products.json";
            var jsonUsers = JsonConvert.SerializeObject(usersDto, Formatting.Indented);

            File.WriteAllText(path, jsonUsers);
        }
Example #23
0
        public async Task <ActionResult <UsersDto> > AddNewUser(UsersDto user)
        {
            var newUser = new UsersDto();

            try
            {
                string query = @"INSERT INTO Users (UserName,Hobbies,Location) VALUES (@UserName,@Hobbies,@Location)";
                var    param = new DynamicParameters();
                param.Add("@UserName", user.UserName);
                param.Add("@Hobbies", user.Hobbies);
                param.Add("@Location", user.Location);
                using (var connection = new MySqlConnection(connString))
                {
                    var result = await connection.ExecuteAsync(query, param, null, null, CommandType.Text);

                    if (result > 0)
                    {
                        newUser = user;
                    }
                }
                if (newUser != null)
                {
                    return(Ok(newUser));
                }
                else
                {
                    return(BadRequest("Unable To  User"));
                }
            }
            catch (Exception)
            {
                return(StatusCode(500, "Unable To Process Request"));
            }
        }
Example #24
0
        public UsersDto Authenticate(string userName, string password)
        {
            var passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);

            password = Convert.ToBase64String(passwordBytes);
            var user = _userRepository.Authenticate(userName, password);

            // return null if user not found
            if (user == null)
            {
                return(null);
            }

            // authentication successful so generate jwt token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(Constant.secrete);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token = tokenHandler.WriteToken(token);

            // remove password before returning
            user.Password = null;
            UsersDto userDto = _mapper.Map <UsersDto>(user);

            return(userDto);
        }
        public dynamic Post([FromBody] UsersDto user)
        {
            try
            {
                string urlUserPut    = this.apiUrl + "/post";
                string parsedContent = "{" +
                                       "\"Username\":\"" + user.Username + "\"," +
                                       "\"Password\":\"" + user.Password + "\"," +
                                       "\"Fullname\":\"" + user.Fullname + "\"," +
                                       "\"Address\":\"" + user.Address + "\"," +
                                       "\"Phone\":\"" + user.Phone + "\"," +
                                       "\"Email\":\"" + user.Email + "\"," +
                                       "\"Age\":" + user.Age + "," +
                                       "\"RolesId\":" + user.RolesId +
                                       "}";

                var getResponse = JObject.Parse(Http.PostCall(urlUserPut, parsedContent, "POST"));

                return(JsonConvert.SerializeObject(getResponse, Formatting.Indented));
            }
            catch (Exception ex)
            {
                return(new CustomResponse {
                    State = 500, Message = ex.Message.ToString()
                });
            }
        }
Example #26
0
            //新增用户
            public static int InsertUsers(UsersDto model, string role)
            {
                using (IDbConnection conn = MySqlConnection())
                {
                    int            result      = 0;
                    IDbTransaction transaction = conn.BeginTransaction();
                    try
                    {
                        result = conn.Execute(
                            "Insert into sysuser values (@Id,@LoginName,@Password,@Name,@Phone,@Enable)", model);
                        if (!string.IsNullOrWhiteSpace(role))
                        {
                            foreach (var rid in role.Split(','))
                            {
                                if (!string.IsNullOrWhiteSpace(rid))
                                {
                                    conn.Execute("Insert into userrole values (@UserId,@RoleId)",
                                                 new UserRoles {
                                        RoleId = rid, UserId = model.Id
                                    });
                                    //RoleUser.Insert(});
                                }
                            }
                        }

                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                    }

                    return(result);
                }
            }
Example #27
0
        /// <summary>
        /// Add/Update group
        /// </summary>
        /// <returns></returns>
        public async Task <ActionResult> ManageClient(int?id)
        {
            var clientMaster = await _masterService.GetClientById(id ?? 0);

            if (clientMaster == null)
            {
                clientMaster = new UsersDto();
            }
            var companies = await _invoiceService.GetCompany();

            var particulars = await _invoiceService.GetParticular();

            clientMaster.Companies = companies.Select(c => new CompanyDto
            {
                Id          = c.Id,
                CompanyName = c.CompanyName
            }).ToList();

            clientMaster.Particulars = particulars.Select(p => new ParticularDto
            {
                Id           = Convert.ToInt32(p.Id),
                ParticularFF = p.ParticularFF
            }).ToList();

            ViewBag.Companies      = new MultiSelectList(companies, "Id", "CompanyName", clientMaster.CompanyIds);
            ViewBag.Consultant     = new SelectList(await _masterService.GetAllConsultant(), "Id", "FullName", clientMaster.ConsultantId);
            ViewBag.Groups         = new SelectList(await _masterService.GetAllGroups(), "GroupId", "Name", clientMaster.GroupId);
            ViewBag.BusinessType   = new SelectList(await _masterService.GetAllBusinessType(), "BusinessTypeId", "Name", clientMaster?.BusinessType);
            ViewBag.BusinessStatus = new SelectList(await _masterService.GetAllBusinessStatus(), "BusinessStatusId", "Name", clientMaster?.BusinessStatus);

            return(View(clientMaster));
        }
Example #28
0
        public async Task <CustomApiResponse> Put([FromBody] UsersDto entity)
        {
            var inputEntity = _mapper.Map <Users>(entity);
            var result      = await _userService.Update(inputEntity);

            return(new CustomApiResponse(entity.Id, result ? "Succeeded" : "Failed", !result));
        }
Example #29
0
 /// <summary>
 /// 测试初始化
 /// </summary>
 public UsersServiceTest()
 {
     _scope           = Ioc.BeginScope();
     _usersRepository = _scope.Create <IUsersRepository>();
     _usersService    = _scope.Create <IUsersService>();
     _usersDto        = UsersDtoTest.Create();
 }
        private static void UsersAndProducts(ProductShopContext context, MapperConfiguration config)
        {
            var users = new UsersDto
            {
                Count = context.Users.Count(u => u.ProductsSold.Count > 0),
                Users = context.Users.Where(u => u.ProductsSold.Count > 0).Select(u => new UserProductDto
                {
                    FirstName    = u.FirstName,
                    LastName     = u.LastName,
                    Age          = u.Age.ToString(),
                    SoldProducts = new SoldProductsDto
                    {
                        Count    = u.ProductsSold.Count,
                        Products = u.ProductsSold.AsQueryable().ProjectTo <ProductDto>(config).ToArray()
                    }
                }).ToArray()
            };

            var serializer = new XmlSerializer(typeof(UsersDto), new XmlRootAttribute("users"));
            var namespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });

            using (var writer = new StreamWriter("../SerializedQueries/users-and-products.xml"))
            {
                serializer.Serialize(writer, users, namespaces);
            }
        }
        public object Get(UsersDto request)
        {
            List<UserDto> users;
            string query;

            //if (request.OrganizationId.HasValue)
            //{
            //    query = String.Format("select u.* " +
            //                              "from User u " +
            //                              "inner join OrganizationAlly oa " +
            //                              "where oa.OrganizationId = {0}", request.OrganizationId);

            //    users = Db.Select<UserDto>(query);
            //}
            //else
            //{
            query = "select u.*, sp.Name as StateProvinceName, sp.Abbreviation as StateProvinceAbbreviation " +
                    "from User u " +
                    "left join StateProvince sp " +
                    "on u.StateProvinceId = sp.Id";

            users = Db.Select<UserDto>(query);
            //}

            return new UsersResponse
            {
                Users = users
            };
        }