コード例 #1
0
ファイル: FeedTasks.cs プロジェクト: Tom-Knighton/EduChat-API
        public async Task <FeedPost> UploadQuizPost(FeedQuiz quiz)
        {
            using (var conn = new MySqlConnection(connString)) //New connection
            {
                await conn.OpenAsync();                        //Waits for connection to open

                using (var cmd = new MySqlCommand($"INSERT INTO feed_post VALUES({0}, 'quiz', {quiz.posterId}, {quiz.subjectId}, '{quiz.datePosted.ToString("yyyy-MM-dd hh:mm:ss")}', " +
                                                  $"{Convert.ToBoolean(quiz.isAnnouncement)}, {Convert.ToBoolean(quiz.isDeleted)});", conn)) //Inserts post into feed_post
                {
                    await cmd.ExecuteNonQueryAsync();                                                                                        //Executes that command

                    int id = (int)cmd.LastInsertedId;                                                                                        //Gets the last inserted auto incremented id
                    using (var cmd2 = new MySqlCommand($"INSERT INTO feed_quiz_post VALUES({id}, '{quiz.QuizTitle}', '{quiz.DifficultyLevel}');", conn))
                        await cmd2.ExecuteNonQueryAsync();                                                                                   //Inserts value into feed_quiz_post values
                    string questionsCommand = "";                                                                                            //Sets up an empty string
                    foreach (FeedQuizQuestion question in quiz.Questions)                                                                    //For each question in the questions array
                    {                                                                                                                        // Add to the questionsCommand string, insert each feed_quiz_question row
                        questionsCommand += $" INSERT INTO feed_quiz_question VALUES({0}, {id}, '{question.Question}', " +
                                            $"'{question.Answers[0]}', '{question.Answers[1]}', '{question.Answers[2]}', '{question.Answers[3]}', '{question.CorrectAnswer}', {question.Difficulty});";
                    }
                    using (var cmd3 = new MySqlCommand(questionsCommand, conn)) //Executes all the commands above
                        await cmd3.ExecuteNonQueryAsync();
                    return(await GetPostById(id));                              //Returns the FeedQuiz object
                }
            }
        }
コード例 #2
0
ファイル: FeedTasks.cs プロジェクト: Tom-Knighton/EduChat-API
        public async Task <FeedPost> GetPostById(int postid)
        {
            using (var conn = new MySqlConnection(connString))                                                //Creates a temporary new Connectio
            {
                await conn.OpenAsync();                                                                       //Waits for connection to open

                using (var cmd = new MySqlCommand($"SELECT * FROM feed_post WHERE `PostId`={postid};", conn)) //Select command to get the row of the id
                    using (var reader = await cmd.ExecuteReaderAsync())                                       //Executes the above command
                    {
                        if (await reader.ReadAsync())                                                         //If any row was returned
                        {
                            FeedPost post = new FeedPost                                                      //Create new FeedPost object from our returned values
                            {
                                postId     = Convert.ToInt32(reader["postId"]), posterId = Convert.ToInt32(reader["posterId"]),
                                postType   = reader["postType"].ToString(), subjectId = Convert.ToInt32(reader["subjectId"]),
                                datePosted = Convert.ToDateTime(reader["datePosted"]), isAnnouncement = Convert.ToBoolean(reader["isAnnouncement"]),
                                isDeleted  = Convert.ToBoolean(reader["isDeleted"]), poster = await new UserTasks().GetUserById(Convert.ToInt32(reader["posterId"]), flatten: true),
                                likes      = await GetAllLikesForPost(Convert.ToInt32(reader["postId"]))
                            };
                            string json = Json.Stringify(post);                       //Convert the above object into a json string
                            switch (post.postType)                                    //What to do for each post type
                            {
                            case "text":                                              //IF it is a text post
                                FeedTextPost tPost = Json.Parse <FeedTextPost>(json); //Convert the above json into a FeedTextPost object
                                tPost = await AddTextPostValues(tPost);               //Create a new object from the above one, with our additional text values

                                return(tPost);                                        //return it

                            case "media":
                                FeedMediaPost mPost = Json.Parse <FeedMediaPost>(json); //Convert the abve json intoa FeedMediaPost object
                                mPost = await AddMediaPostValues(mPost);                //Create a new object from the above, with our additional media values

                                return(mPost);                                          //return it

                            case "poll":                                                //If it is a poll
                                FeedPoll pPost = Json.Parse <FeedPoll>(json);           //Convert above json to a FeedPoll object
                                pPost = await AddPollPostValues(pPost);                 //Create a new object from the above, including additional values

                                return(pPost);                                          //return it

                            case "quiz":
                                FeedQuiz fPost = Json.Parse <FeedQuiz>(json); //Convert json into FeedQuiz object
                                fPost = await AddBasicQuizValues(fPost);      //Adds quiz values

                                return(fPost);                                //return it

                            default: return(null);                            //If the switch statement fails, return nothing.
                            }
                        }
                    }
                return(null); //If no row is returned, return nothing.
            }
        }
