コード例 #1
0
        /// <summary>
        /// This function checks if the incoming username exists in the database
        /// </summary>
        /// <param name="dto"> Username dto from Business layer to Data Access Layer </param>

        public UsernameResponseDTO CheckUserName(UsernameDTO dto)
        {
            UsernameResponseDTO response = new UsernameResponseDTO();
            List <string>       messages = new List <string>();

            try
            {
                string username = (from x in db.Credentials
                                   where x.UserName == dto.Username
                                   select x.UserName).FirstOrDefault();
                if (dto.Username == username)
                {
                    response.isSuccessful = false;
                    messages.Add("Username already exists. Please try again");
                    response.Messages = messages;
                }
                else
                {
                    response.isSuccessful = true;
                }
            }
            catch (SqlException)
            {
                response.isSuccessful = false;
                messages.Add("Your request could not be made. Please try again.");
                response.Messages = messages;
            }
            catch (DataException)
            {
                response.isSuccessful = false;
                messages.Add("Your request could not be made. Please try again.");
                response.Messages = messages;
            }
            return(response);
        }
コード例 #2
0
        public async Task <ActionResult <List <PostAndKeyword> > > GetWriterPost([FromBody] UsernameDTO usernameDTO)
        {
            List <TblPosts>       listNotHaving = getListPostNotInHavingPosts(usernameDTO.Username);
            List <TblPosts>       listResponse  = new List <TblPosts>();
            List <PostAndKeyword> listPostAndKeywordResponse = new List <PostAndKeyword>();

            for (int i = 0; i < listNotHaving.Count; i++)
            {
                TblPosts currentPost = listNotHaving[i];
                if (currentPost.PostType.Equals("Writer"))
                {
                    listResponse.Add(currentPost);

                    PostAndKeyword postAndKeyword = new PostAndKeyword();
                    postAndKeyword.Id              = currentPost.Id;
                    postAndKeyword.Title           = currentPost.Title;
                    postAndKeyword.Description     = currentPost.Description;
                    postAndKeyword.CharacterLimit  = currentPost.CharacterLimit;
                    postAndKeyword.Amount          = currentPost.Amount;
                    postAndKeyword.PostType        = currentPost.PostType;
                    postAndKeyword.RelatedDocument = currentPost.RelatedDocument;
                    postAndKeyword.IsPublic        = currentPost.IsPublic;
                    postAndKeyword.CreatedDate     = currentPost.CreatedDate;
                    postAndKeyword.Status          = currentPost.Status;
                    postAndKeyword.listKeywords    = findListKeyByPostId(currentPost.Id);

                    listPostAndKeywordResponse.Add(postAndKeyword);
                }
            }

            return(listPostAndKeywordResponse);
        }
コード例 #3
0
        public async Task <ActionResult <TblUsers> > setStatus(UsernameDTO usernameDTO)
        {
            TblUsers userEntity = _context.TblUsers
                                  .FromSqlRaw("select * from tblUsers where Username = {0}", usernameDTO.Username).First();

            if (userEntity != null)
            {
                if (userEntity.Status.Equals("active"))
                {
                    userEntity.Status = "banned";
                    _context.Entry(userEntity).State = EntityState.Modified;
                    await _context.SaveChangesAsync();
                }
                else if (userEntity.Status.Equals("banned"))
                {
                    userEntity.Status = "active";
                    _context.Entry(userEntity).State = EntityState.Modified;
                    await _context.SaveChangesAsync();
                }
            }
            else
            {
                return(NotFound());
            }
            return(userEntity);
        }
コード例 #4
0
        //Return ReviewDetailDTO
        public IEnumerable <ReviewDetailDTO> GetUserReviewDetails(UsernameDTO obj)
        {
            //gets user's ID from userprofile
            int getUserID = (from cred in db.Credentials
                             where obj.Username == cred.UserName
                             select cred.UserID).FirstOrDefault();

            //get the sequence of reviewees that reviewed user
            var revieweeID = (from rev in db.Review
                              where getUserID == rev.UserID
                              select rev.RevieweeID).FirstOrDefault();

            //gets username based off of the revie
            var revieweeUsername = (from cred in db.Credentials
                                    where revieweeID == cred.UserID
                                    select cred.UserName).FirstOrDefault();

            return(from b in db.Review
                   join cred in db.Credentials
                   on b.UserID equals cred.UserID
                   where obj.Username == cred.UserName
                   select new ReviewDetailDTO()
            {
                ReviewMessage = b.ReviewMessage,
                Rating = b.Rating,
                DateAndTime = b.DateAndTime
            });
        }
