Ydav Păcat
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Memoria Sprint 1 **Grupo** IS12.06 - Coconut JPG > **Miembros** > > - ALTÉS GÓMEZ-LECHÓN, Juan Antonio > > - MARTÍNEZ MOMPÓ, Pilar > > - MORANT JUAN, Nicolas > > - SINTIMBREAN, Daniel David ## 0. Introducción En el siguiente documento se incluye una descripción sobre la arquitectura empleada en nuestro proyecto *Quizify*, como también un análisis sobre el método fábrica y su aplicación. # 1. Arquitectura de la aplicación La arquitectura se basa principalmente en 4 capas - **Presentación o Interfaz de usuario**: donde estará la toda la interacción del usuario con la aplicación - **Lógica de negocio**: contiene toda la funcionalidad interna de aplicación. - **Repositorios**: facilita el acceso a la capa de la lógica de los objetos persistidos en la base de datos. - **Acceso a base datos**: establece la conexión a la base de datos y la proporciona a los repositorios. <center> <img src="https://i.imgur.com/6ApDNRw.png" alt="drawing" width="350"/> </center> *<center> Ilustración de la arquitectura empleada </center>* ## Presentación La capa de presentación se encarga de gestionar la interacción del usuario con la aplicación, encapsulando todas las entradas que este genera y distribuyéndolas a la capas inferiores (la lógica de negocio) para su posterior procesamiento. En el diseño de la interfaz gráfica se ha tomado la decisión de simplificarla al máximo para hacerla lo más amigable posible ante el usuario. Para ello, los formularios de la aplicación se estructuran de manera centralizada en torno al "MainStage"; un formulario que actua como ventana principal de la aplicación y desde el cual se puede acceder a las diferentes funcionalidades del Quizify, ya que actua de lanzadera para el resto. A continuación se muestra un pequeño esquema que ilustra la navegación dentro de la aplicación *Quizify* y el comportamiento del formulario lanzadera *MainStage* (figura central). <center> <img src="https://i.imgur.com/KtZojKa.jpg" alt="drawing" width="800"/> </center> *<center> Esquema de navegación de la aplicación </center>* Otro elemento a destacar de las interfaces es que estas cuentan con diferentes vistas según si accedes como usuario (opciones como crear quiz o curso no aparecen visibles) o si accedes como instructor (la opción de examinarse de un quiz no aparece disponible). <center> <img src="https://i.imgur.com/xLxdLDS.png" alt="drawing" width="600"/> </center> *<center> Diferencias entre la vista Instructor y Alumno </center>* ## Lógica de negocio La capa de lógica se encarga principalmente de comunicar la capa de presentación con los repositorios, creando métodos para enviar o recibir los datos necesarios de la interfaz a la base de datos o hacer consultas sobre los datos. Las clases de la capa de presentación, que así lo requieran, tienen asociadas una clase que se encarga de la lógica. <center> <img src="https://i.imgur.com/UopRGqT.png" alt="drawing" width="600"/> </center> Como primer ejemplo vamos a tratar el paso de datos de la capa de presentación hacia la base de datos. A la hora de registrar un usuario se pasan los datos introducidos en los campos de la interfaz hacia la capa lógica; dicha capa podrá llamar al método del repositorio específico para crear el ususario en la base de datos. **Método para guardar información en la base de datos:** ```csharp= public async Task<Student> RegisterNewStudent(String username, String password, String dni, String email) { Student student = new Student() { Username = username, Password = password, DNI = dni, Email = email }; StudentRepository repository = new StudentRepository(); await repository.Insert(student); return student; } ``` La instrucción de arriba `await repository.Insert(student)` accede al método del repositorio estudiante para crear un nuevo usuario en la base de datos a partir de los datos enviados desde la capa de presentación. Este método se ejecutará cuando en la capa de presentación se quiera crear un usuario a partir de los datos introducidos en la interfaz. Otro ejemplo sería hacer el camino inverso, es decir, recuperar información de la base de datos para mostrarlo a través de la interfaz. En el caso de la interfaz que muestra todos los quizzes por pantalla, la capa de presentación llamará a un método en la lógica el cual tendrá que devolver una lista con todos los quizzes, por lo tanto, la capa lógica será la encargada de llamar a un método del repositorio para conseguir dicha lista y pasarla hacia la capa de presentación. **Método para recuperar todos los quizzes de la base de datos:** ```csharp= public AllQuizzesLogic() { quiz = new QuizRepository(); } public async Task<List<Quiz>> GetAllQuizzes() { return (await quiz.GetAll()).ToList(); } ``` La instrucción `(await quiz.GetAll()).ToList()` accederá al repositorio de los quizzes para obtener en una lista todos los quizzes de la base de datos, este método se ejecutará cuando se llame desde la clase de la capa presentación que muestra todos los quizzes. Por último ejemplo trataremos la consulta de datos, para ello usaremos el caso de login de usuario en cual necesita consultar si el usuario y contraseña existe. **Metodos que comprueba si existe el usuario y la contraseña** ```csharp= public class LoginLogic { private StudentRepository student; private InstructorRepository instructor; public LoginLogic() { student = new StudentRepository(); instructor = new InstructorRepository(); } public async Task<bool> CheckUserName(string name) { var existsStudent = student.ExistsUsername(name); var existsInstructor = instructor.ExistsName(name); return await existsInstructor || await existsStudent; } public async Task<bool> UsernamePassword(string user, string password) { return await student.CheckStudentPassword(user, password); } public async Task<bool> InstructorPassword(string user, string password) { return await instructor.CheckInstrucotrPassword(user, password); } } ``` Estos dos metodos de la lógica de login se encargan de acceder al repositorio de usuarios o instructores y comprobar si existe el usuario con esa contraseña; la capa de presentación de login utilizará dichos métodos para comprobar los campos de la interfaz ## Repositorio La función del repositorio es facilitar y abstraer el acceso a la base de datos para que la capa de lógica simplemente tenga que utilizar los métodos que proporciona el repositorio. Actúa como una fachada de la base datos. Para ello, por cada colección *(recordemos que se está usando una base de datos NoSQL, por lo tanto no hablamos de tablas sino de colecciones)* en la base de datos existirá su repositorio correspondiente. De momento estamos utilizando 5 que son lo siguientes: `QuizRepository`, `StudentRespository`, `InstructorResitory`, `QuestionRepository` y `CourseRepository`. En cada repositorio estarán los métodos que se necesiten para interactuar con cada colección, al necesitar un repostorio por cada colección. Hay métodos que se usaran en todos ellos y serán prácticamente iguales, como por ejemplo `getById`, `getAll`, `insert`... estos métodos se incorporarán en la clase `BaseReposity`. Luego, cada implementación del repositorio herederá de este, por lo que ya tendrá el código base y simplemente se tendrá que añadir la funcionalidad específica que necesite, consiguiendo ahorrar código duplicado y simplificando el mantenimiento de este. Aquí se puede observar un fragmento de cómo quedaría la clase con los métodos genéricos. ```csharp= public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class { protected readonly IMongoQuizifyDBContext _mongoContext; protected IMongoCollection<TEntity> _dbCollection; protected BaseRepository() { _mongoContext = new MongoQuizifyDBContext(); _dbCollection = _mongoContext.GetCollection<TEntity>(); } public async Task Insert(TEntity obj) { if (obj == null) { throw new ArgumentNullException(typeof(TEntity).Name + " object is null"); } await _dbCollection.InsertOneAsync(obj); } public void Delete(string id) { var objectId = new ObjectId(id); _dbCollection.DeleteOneAsync(Builders<TEntity>.Filter.Eq("_id", objectId)); } public async Task<TEntity> GetById(string id) { var objectId = new ObjectId(id); FilterDefinition<TEntity> filter = Builders<TEntity>.Filter.Eq("_id", objectId); return await _dbCollection.FindAsync(filter).Result.FirstOrDefaultAsync(); } } ``` Y una implementación específica, en este caso de Quiz ```csharp= public class QuizRepository : BaseRepository<Quiz>, IQuizRepository { private CourseRepository _courseRepo; private StudentRepository _studentRepo; private InstructorRepository _instructorRepo; public QuizRepository() : base() { _courseRepo = new CourseRepository(); _studentRepo = new StudentRepository(); _instructorRepo = new InstructorRepository(); } public async Task<IEnumerable<Quiz>> StudentsQuizzez(string studentName) { List<Course> studentsCourses = (await _courseRepo.GetStudentsCourses(studentName)).ToList(); List<Quiz> quizzes = new List<Quiz>(); foreach (var couse in studentsCourses) { List<Quiz> courseQuizz = (await CoursesQuizzez(couse)).ToList(); foreach (var quizz in courseQuizz) { quizzes.Add(quizz); } } return quizzes; } public async Task<IEnumerable<Quiz>> IstructorQuizzez(string instructorName) { var instructor = await _instructorRepo.GetByName(instructorName); var filter = Builders<Quiz>.Filter.Eq(quiz => quiz.Author, instructor.Id); return (await _dbCollection.FindAsync(filter)).ToList(); } public async Task<IEnumerable<Quiz>> CoursesQuizzez(string couseName) { Course course = await _courseRepo.GetByName(couseName); return await CoursesQuizzez(course); } } ``` ## Conexión a base de datos Esta capa únicamente se encarga de proporcionar la conexión desde la base de datos hacia los repositorios, y luego, dependiendo del repositorio, cada uno acederá a la colección que le corresponde. Aquí se aplica el patrón *singleton*: se comprueba si existe una instancia de conexión a la base de datos (`IMongoDatabase`), si esta ya existe, te la devuelve; en caso contraio te crea una nueva. Con esto nos evitamos que cada repositorio tenga varias conexiónes diferente a la base de datos, y así todos comparten la misma. El código quedaría de la siguiente manera: ```csharp= public class MongoConexion { private static volatile IMongoDatabase _mongoDatabase; private static readonly object _lock = new object(); public static IMongoDatabase ConectToDataBase() { if (_mongoDatabase != null) { return _mongoDatabase; } lock (_lock) { if (_mongoDatabase == null) { var settings = MongoClientSettings. FromConnectionString(ConfigurationManager.AppSettings.Get("monogoURL")); var client = new MongoClient(settings); _mongoDatabase = client.GetDatabase("QuizifyDB"); } return _mongoDatabase; } } } ``` ## 2. Aplicación de Método Fábrica Para la implementación se ha decido hacerlo con una fábrica de `Answers`, que es un clase que forma parte de los atributos de `Questions`. Para los distintos tipos de preguntas simplemente hay que cambiar el tipo de la respuesta. <center><img src="https://i.imgur.com/BV6Gek5.png" /></center> *<center>Imagen de pregunta y respuesta en MongoDB</center>* En esta última imagen se muestra una pregunta con todos sus atributos. El cuarto atributo (`Answers`) es el objeto que representa las respuestas dependiento del tipo que sea la pregunta. Por el momento se crearán 3 tipos de fábricas para los 3 tipos de preguntas que vamos a implementar: - `MultipleChoiceFactory` - `TrueFalseFactory` - `OpenFactory` Para gestionar cuál es la respuesta correcta se usará un enumerado `CorrectAnswer` para crear el objeto respuesta, el cual luego se guardará como atributo de una pregunta. Para el primer sprint solo tenemos la opción de crear preguntas de tipo test (fábrica de `MultipleChoiceFactory`), pero ya hemos creado las fábricas de preguntas de verdadero y falso (`TrueFalseFactory`) y la fábrica de respuestas abiertas (`OpenFactory`). Cada vez que se llama al método de la fábrica, se comprueba que los datos introducidos sean correctos. En caso de no serlo, se lanzará un excepción que se gestionará en lógica. El código quedaría de la siguiente manera: ```csharp= public abstract class AnswersType { public List<string> AnswersList { get; set; } public int? CorrectAnswer { get; set; } } [Flags] public enum CorrectAnswer : int { Open = 0, First = 1 << 0, Second = 1 << 1, Third = 1 << 2, Fourth = 1 << 3, False = 1 << 5, True = 1 << 6, } public abstract class AnswersFactory { public abstract AnswersType createAswer(List<string> answers, CorrectAnswer? correctAnswer); } public class TrueFalseFactory : AnswersFactory { public override AnswersType createAswer(List<string> answers, CorrectAnswer? correctAnswer) { if (!(correctAnswer == CorrectAnswer.False || correctAnswer == CorrectAnswer.True)) { throw new ArgumentException("CorrectAnswer must be true or false"); } return new TrueFalse() { AnswersList = new List<string>() { "False", "True" }, CorrectAnswer = (int?)correctAnswer >> 6, }; } } public class MultipleChoiceFactoy : AnswersFactory { public MultipleChoiceFactoy() { } public override AnswersType createAswer(List<string> answers, CorrectAnswer? correctAnswer) { if (answers.Count != 4) { throw new ArgumentException("Answers for multiple choice must be 4"); } return new MultipleChoice() { AnswersList = answers, CorrectAnswer = (int?)Math.Log((double)correctAnswer, 2), }; } } ``` Y las preguntas se generarían de esta otra: ```csharp= public static async Task CreateAndInsertQuestion() { List<string> Answers = new List<string>() { "Respuesta falsa 1", "Respuesta falsa 2", "Respuesta falsa 3", "Respuesta verdadera", }; MultipleChoiceFactoy MCFactory = new MultipleChoiceFactoy(); TrueFalseFactory TFFactory = new TrueFalseFactory(); Question question1 = new Question() { Answers = MCFactory.createAswer(Answers, CorrectAnswer.Fourth), Author = (await _instructorRepo.GetByName("Paquito")).Id, QuestionValue = new decimal(2.5), Statement = "Esta es la pregunta número 1", }; Question question2 = new Question() { Answers = TFFactory.createAswer(null, CorrectAnswer.True), Author = (await _instructorRepo.GetByName("Paquito")).Id, QuestionValue = new decimal(2.5), Statement = "Esta es verdadera", }; } ``` ## 3. Estructura en MongoDB La base de datos la tenemos dividida en 5 colecciones: <center> <img src="https://i.imgur.com/kbmAdzT.png" alt="drawing" width="250"/> </center> Y la estructura interna de cada uno de ellos:P *Colección Curso* <img src="https://i.imgur.com/x7lEgPj.png" alt="drawing" width="450"/> *** *Colección Instructor* <img src="https://i.imgur.com/H37aprl.png" alt="drawing" width="350"/> *** *Colección Question* <img src="https://i.imgur.com/OAGZWKj.png" alt="drawing" width="350"/> *** *Colección Quiz* <img src="https://i.imgur.com/BBXlY1B.png" alt="drawing" width="350"/> *** *Colección Student* <img src="https://i.imgur.com/yM6Su1W.png" alt="drawing" width="350"/>

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully