public async Task <IActionResult> UpdateUser([FromBody] UpdateUserDto updateUser, [FromRoute] Guid id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var userId = User.Claims.FirstOrDefault(p => p.Type == ClaimTypes.NameIdentifier)?.Value;

            if (id.ToString() != userId)
            {
                return(BadRequest());
            }
            var isUser = _userManager.Users.Any(u => u.Id == id.ToString());

            if (!isUser)
            {
                return(NotFound());
            }
            var updatedUser = await _userService.UpdateUserAsync(id, updateUser).ConfigureAwait(false);

            var saved = await _userService.SaveAsync().ConfigureAwait(false);

            if (!saved)
            {
                return(BadRequest());
            }
            var profileUser = new ProfileDto(updatedUser);

            return(Ok(profileUser));
        }
Beispiel #2
0
        public async Task <IActionResult> Post(ProfileDto model)
        {
            _logger.LogInformation($"{JsonConvert.SerializeObject(model)} has been submitted!");

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState.Values));
            }

            try
            {
                await _submission.SubmitAsync(
                    new SubmissionModel
                {
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    Email       = model.Email,
                    MobilePhone = model.MobilePhone
                });
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "An error occured while submitting subscription.");

                return(StatusCode(
                           500,
                           new
                {
                    error = "A server error has occured and the request could not be submitted."
                }));
            }

            return(Ok());
        }
Beispiel #3
0
        public async Task <Result> AddProfileAsync(ProfileDto profileDto)
        {
            using var context = _contextFactory.CreateDbContext();
            var profile = await context.Profiles.FindAsync(profileDto.Id);

            if (profile != null)
            {
                return(Result.Failure("Profile already exists"));
            }

            profile = new Profile
            {
                Name        = profileDto.Name,
                Description = profileDto.Description,
                ServerName  = profileDto.ServerName,
                ServerPort  = profileDto.ServerPort,
                UserName    = profileDto.UserName,
                Password    = profileDto.Password,
                AuthBaseUri = profileDto.AuthBaseUri,
                ApiBaseUri  = profileDto.ApiBaseUri
            };

            await context.Profiles.AddAsync(profile);

            return(Result.Success());
        }
Beispiel #4
0
        public void CreateProfileTest_ArgumentNullException(ProfileDto profile)
        {
            var exc = Assert.Throws <ArgumentNullException>(() => _testObject.CreateProfile(profile));

            Assert.AreEqual("profile", exc.ParamName);
            _profileProvider.DidNotReceiveWithAnyArgs().Create(Arg.Any <UserProfile>());
        }
        public async Task <ProfileDto> GetProfileByUserId(string userId)
        {
            if (userId is null)
            {
                throw new ArgumentNullException(nameof(userId));
            }

            var profiles = await _repository.GetAll().AsNoTracking().ToListAsync();

            var profileDataModel = profiles.FirstOrDefault(c => c.UserId.Equals(userId));

            if (profileDataModel is null)
            {
                return(new ProfileDto());
            }

            var profile = new ProfileDto
            {
                UserId     = profileDataModel.UserId,
                FirstName  = profileDataModel.FirstName,
                LastName   = profileDataModel.LastName,
                MiddleName = profileDataModel.MiddleName,
            };

            profile.Id = profileDataModel.Id;
            return(profile);
        }
        public async Task <IActionResult> GetMyProfile()
        {
            var user = await _userManager.FindByIdAsync(this.User.Identity.Name);

            var userWithPhotos = await _dbContext.Users.Where(q => q.Id == user.Id).Include(q => q.Photos).FirstAsync();

            var ret = new ProfileDto
            {
                Age         = user.Age,
                Description = user.Description,
                Gender      = user.Gender,
                Id          = user.Id,
                Job         = user.Job,
                Name        = user.Name,
                School      = user.School,
            };

            foreach (var item in userWithPhotos.Photos)
            {
                ret.Photos.Add(new PhotoDto {
                    Id = item.Id, Url = item.Url, Main = item.Main, Extenstion = item.Extenstion, FileName = item.FileName
                });
            }
            return(Ok(ret));
        }
        public IActionResult Put([FromBody] ProfileDto profileDto)
        {
            _unitOfWork.ProfilesRepository.Update(_dtoProfileMapper.Map(profileDto));
            _unitOfWork.Save();

            return(Ok());
        }
        public async Task <IActionResult> Put([FromBody] ProfileDto profileDto)
        {
            try
            {
                var actualUserId = _firebaseTokenService.GetTokenData(HttpContext).UserId;
                if (profileDto.UserId != actualUserId)
                {
                    return(Unauthorized());
                }

                var profile = await _profileService.GetProfile(profileDto.UserId);

                if (profile == null)
                {
                    return(NotFound());
                }

                await _profileService.EditProfile(profileDto);

                return(NoContent());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message, ex);
                return(StatusCode(StatusCodes.Status500InternalServerError, ex));
            }
        }