コード例 #5
0
        public void GetWorkouts()
        {
            List <WorkoutLogDTO> container = new List <WorkoutLogDTO>();
            UsernameDTO          u         = new UsernameDTO
            {
                Username = "******"
            };

            container.AddRange(test.GetWorkouts(u));
            //container = test.GetWorkouts("Latmay").ToList<WorkoutLogDTO>();
            bool hasSomething = !container.Any();

            Assert.True(hasSomething);
        }
コード例 #6
0
        public IHttpActionResult ProfileData([FromBody] UsernameDTO obj)
        {
            // Creates service to handle request
            UserProfileService temp = new UserProfileService();
            var response            = temp.GetProfile(obj);

            // Was the request handled?
            if (!response.IsSuccessful)
            {
                // Return failure notice to front end
                return(Content(HttpStatusCode.NotFound, "Error: " + response.Messages));
            }
            // Request was handled, sending success to front end with data
            return(Content(HttpStatusCode.OK, response.Data));
        }
コード例 #7
0
        public async Task <ActionResult <List <TblPosts> > > GetCompanyPosts(UsernameDTO usernameDTO)
        {
            List <TblPosts>            listCompanyPosts = new List <TblPosts>();
            List <TblUsersHavingPosts> listCreatedPosts = _context.TblUsersHavingPosts
                                                          .FromSqlRaw("select PostId from tblUsersHavingPosts where Username = {0} and Status = 'created'", usernameDTO.Username)
                                                          .ToList <TblUsersHavingPosts>();

            for (int i = 0; i < listCreatedPosts.Count; i++)
            {
                TblUsersHavingPosts curCreatedPost = listCreatedPosts[i];
                TblPosts            companyPost    = _context.TblPosts.Find(curCreatedPost);
                listCompanyPosts.Add(companyPost);
            }
            return(listCompanyPosts);
        }
コード例 #8
0
        /// <summary>
        /// Validates the user credentials of the registraion information
        /// </summary>
        /// <param name="userCred"> User Credentials of the registration information </param>
        /// <returns> status if the credentials are valid based on business rules </returns>
        public bool ValidateUserCred(UserCredential userCred)
        {
            var messages = new List <string>();

            // Returns error if user credentials are null
            if (userCred == null)
            {
                Response.isSuccessful = false;
                messages.Add(AccountConstants.REGISTRATION_INVALID);
                Response.Messages = messages;
                return(false);
            }
            var validator = new UserCredValidator();
            var results   = validator.Validate(userCred);

            IList <ValidationFailure> failures = results.Errors;

            // Returns any error messages if there was any when validating
            if (failures.Any())
            {
                foreach (ValidationFailure failure in failures)
                {
                    messages.Add(failure.ErrorMessage);
                }
                Response.isSuccessful = false;
                Response.Messages     = messages;
                return(false);
            }

            var dto = new UsernameDTO()
            {
                Username = userCred.Username
            };

            // Checks username in the database
            var gateway         = new RegistrationGateway();
            var gatewayResponse = gateway.CheckUserName(dto);

            // Return error if theres any error messages
            if (!gatewayResponse.isSuccessful)
            {
                Response.isSuccessful = false;
                Response.Messages     = gatewayResponse.Messages;
                return(false);
            }

            return(true);
        }
        public async Task <ActionResult <IEnumerable <HistoryRecordDTO> > > Mine([FromBody] UsernameDTO usernameDTO)
        {
            if (string.IsNullOrWhiteSpace(usernameDTO.Username))
            {
                return(BadRequest("Invalid username"));
            }

            ICollection <HistoryData>?result = await MarketUserService.GetUserHistory(usernameDTO.Username);

            if (result == null)
            {
                return(InternalServerError());
            }

            return(Ok(result.Select(HistoryRecordDTO.FromHistoryData)));
        }
        public IHttpActionResult SingleScholarAccountInformation(UsernameDTO usernameDTO)
        {
            Account requestedAccount;

            // Verifying the requested account exists
            if (_accountLogic.Exists(usernameDTO.username))
            {
                requestedAccount = _accountLogic.GetByUsername(usernameDTO.username);
            }
            // The requested account does not exist.
            else
            {
                return(BadRequest("The requested account with the given username does not exist!"));
            }
            return(Json(new { requestedAccount.AccountStatus }));
        }
        public async Task <ActionResult> Logout([FromBody] UsernameDTO usernameDTO)
        {
            if (string.IsNullOrWhiteSpace(usernameDTO.Username))
            {
                return(BadRequest("Invalid username"));
            }

            string?result = await MarketUserService.Instance.logoutAsync(usernameDTO.Username);

            if (string.IsNullOrWhiteSpace(result))
            {
                return(InternalServerError());
            }

            return(Ok(result));
        }
コード例 #12
0
        //Enumerable returns workotu objects
        public IEnumerable <WorkoutLogDTO> GetWorkouts(UsernameDTO obj)
        {
            int getUserID = (from cred in db.Credentials
                             where obj.Username == cred.UserName
                             select cred.UserID).FirstOrDefault();
            //get workout DTO from cardio table
            var car = (from work in db.Workouts
                       join cred in db.Credentials
                       on work.UserID equals cred.UserID
                       where obj.Username == cred.UserName
                       join card in db.Cardios
                       on work.WorkoutLogID equals card.WorkoutID
                       select new WorkoutLogDTO()
            {
                WorkoutType = work.WorkoutType,
                Date_Time = work.Date_Time,
                LiftingType = null,
                Reps = 0,
                Sets = 0,
                CardioType = card.CardioType,
                Distance = card.Distance,
                Time = card.Time
            });
            //get workout DTO from weightlifting table
            var weigh = (from work in db.Workouts
                         join cred in db.Credentials
                         on work.UserID equals cred.UserID
                         where obj.Username == cred.UserName
                         join weight in db.WeightLiftings
                         on work.WorkoutLogID equals weight.WorkoutID
                         select new WorkoutLogDTO()
            {
                WorkoutType = work.WorkoutType,
                Date_Time = work.Date_Time,
                LiftingType = weight.LiftingType,
                Reps = weight.Reps,
                Sets = weight.Sets,
                CardioType = null,
                Distance = 0,
                Time = null
            });
            //union two workoutDTO and returns by date descending
            var logs = (car.Union(weigh).OrderByDescending(m => m.Date_Time));

            return(logs);
        }
コード例 #13
0
ファイル: UserLogic.cs プロジェクト: GeorgeMi/AzurePollApp
        /// <summary>
        /// Returnarea listei cu toti userii si id-urile asociate
        /// </summary>
        /// <returns></returns>
        public List <UsernameDTO> GetAllUsernames()
        {
            List <User>        userList    = _dataAccess.UserRepository.GetAll().ToList();
            List <UsernameDTO> userDtoList = new List <UsernameDTO>();
            UsernameDTO        userDTO;

            foreach (User u in userList)
            {
                userDTO          = new UsernameDTO();
                userDTO.Username = u.Username;
                userDTO.UserID   = u.UserID;

                userDtoList.Add(userDTO);
            }

            return(userDtoList.ToList());
        }
コード例 #14
0
        public async Task <ActionResult <List <PostAndKeyword> > > GetAcceptedPosts(UsernameDTO usernameDTO)
        {
            List <TblUsersHavingPosts> listRequested = _context.TblUsersHavingPosts
                                                       .FromSqlRaw("select * from tblUsersHavingPosts where Username = {0} and Status = 'requested'", usernameDTO.Username)
                                                       .ToList <TblUsersHavingPosts>();
            List <TblPosts> listAccepted = _context.TblPosts
                                           .FromSqlRaw("select * from tblPosts where Id in " +
                                                       "(select PostId from tblUsersHavingPosts where Username = {0} and Status = 'accepted')", usernameDTO.Username)
                                           .ToList <TblPosts>();

            List <TblPosts>       listResponse = new List <TblPosts>();
            List <PostAndKeyword> listPostAndKeywordResponse = new List <PostAndKeyword>();

            if (listAccepted.Count > 0)
            {
                for (int i = 0; i < listAccepted.Count; i++)
                {
                    TblPosts currentPost = listAccepted[i];
                    if (currentPost.PostType.Equals("Writer") || currentPost.PostType.Equals("Design") || currentPost.PostType.Equals("Translate"))
                    {
                        listResponse.Add(currentPost);

                        PostAndKeyword postAndKeyword = new PostAndKeyword();
                        postAndKeyword.Id              = currentPost.Id;
                        postAndKeyword.Title           = currentPost.Title;
                        postAndKeyword.Description     = currentPost.Description;
                        postAndKeyword.CharacterLimit  = currentPost.CharacterLimit;
                        postAndKeyword.Amount          = currentPost.Amount;
                        postAndKeyword.PostType        = currentPost.PostType;
                        postAndKeyword.RelatedDocument = currentPost.RelatedDocument;
                        postAndKeyword.IsPublic        = currentPost.IsPublic;
                        postAndKeyword.CreatedDate     = currentPost.CreatedDate;
                        postAndKeyword.Status          = currentPost.Status;
                        postAndKeyword.listKeywords    = findListKeyByPostId(currentPost.Id);

                        listPostAndKeywordResponse.Add(postAndKeyword);
                    }
                }
                _context.TblUsersHavingPosts.RemoveRange(listRequested);
                await _context.SaveChangesAsync();

                return(listPostAndKeywordResponse);
            }
            return(null);
        }