コード例 #3
0
ファイル: FeedTasks.cs プロジェクト: Tom-Knighton/EduChat-API
        //QUIZ:
        public async Task <FeedQuiz> GetFullFeedQuiz(int QuizId)
        {
            FeedQuiz quiz = (FeedQuiz) await GetPostById(QuizId); //Gets base FeedPost obkect

            List <FeedQuizQuestion> questions = new List <FeedQuizQuestion>();
            List <FeedQuizResult>   results   = new List <FeedQuizResult>();

            using (var conn = new MySqlConnection(connString)) //New connection
            {
                await conn.OpenAsync();                        //Waits for connection to open

                using (var questionsCmd = new MySqlCommand($"SELECT * FROM feed_quiz_question WHERE PostId={QuizId};", conn))
                    // ^ selects all rows in the question table for this quiz
                    using (var qReader = await questionsCmd.ExecuteReaderAsync()) //reads the data
                        while (await qReader.ReadAsync())                         //For each row returndd
                        {
                            questions.Add(new FeedQuizQuestion                    //Add a new Question object to the array
                            {
                                PostId        = QuizId, QuestionId = Convert.ToInt32(qReader["questionId"]),
                                CorrectAnswer = qReader["correctAnswer"].ToString(),
                                Answers       = new List <string> {
                                    qReader["answer1"].ToString(), qReader["answer2"].ToString(),
                                    qReader["answer3"].ToString(), qReader["answer4"].ToString()
                                },
                                Difficulty = Convert.ToInt32(qReader["questionDifficulty"]),
                                Question   = qReader["question"].ToString()
                            });
                        }
                using (var resultsCmd = new MySqlCommand($"SELECT * FROM feed_quiz_result WHERE PostId={QuizId};", conn))
                    // ^ Selects all rows in the result table for this quiz
                    using (var rReader = await resultsCmd.ExecuteReaderAsync())
                    {                                      //Reads the data
                        while (await rReader.ReadAsync())
                        {                                  //For each row returned
                            results.Add(new FeedQuizResult //Adds a new Result object to the array
                            {
                                PostId       = QuizId,
                                UserId       = Convert.ToInt32(rReader["userId"]),
                                OverallScore = Convert.ToInt32(rReader["overallScore"]),
                                User         = await new UserTasks().GetUserById(Convert.ToInt32(rReader["userId"]), flatten: true),
                                DatePosted   = Convert.ToDateTime(rReader["datePosted"])
                            });
                        }
                        quiz.Questions = questions; quiz.Results = results; //Adds questions and results
                        return(quiz);                                       //Returns modified quiz object
                    }
            }
        }
コード例 #4
0
ファイル: FeedTasks.cs プロジェクト: Tom-Knighton/EduChat-API
        public async Task <FeedQuiz> AddBasicQuizValues(FeedQuiz quiz)
        {
            using (var conn = new MySqlConnection(connString)) //New connection
            {
                await conn.OpenAsync();                        //Waits to open

                using (var cmd = new MySqlCommand($"SELECT * FROM feed_quiz_post WHERE `PostId`={quiz.postId};", conn))
                    //^ Selects all data from feed_quiz for our post
                    using (var reader = await cmd.ExecuteReaderAsync()) //reads the data
                    {
                        if (await reader.ReadAsync())                   //IF we found anything
                        {
                            quiz.QuizTitle       = reader["postTitle"].ToString();
                            quiz.DifficultyLevel = reader["overallDifficulty"].ToString();
                            return(quiz);
                        }
                    }
                return(null); //else return nothing
            }
        }
コード例 #5
0
 public async Task <IActionResult> UploadQuiz([FromBody] FeedQuiz quiz)
 {
     return(Ok(await new FeedTasks().UploadQuizPost(quiz)));
 }