Beispiel #9
0
        public async Task <IActionResult> Profile(ProfileViewModel model)
        {
            model = model ?? throw new ArgumentNullException(nameof(model));

            if (ModelState.IsValid)
            {
                var profileDto = new ProfileDto
                {
                    UserId    = User.GetUserIdByClaimsPrincipal(),
                    Name      = model.Name,
                    BirthDate = model.BirthDate,
                    Gender    = model.Gender,
                    Address   = model.Address,
                };

                if (model.AvatarFile is not null)
                {
                    byte[] imageData = null;
                    using (var binaryReader = new BinaryReader(model.AvatarFile.OpenReadStream()))
                    {
                        imageData = binaryReader.ReadBytes((int)model.AvatarFile.Length);
                    }
                    profileDto.Avatar = imageData;
                }

                await _profileManager.UpdateProfileAsync(profileDto);

                return(RedirectToAction("Index", "Home"));
            }

            return(View(model));
        }
Beispiel #10
0
        public IHttpActionResult ModifyProfile([FromBody] ProfileDto profile)
        {
            if (profile == null)
            {
                return(BadRequest(Resources.EmtyData));
            }

            var userClaims = HttpContext.Current.User.Identity as ClaimsIdentity
                             ?? throw new ArgumentNullException(nameof(HttpContext.Current.User.Identity));
            var idUser = Convert.ToInt64(userClaims.Claims.FirstOrDefault(x => x.Type == Resources.ClaimTypeId)?.Value);

            if (idUser < 1 || !ModelState.IsValid)
            {
                return(BadRequest(ShowErrorsHelper.ShowErrors(ModelState)));
            }

            try
            {
                profile.AccountId = idUser;
                var user = _userService.ModifyProfile(profile);
                return(Ok(user));
            }
            catch (ArgumentException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (NotFoundUserException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (AddAccountException ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Beispiel #11
0
 private void SetOutBoundConnectionState(ToolStripMenuItem item, ProfileDto profile)
 {
     item.CheckState =
         firewallService.OutboundConnectionsAllowedOn(profile)
         ? CheckState.Checked
         : CheckState.Unchecked;
 }
Beispiel #12
0
        public ActionResult InitialProfileSetup(ProfileViewModel profile)
        {
            if (ModelState.IsValid)
            {
                var insert = new ProfileDto()
                {
                    UserId            = User.Identity.GetUserId(),
                    FirstName         = profile.FirstName,
                    LastName          = profile.LastName,
                    Title             = profile.Title,
                    Summary           = profile.Summary,
                    Location          = profile.Location,
                    Mobile            = profile.Mobile,
                    Phone             = profile.Phone,
                    IsAvailable       = profile.IsAvailable,
                    AvailableFromDate = profile.AvailableFromDate,
                    ImageUrl          = profile.ImageUrl,
                    PortfolioUrl      = profile.PortfolioUrl,
                    LinkedInUrl       = profile.LinkedInUrl
                };

                var isAdded = _profileService.InsertProfile(User.Identity.GetUserId(), insert);
                if (isAdded)
                {
                    return(RedirectToAction("Overview", "Portal"));
                }
            }
            return(View(profile));
        }
Beispiel #13
0
        public async Task <IActionResult> Profile_1_0(ApiVersion apiVersion)
        {
            var identity = HttpContext.User.Identity;

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

            var user = await _userManager.FindByNameAsync(identity.Name);

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

            var roles = await _userManager.GetRolesAsync(user);

            var profile = new ProfileDto {
                Name     = user.Name,
                Nickname = user.Nickname,
                Email    = user.Email,
                Username = user.UserName,
                Roles    = new List <string>(roles)
            };

            return(Ok(profile));
        }
        public bool OutboundConnectionsAllowedOn(ProfileDto profileDto)
        {
            var profile = (NET_FW_PROFILE_TYPE2_)profileDto;
            var action  = firewallPolicy.get_DefaultOutboundAction(profile);

            return(action == NET_FW_ACTION_.NET_FW_ACTION_ALLOW);
        }
Beispiel #15
0
        public async Task <bool> Consume(string message)
        {
            UserEvent userEvent = JsonConvert.DeserializeObject <UserEvent>(message);

            if (userEvent == null)
            {
                return(false);
            }

            Profile profile = new Profile
            {
                Id             = userEvent.Id,
                Avatar         = userEvent.Avatar,
                DisplayName    = userEvent.DisplayName,
                DateOfCreation = userEvent.DateOfCreation,
                Email          = userEvent.Email,
                GoogleId       = userEvent.GoogleId
            };

            await _context.Profiles.AddAsync(profile);

            bool success = await _context.SaveChangesAsync() > 0;

            if (!success)
            {
                return(false);
            }

            ProfileDto profileDto = _mapper.Map <ProfileDto>(profile);

            CreateProfileEvent(profileDto);

            return(true);
        }
Beispiel #16
0
        public async Task <ActionResult> HomePageCallToApi()
        {
            var        claims  = User as ClaimsPrincipal;
            ProfileDto profile = null;

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization
                    = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", claims.FindFirst("token")?.Value ?? "");

                var response = await httpClient.GetAsync("http://localhost:53866/api/profiles");

                if (response.IsSuccessStatusCode)
                {
                    var profileString = await response.Content.ReadAsStringAsync();

                    profile = Newtonsoft.Json.JsonConvert.DeserializeObject <ProfileDto>(profileString);
                }
                else
                {
                    if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                    {
                        return(Content(System.Net.HttpStatusCode.Unauthorized.ToString()));
                    }
                }
            }

            return(View(profile));
        }
Beispiel #17
0
        public async Task <bool> UpdateStudentDetailsAsync(ProfileDto modUser, string studentId)
        {
            try
            {
                var user = (from a in context.ModelUsers
                            where a.Id == studentId
                            select a).SingleOrDefault();
                if (user != null)
                {
                    user.Id          = modUser.id;
                    user.Email       = modUser.Email;
                    user.FirstName   = modUser.FirstName;
                    user.LastName    = modUser.LastName;
                    user.PhoneNumber = modUser.PhoneNumber;
                    await context.SaveChangesAsync();

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #18
0
        public async Task <ApiResponse> uploadProfle([FromForm] ProfileDto dto)
        {
            try
            {
                if (dto.Id == Guid.Empty)
                {
                    return(new ApiResponse("Không tìm thấy Id: ", dto.Id, 400));
                }
                var user = await _userService.GetByIdAsync(dto.Id);

                if (user == null)
                {
                    return(new ApiResponse("User không tồn tại", user, 404));
                }
                MemoryStream ms = new MemoryStream();
                dto.ImageUser.CopyTo(ms);
                user.ImageUser = ms.ToArray();
                ms.Close();
                ms.Dispose();
                user.UpdatedDate = DateTime.Now;

                await _userService.UpdateAsync(user);

                var userViewModel = _mapper.Map <UserViewModel>(user);
                return(new ApiResponse("Update date user success: ", userViewModel, 200));
            }
            catch (Exception ex)
            {
                return(new ApiResponse($"{ex}", ex, 200));
            }
        }
Beispiel #19
0
        public IActionResult Put(int id, ProfileDto profileDto)
        {
            try
            {
                var tools = new SixTools(_httpContextAccessor);
                var user  = _userService.GetById(tools.GetUserTokenId());
                if (user == null)
                {
                    return(BadRequest(new { StatusCode = HttpStatusCode.BadRequest, message = "Usuário não localizado" }));
                }
                if (!user.Profile.Update)
                {
                    return(BadRequest(new { StatusCode = HttpStatusCode.BadRequest, message = "Usuário não possui permissão para realizar esta operacao" }));
                }
                var profile = _profileService.GetById(id);
                if (profile == null)
                {
                    return(BadRequest(new { StatusCode = HttpStatusCode.BadRequest, message = "Profile não localizado" }));
                }

                profile.Name      = profileDto.Name;
                profile.Create    = profileDto.Create;
                profile.Update    = profileDto.Update;
                profile.Delete    = profileDto.Delete;
                profile.IsAdmin   = profileDto.IsAdmin;
                profile.UpdatedAt = DateTime.Now;

                _profileService.Update(profile);
                return(Ok(_mapper.Map <ProfileDto>(profile)));
            }
            catch (Exception e)
            {
                return(BadRequest(new { StatusCode = HttpStatusCode.PreconditionFailed, message = e.Message }));
            }
        }
Beispiel #20
0
        public IHttpActionResult Profile(ProfileDto profileToUpdate)
        {
            var userId = GetUserIdFromContext();
            var dto    = _accountService.UpdateProfile(userId, profileToUpdate);

            return(Ok(dto));
        }
Beispiel #21
0
        public bool UpdateMentorDetails(ProfileDto modUser, string mentorId)
        {
            try
            {
                var user = (from a in context.MODUsers
                            where a.Id == mentorId
                            select a).SingleOrDefault();
                if (user != null)
                {
                    user.Id          = modUser.id;
                    user.Email       = modUser.Email;
                    user.FirstName   = modUser.FirstName;
                    user.LastName    = modUser.LastName;
                    user.PhoneNumber = modUser.PhoneNumber;
                    user.Skills      = modUser.Skills;
                    user.Experience  = modUser.Experience;

                    context.SaveChanges();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                return(false);
            }
        }
Beispiel #22
0
        public void ProfileDtoIsValid_WhenMissingData_ShouldReturnFalse()
        {
            this.profileDto = new ProfileDto();

            string msg = null;

            Assert.IsFalse(profileDto.IsValid(ref msg));
            Assert.AreEqual(msg, ErrorMessages.MissingFirstName);

            this.profileDto.FirstName = "FirstName";
            Assert.IsFalse(profileDto.IsValid(ref msg));
            Assert.AreEqual(msg, ErrorMessages.MissingLastName);

            this.profileDto.LastName = "LastName";
            Assert.IsFalse(profileDto.IsValid(ref msg));
            Assert.AreEqual(msg, ErrorMessages.MissingEmail);

            this.profileDto.Email = "Email";
            Assert.IsFalse(profileDto.IsValid(ref msg));
            Assert.AreEqual(msg, ErrorMessages.MissingPassword);

            this.profileDto.Password = "******";
            Assert.IsFalse(profileDto.IsValid(ref msg));
            Assert.AreEqual(msg, ErrorMessages.MissingAreaCode);

            this.profileDto.AreaCode = "AreaCode";
            Assert.IsFalse(profileDto.IsValid(ref msg));
            Assert.AreEqual(msg, ErrorMessages.MissingPhoneNumber);
        }
Beispiel #23
0
        public ProfileDto GetUserProfileByUserId(string userId)
        {
            var profile = _context.Profiles.FirstOrDefault(x => x.UserId == userId);

            if (profile == null)
            {
                return(null);
            }

            var result = new ProfileDto
            {
                Id                = profile.Id,
                UserId            = profile.UserId,
                FirstName         = profile.FirstName,
                LastName          = profile.LastName,
                Title             = profile.Title,
                Summary           = profile.Summary,
                Location          = profile.Location,
                Mobile            = profile.Mobile,
                Phone             = profile.Phone,
                IsAvailable       = profile.IsAvailable,
                AvailableFromDate = profile.AvailableFromDate,
                ImageUrl          = profile.ImageUrl,
                PortfolioUrl      = profile.PortfolioUrl,
                LinkedInUrl       = profile.LinkedInUrl,
                JoinDate          = profile.CreateDate
            };

            return(result);
        }
Beispiel #24
0
        public bool UpdateProfile(ProfileDto profile)
        {
            var record = _context.Profiles.FirstOrDefault(x => x.UserId == profile.UserId);

            if (record == null)
            {
                return(false);
            }

            record.FirstName         = profile.FirstName;
            record.LastName          = profile.LastName;
            record.Title             = profile.Title;
            record.Summary           = profile.Summary;
            record.Location          = profile.Location;
            record.Mobile            = profile.Mobile;
            record.Phone             = profile.Phone;
            record.IsAvailable       = profile.IsAvailable;
            record.AvailableFromDate = profile.AvailableFromDate;
            record.ImageUrl          = profile.ImageUrl;
            record.PortfolioUrl      = profile.PortfolioUrl;
            record.LinkedInUrl       = profile.LinkedInUrl;

            _context.Profiles.AddOrUpdate(record);
            return(_context.SaveChanges() == 1);
        }
Beispiel #25
0
        public bool UpdateStudentDetails(ProfileDto ModUser, string studentId)
        {
            try
            {
                var user = (from a in context.MODUsers
                            where a.Id == studentId
                            select a).SingleOrDefault();
                if (user != null)
                {
                    user.Id          = ModUser.id;
                    user.Email       = ModUser.Email;
                    user.FirstName   = ModUser.FirstName;
                    user.LastName    = ModUser.LastName;
                    user.PhoneNumber = ModUser.PhoneNumber;
                    user.Skill       = ModUser.Skill;
                    user.Experience  = ModUser.Experience;

                    context.SaveChanges();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                return(false);
            }
            throw new NotImplementedException();
        }
Beispiel #26
0
        private static void CreateProfiles()
        {
            var client = new DataServiceClient.DataServiceClient();

            var profile1 = new ProfileDto
            {
                Id   = 0,
                Name = "Administrator"
            };

            var profile2 = new ProfileDto
            {
                Id   = 0,
                Name = "Operator"
            };

            var profile3 = new ProfileDto
            {
                Id   = 0,
                Name = "Customer"
            };

            client.SaveProfile(profile1);
            client.SaveProfile(profile2);
            client.SaveProfile(profile3);
        }
        public async Task <IActionResult> ProfileInfo()
        {
            User user = (User)await this._manager.FindByNameAsync(HttpContext.User.Identity.Name);

            ProfileDto profile = new ProfileDto()
            {
                Email  = user.Email,
                Street = user.Street,
                Age    = user.Age,
                City   = user.City,
            };

            var orders = (from o in this._context.Orders
                          where o.UserId.Equals(user.Id)
                          join book in this._context.Books on o.Id equals book.OrderId
                          select new { o, book }).ToList();

            int    countbooks = orders.Count;
            double totalsum   = orders.Sum(o => o.book.Price);

            UserStatistic statistic = new UserStatistic()
            {
                TotalSum    = totalsum,
                CountBooks  = countbooks,
                CountOrders = user.Orders.Count
            };

            ViewData["statistic"] = statistic;

            return(View(profile));
        }
Beispiel #28
0
        public new async Task <ActionResult> Profile([Bind(Include = "Id,Name,Index,FirstName,LastName,School,Street,City,Country,Average,Passed,Subjects")] ProfileDto profile)
        {
            if (ModelState.IsValid)
            {
                Student dbStudent = await GetLoggedInStudent();

                dbStudent.Index           = profile.Index;
                dbStudent.FirstName       = profile.FirstName;
                dbStudent.LastName        = profile.LastName;
                dbStudent.School          = profile.School;
                dbStudent.Street          = profile.Street;
                dbStudent.City            = profile.City;
                dbStudent.Country         = profile.Country;
                db.Entry(dbStudent).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Profile"));
            }

            ProfileDto profileDto = new ProfileDto()
            {
                Index     = profile.Index,
                FirstName = profile.FirstName,
                LastName  = profile.LastName,
                School    = profile.School,
                Street    = profile.Street,
                City      = profile.City,
                Country   = profile.Country,
                Average   = profile.Average,
                Passed    = profile.Passed,
                Subjects  = profile.Subjects
            };

            return(View(profileDto));
        }
Beispiel #29
0
        public IEnumerable <RuleDto> ReadRules(ProfileDto profile, RuleDirectionDto direction)
        {
            int p = (int)profile, dir = (int)direction;
            var rules = rulesRepository
                        .Read(r => r.Direction == dir && r.Profile == p);

            return(mapper.Map <IEnumerable <RuleDto> >(rules));
        }
Beispiel #30
0
 public CommentDto(Comment comment)
 {
     Body      = comment.Body;
     CreatedAt = comment.CreatedAt;
     UpdatedAt = comment.UpdatedAt;
     Id        = comment.CommentId;
     Author    = new ProfileDto(comment.Author);
 }