コード例 #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public ResponseDTO <ProfileDTO> GetProfile(UsernameDTO obj)
        {
            // Creates ResponseDTO for transfering data and error messages between layers.
            ResponseDTO <ProfileDTO> response = new ResponseDTO <ProfileDTO>();

            if (!ValidateUserName(obj.Username))
            {
                response.IsSuccessful = false;
                response.Messages.Add("Invalid userName.");
                return(response);
            }
            // Creating Profile Gateway to access data
            UserProfileGateway userProfileDb = new UserProfileGateway();

            // sending data from Gateway back to response object
            response = userProfileDb.GetProfile(obj);
            return(response);
        }
コード例 #16
0
 public IHttpActionResult Getfollows([FromBody] UsernameDTO userDTO)
 {
     if (HttpContext.Current.Request.HttpMethod == "POST")
     {
         requestedUser.UserName = userDTO.Username;
         if (followsGateway.DoesUserNameExists(requestedUser))
         {
             return(Ok(followService.GetEnumerator(userDTO.Username)));
         }
         else
         {
             return(Content(HttpStatusCode.NotAcceptable, new { }));
         }
     }
     else
     {
         return(Content(HttpStatusCode.MethodNotAllowed, new { }));
     }
 }
コード例 #17
0
        public void GetProfileTest()
        {
            // Arrange
            UserProfileService service = new UserProfileService();
            UsernameDTO        obj     = new UsernameDTO()
            {
                Username = "******"
            };
            // Act
            var response = service.GetProfile(obj);

            // Assert
            Assert.True(response.IsSuccessful);
            Assert.Equal("April", response.Data.FirstName);
            Assert.Equal("May", response.Data.LastName);
            Assert.Equal("Female", response.Data.Gender);
            Assert.Equal("Beginner", response.Data.SkillLevel);
            Assert.Equal("SomeDescription", response.Data.Description);
            Assert.Null(response.Data.ProfilePicture);
        }
コード例 #18
0
        public IActionResult IsUsernameTaken([FromBody] UsernameDTO username)
        {
            if (username == null)
            {
                return(BadRequest("There was a problem with the validation of the request parameters for verify existing username"));
            }

            try
            {
                bool exist = _contract.CheckIfUsernameExist(username.Username);
                return(Ok(exist));
            }
            catch (ValidationException ex)
            {
                return(BadRequest(ex.Message));
            }
            catch (Exception ex)
            {
                return(InternalServerError(ex.Message));
            }
        }
コード例 #19
0
        public IHttpActionResult Addfollows([FromBody] UsernameDTO userDTO)
        {
            string[] Users = userDTO.Username.Split(' ');
            requestedUser.UserName = Users[0];
            var wantoFollo = Users[1];

            if (HttpContext.Current.Request.HttpMethod == "POST")
            {
                if (followsGateway.DoesUserNameExists(requestedUser))
                {
                    return(Ok(followService.Add(requestedUser.UserName, wantoFollo)));
                }
                else
                {
                    return(Content(HttpStatusCode.NotAcceptable, new { }));
                }
            }
            else
            {
                return(Content(HttpStatusCode.MethodNotAllowed, new { }));
            }
        }
コード例 #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public ResponseDTO <ProfileDTO> GetProfile(UsernameDTO obj)
        {
            ResponseDTO <ProfileDTO> response = new ResponseDTO <ProfileDTO>();
            var foundProfile = (from user in db.Credentials
                                join profile in db.UserProfiles
                                on user.UserID equals profile.UserID
                                where user.UserName == obj.Username
                                select profile).FirstOrDefault();

            if (foundProfile == null)
            {
                // Return failure in responseDTO
                response.IsSuccessful = false;
                response.Data         = null;
                return(response);
            }
            // Found user, sending data back to frontend
            response.Data         = new ProfileDTO(foundProfile.FirstName, foundProfile.LastName, foundProfile.Description, foundProfile.SkillLevel, foundProfile.Email, foundProfile.Gender, foundProfile.ProfilePicture);
            response.IsSuccessful = true;
            response.Messages.Add("User Found, retrieving data.");
            return(response);
        }
        public ActionResult <ShoppingCartDTO> MyShoppingCart([FromBody] UsernameDTO usernameDTO)
        {
            if (string.IsNullOrWhiteSpace(usernameDTO.Username))
            {
                return(BadRequest("Invalid username"));
            }

            Dictionary <NamedGuid, Dictionary <ProductData, int> >?result = MarketShoppingCartService.ViewShoppingCart(usernameDTO.Username);

            if (result == null)
            {
                return(InternalServerError());
            }

            Dictionary <Guid, double>?prices = MarketShoppingCartService.ViewShoppingCartsUpdatedPrice(usernameDTO.Username);

            if (prices == null)
            {
                return(InternalServerError());
            }

            return(Ok(ShoppingCartDTO.FromDictionaries(result, prices)));
        }
        public async Task <ActionResult <IEnumerable <BidUserDTO> > > MineAsync([FromBody] UsernameDTO usernameDTO)
        {
            if (string.IsNullOrWhiteSpace(usernameDTO.Username))
            {
                return(BadRequest("Invalid username"));
            }

            Result <ICollection <Bid> >?result = MarketBidsService.GetCustomerBids(usernameDTO.Username);

            if (result == null || (result.IsErr && string.IsNullOrWhiteSpace(result.Mess)))
            {
                return(InternalServerError());
            }
            if (result.IsErr)
            {
                return(InternalServerError(result.Mess));
            }

            // TODO: fetch store names as well using a designated service layer function
            IEnumerable <BidUserDTO> userBids = result.Ret.Select(BidUserDTO.FromBid).ToList();

            foreach (BidUserDTO userBid in userBids)
            {
                StoreData?store = await MarketStoreGeneralService.getStoreById(userBid.StoreId);

                if (store == null)
                {
                    return(InternalServerError());
                }

                userBid.StoreName = store.Name;
                ProductData?product = store.Products.FirstOrDefault(p => p.pid == userBid.ProductId);
                userBid.ProductName = product?._name;
            }
            return(Ok(userBids));
        }
コード例 #23
0
        //Returns Review objects to front end, ReviewMessage, Rating, and Datetime
        public IEnumerable <WorkoutLogDTO> GetUserWorkouts(UsernameDTO obj)
        {
            var gateway = new WorkoutLogGateway();

            return(gateway.GetWorkouts(obj));
        }
コード例 #24
0
        public IEnumerable <WorkoutLogDTO> GetWorkout(UsernameDTO obj)
        {
            WorkoutLogGateway service = new WorkoutLogGateway();

            return(service.GetWorkouts(obj));
        }
コード例 #25
0
        public IEnumerable <ReviewDetailDTO> GetUserReview(UsernameDTO obj)
        {
            ReviewService service = new ReviewService();

            return(service.GetUserReview(obj));
        }
コード例 #26
0
        public async Task <ActionResult <List <TransactionHistoryShowUp> > > GetTransactionHistoryByName(UsernameDTO usernameDTO)
        {
            List <TransactionHistoryShowUp> listResponse    = new List <TransactionHistoryShowUp>();
            List <TransactionHistory>       listTransaction = _context.TransactionHistory
                                                              .FromSqlRaw("select * from TransactionHistory where Receiver = {0}", usernameDTO.Username).ToList <TransactionHistory>();

            for (int i = 0; i < listTransaction.Count; i++)
            {
                TransactionHistory       current  = listTransaction[i];
                TransactionHistoryShowUp response = new TransactionHistoryShowUp();
                response.PostTitle       = _context.TblPosts.Find(current.PostId).Title;
                response.TransactionDate = current.TransactionDate;
                response.Amount          = current.Amount;
                listResponse.Add(response);
            }
            return(listResponse);
        }
コード例 #27
0
        public async Task <ActionResult <int> > GetUserBeans(UsernameDTO usernameDTO)
        {
            int amount = (int)_context.TblUsers.Find(usernameDTO.Username).Amount;

            return(amount);
        }
コード例 #28
0
ファイル: ReviewService.cs プロジェクト: rsanchez-dv/WhatFits
        //Returns Review objects to front end, ReviewMessage, Rating, and Datetime
        public IEnumerable <ReviewDetailDTO> GetUserReview(UsernameDTO obj)
        {
            var gateway = new ReviewsGateway();

            return(gateway.GetUserReviewDetails(obj));
        }