public async Task CanUnEnrollFromCpaForAllSkus()
        {
            EnrollmentResponse result = await priceApi.SetupAllCpaSku(false);

            Assert.IsType <EnrollmentResponse>(result);
            Assert.False(result.EnrollStatus);
        }
        /// <summary>
        /// Enrolls the audio of the speaker
        /// </summary>
        /// <param name="audioStream">The audio stream</param>
        private async void enrollSpeaker(Stream audioStream)
        {
            try
            {
                Stopwatch          sw       = Stopwatch.StartNew();
                EnrollmentResponse response = await _serviceClient.EnrollStreamAsync(audioStream, _speakerId);

                sw.Stop();
                _remainingEnrollments = response.RemainingEnrollments;
                setStatus("Enrollment Done, Elapsed Time: " + sw.Elapsed);
                verPhraseText.Text = response.Phrase;
                setStatus("Your phrase: " + response.Phrase);
                setUserPhrase(response.Phrase);
                remEnrollText.Text = response.RemainingEnrollments.ToString();
                if (response.RemainingEnrollments == 0)
                {
                    MessageBox.Show("You have now completed the minimum number of enrollments. You may perform verification or add more enrollments", "Speaker enrolled");
                }
                resetBtn.IsEnabled = true;
                IsolatedStorageHelper _storageHelper = IsolatedStorageHelper.getInstance();
                _storageHelper.writeValue(MainWindow.SPEAKER_ENROLLMENTS, "Done");
            }
            catch (EnrollmentException exception)
            {
                setStatus("Cannot enroll speaker: " + exception.Message);
            }
            catch (Exception gexp)
            {
                setStatus("Error: " + gexp.Message);
            }
        }
Пример #3
0
        /// <summary>
        /// Deserialize JSON into a FHIR EnrollmentResponse
        /// </summary>
        public static void DeserializeJson(this EnrollmentResponse current, ref Utf8JsonReader reader, JsonSerializerOptions options)
        {
            string propertyName;

            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndObject)
                {
                    return;
                }

                if (reader.TokenType == JsonTokenType.PropertyName)
                {
                    propertyName = reader.GetString();
                    if (Hl7.Fhir.Serialization.FhirSerializerOptions.Debug)
                    {
                        Console.WriteLine($"EnrollmentResponse >>> EnrollmentResponse.{propertyName}, depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    reader.Read();
                    current.DeserializeJsonProperty(ref reader, options, propertyName);
                }
            }

            throw new JsonException($"EnrollmentResponse: invalid state! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
        }
Пример #4
0
        public IActionResult PromoteStudent(PromoteStudentsRequest request)
        {
            var studies = _dbContext.Studies.Where(st => st.Name.Equals(request.Studies));

            if (studies.Count() == 0)
            {
                return(NotFound("Brak studiów o podanym kierunku"));
            }

            var study = studies.First();

            var enrollments = _dbContext.Enrollment.Where(en => en.IdStudy == study.IdStudy && en.Semester == request.Semester);

            if (enrollments.Count() == 0)
            {
                return(NotFound("Brak wpisów na 1 semestr dla podanego kierunku"));
            }

            var id = enrollments.First().IdEnrollment;

            _dbContext.Database.ExecuteSqlRaw($"promotestudents {request.Studies} {request.Semester}");

            _dbContext.SaveChanges();

            var enrollment = _dbContext.Enrollment.Find(id);

            var response = new EnrollmentResponse();

            response.IdEnrollment = enrollment.IdEnrollment;
            response.Semester     = enrollment.Semester;
            response.IdStudy      = enrollment.IdStudy;
            response.StartDate    = enrollment.StartDate;

            return(Created("", response));
        }
        public async Task CanEnrollInCpaForAllSkus()
        {
            EnrollmentResponse result = await priceApi.SetupAllCpaSku(true);

            Assert.IsType <EnrollmentResponse>(result);
            Assert.True(result.EnrollStatus);
        }
Пример #6
0
        public IActionResult EnrollStudent(EnrollmentRequest enrollment)
        {
            // sprawdzam poprawność danych
            if (enrollment.IndexNumber == "")
            {
                return(BadRequest());
            }
            if (enrollment.FirstName == "")
            {
                return(BadRequest());
            }
            if (enrollment.LastName == "")
            {
                return(BadRequest());
            }
            if (enrollment.BirthDate == "")
            {
                return(BadRequest());
            }
            if (enrollment.Studies == "")
            {
                return(BadRequest());
            }

            EnrollmentResponse enrollmentResponse = __service.enrollment(enrollment);

            if (enrollmentResponse == null)
            {
                return(BadRequest());
            }

            return(CreatedAtAction("enroll", enrollmentResponse));
        }
Пример #7
0
        public IActionResult EnrollStudent(EnrollStudentRequest request)
        {
            var student = _dbContext.Student.Find(request.IndexNumber);

            if (student != null)
            {
                return(BadRequest("Podano zły nr indeksu"));
            }

            var studies = _dbContext.Studies.Where(s => s.Name.Equals(request.Studies));

            if (studies.Count() == 0)
            {
                return(NotFound("Podane studia nie istnieją"));
            }

            var enrollments = _dbContext.Enrollment.Where(en => en.IdStudy == studies.First().IdStudy&& en.Semester == 1)
                              .OrderByDescending(en => en.StartDate);
            Enrollment enrollment;

            if (enrollments.Count() == 0)
            {
                enrollment = new Enrollment();

                enrollment.IdEnrollment = Convert.ToInt32(_dbContext.Enrollment.Max(en => en.IdEnrollment)) + 1;
                enrollment.Semester     = 1;
                enrollment.IdStudy      = studies.First().IdStudy;
                enrollment.StartDate    = DateTime.Now.Date;

                _dbContext.Enrollment.Add(enrollment);
            }
            else
            {
                enrollment = enrollments.First();
            }

            //dodanie studenta
            student = new Student();

            student.IndexNumber  = request.IndexNumber;
            student.FirstName    = request.FirstName;
            student.LastName     = request.LastName;
            student.BirthDate    = DateTime.Parse(request.BirthDate);
            student.IdEnrollment = enrollment.IdEnrollment;

            var response = new EnrollmentResponse();

            response.IdEnrollment = enrollment.IdEnrollment;
            response.Semester     = enrollment.Semester;
            response.IdStudy      = enrollment.IdStudy;
            response.StartDate    = enrollment.StartDate;

            _dbContext.Student.Add(student);

            _dbContext.SaveChanges();

            return(Created("", response));
        }
Пример #8
0
        public EnrollmentResponse PromoteStudents(EnrollPromoteRequest enrollPromoteRequest)
        {
            using (SqlConnection con =
                       new SqlConnection("Data Source=db-mssql;Initial Catalog=s19267;Integrated Security=True"))
                using (SqlCommand com = new SqlCommand())
                {
                    com.Connection = con;

                    con.Open();
                    var tran = con.BeginTransaction();
                    com.Transaction = tran;

                    //idStudy
                    com.CommandText = "select IdStudy from Studies where name=@studiesName";
                    com.Parameters.AddWithValue("studiesName", enrollPromoteRequest.studies);
                    var dr = com.ExecuteReader();
                    if (!dr.Read())
                    {
                        tran.Rollback();
                        return(null);
                    }

                    int idStudies = (int)dr["IdStudy"];
                    dr.Close();

                    //Enrollments
                    com.CommandText = "select IdEnrollment from Enrollment where Semester=@semester and IdStudy=@idStudy";
                    com.Parameters.AddWithValue("semester", enrollPromoteRequest.semester);
                    com.Parameters.AddWithValue("idStudy", idStudies);
                    dr = com.ExecuteReader();
                    if (!dr.Read())
                    {
                        tran.Rollback();
                        return(null);
                    }

                    dr.Close();

                    com.CommandText = " Exec promoteStudents @studiesName, @semester";
                    dr = com.ExecuteReader();
                    if (dr.Read())
                    {
                        EnrollmentResponse response = new EnrollmentResponse
                        {
                            Semester     = (int)dr["Semester"],
                            IdEnrollment = (int)dr["IdEnrollment"],
                            IdStudy      = (int)dr["IdStudy"],
                            StartDate    = dr["StartDate"].ToString()
                        };
                        dr.Close();
                        tran.Commit();
                        return(response);
                    }

                    return(null);
                }
        }
Пример #9
0
        public IActionResult Promote(EnrollPromoteRequest enrollPromoteRequest)
        {
            EnrollmentResponse enrollmentResponse = _studentsDbService.PromoteStudents(enrollPromoteRequest);

            if (enrollmentResponse == null)
            {
                return(BadRequest("studia nie istnieją"));
            }
            else
            {
                return(CreatedAtAction("createStudent", enrollmentResponse));
            }
        }
Пример #10
0
        public EnrollmentResponse PromoteStudents(PromoteStudentsRequest request)
        {
            APBDContext context = new APBDContext();
            //istnienie wpisów
            Enrollment enr = context.Enrollment
                             .Where(x => x.Semester == request.Semester)
                             .Where(x => x.IdStudy == context.Studies.Where(y => y.Name == request.Studies).FirstOrDefault().IdStudy)
                             .FirstOrDefault();

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

            //istnienie wpisu +1
            Enrollment enr2 = context.Enrollment
                              .Where(x => x.Semester == request.Semester + 1)
                              .Where(x => x.IdStudy == enr.IdStudy)
                              .FirstOrDefault();

            if (enr2 == null)
            {
                context.Enrollment.Add(enr2 = new Enrollment {
                    Semester     = request.Semester + 1,
                    StartDate    = DateTime.Today,
                    IdEnrollment = context.Enrollment.Select(x => x.IdEnrollment).Max() + 1,
                    IdStudy      = enr.IdStudy
                });
            }


            //promocja studentów
            var students = context.Student
                           .Where(x => x.IdEnrollment == enr.IdEnrollment).ToList();

            foreach (Student s in students)
            {
                s.IdEnrollment = enr2.IdEnrollment;
            }
            context.SaveChanges();

            // stworzenie Enrollmentu
            EnrollmentResponse enrResp = new EnrollmentResponse();

            enrResp.Semester  = enr2.Semester;
            enrResp.StudyName = request.Studies;
            enrResp.StartDate = enr2.StartDate.ToString();

            return(enrResp);
        }
Пример #11
0
        public IActionResult CreateEnrollment([FromBody] EnrollmentRequest request)
        {
            var study = _context.Studies
                        .Where(s => s.Name == request.Studies)
                        .FirstOrDefault();

            if (study == null)
            {
                return(BadRequest("study not found"));
            }

            var enrollent = _context.Enrollment
                            .Where(e => e.IdStudy == study.IdStudy)
                            .Where(e => e.Semester == 1)
                            .FirstOrDefault();

            if (enrollent == null)
            {
                enrollent = new Enrollment();
                Random rnd = new Random();
                // should be set by db sequence
                enrollent.IdEnrollment = rnd.Next(1, 10000);
                enrollent.IdStudy      = study.IdStudy;
                enrollent.Semester     = 1;
                enrollent.StartDate    = DateTime.Today;

                _context.Enrollment.Add(enrollent);
            }

            var student = new Student();

            student.IndexNumber  = request.IndexNumber;
            student.FirstName    = request.FirstName;
            student.LastName     = request.LastName;
            student.BirthDate    = request.BirthDate;
            student.IdEnrollment = enrollent.IdEnrollment;

            _context.Student.Add(student);

            _context.SaveChanges();

            var response = new EnrollmentResponse();

            response.LastName  = student.LastName;
            response.Semester  = enrollent.Semester;
            response.StartDate = enrollent.StartDate;
            return(Ok(response));
        }
Пример #12
0
        public EnrollmentResponse PromoteStudents(PromoteStudentsRequest request)
        {
            using (var con = new SqlConnection(ConStr))
                using (var com = new SqlCommand())
                {
                    com.Connection = con;
                    con.Open();

                    // istnienie wpisów
                    com.CommandText = "select idEnrollment from Enrollment e, Studies s " +
                                      " where e.idStudy=s.idStudy " +
                                      " and s.Name=@Studies and e.Semester=@Semester";
                    com.Parameters.AddWithValue("Studies", request.Studies);
                    com.Parameters.AddWithValue("Semester", request.Semester);
                    SqlDataReader sdr = com.ExecuteReader();
                    if (!sdr.Read())
                    {
                        sdr.Close();
                        return(null);
                    }
                    sdr.Close();

                    // procedura skladowana
                    SqlCommand cmd = new SqlCommand("dbo.promoteStudents", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@Studies", SqlDbType.VarChar).Value = request.Studies;
                    cmd.Parameters.Add("@Semester", SqlDbType.Int).Value    = request.Semester;
                    //cmd.ExecuteNonQuery();

                    // stworzenie Enrollmentu
                    EnrollmentResponse enr = new EnrollmentResponse();
                    sdr = cmd.ExecuteReader();
                    sdr.Read();
                    enr.Semester  = (int)(sdr["Semester"]);
                    enr.StudyName = sdr["Name"].ToString();
                    enr.StartDate = sdr["StartDate"].ToString();

                    return(enr);
                }
        }
        public async Task <EnrollmentResponse> SetupAllCpaSku(bool enroll)
        {
            // to avoid deadlock if this method is executed synchronously
            await new ContextRemover();

            Base.Http.Request request = CreateRequest();
            request.EndpointUri = "/v3/cppreference";
            var content = JsonConvert.SerializeObject(new Payload.Cpa.Enrollment()
            {
                Enroll = enroll
            });

            request.HttpRequest.Content = new StringContent(content, Encoding.UTF8, "application/json");
            request.HttpRequest.Headers.Add("Accept", "application/json");

            Base.Http.IResponse response = await client.PostAsync(request);

            var responseContent = await response.GetPayloadAsString();

            EnrollmentResponse result = JsonConvert.DeserializeObject <EnrollmentResponse>(responseContent);

            return(result);
        }
        public EnrollmentResponse EnrollStudent(EnrollmentRequest enrollmentRequest)
        {
            var studyId       = GetStudyId(enrollmentRequest.Studies);
            var enrollmentId  = GetEnrollmentId(1, studyId);
            var insertRequest = new InsertStudentRequest()
            {
                IndexNumber  = enrollmentRequest.IndexNumber,
                FirstName    = enrollmentRequest.FirstName,
                LastName     = enrollmentRequest.LastName,
                BirthDate    = enrollmentRequest.BirthDate,
                Password     = enrollmentRequest.Password,
                IdEnrollment = enrollmentId.ToString()
            };

            _studentDb.InsertStudent(insertRequest);

            EnrollmentResponse response = new EnrollmentResponse()
            {
                LastName = enrollmentRequest.LastName,
                Semester = 1
            };

            return(response);
        }
Пример #15
0
        public EnrollmentResponse EnrollNewStudentEntity(EnrollmentStudentRequest enrollmentStudentRequest)
        {
            var context = new StudentDbContext();
            var studies = context.Studies
                          .FirstOrDefault(stud => enrollmentStudentRequest.Studies.Equals(stud.Name));

            if (studies == null)
            {
                throw new ResourceNotFoundException("Studies with name = " + enrollmentStudentRequest.Studies
                                                    + " dont exist");
            }

            var enrollment = context.Enrollment.FirstOrDefault(enroll => 1.Equals(enroll.Semester) &&
                                                               studies.IdStudy.Equals(enroll.IdStudy));

            var enrollmentResponse = new EnrollmentResponse();

            if (enrollment == null)
            {
                var enrollmentNew = new Enrollment
                {
                    IdEnrollment = context.Enrollment.Select(enroll =>
                                                             enroll.IdEnrollment).OrderByDescending(i => i).First() + 1,
                    Semester  = 1,
                    StartDate = DateTime.Now,
                    IdStudy   = studies.IdStudy
                };

                context.Enrollment.Add(enrollmentNew);

                enrollmentResponse.IdEnrollment = enrollmentNew.IdEnrollment;
                enrollmentResponse.Semester     = enrollmentNew.Semester;
                enrollmentResponse.IdStudy      = enrollmentNew.IdStudy;
                enrollmentResponse.StartDate    = enrollmentNew.StartDate.ToString("yyyy-MM-dd");
            }
            else
            {
                enrollmentResponse.IdEnrollment = enrollment.IdEnrollment;
                enrollmentResponse.Semester     = enrollment.Semester;
                enrollmentResponse.IdStudy      = enrollment.IdStudy;
                enrollmentResponse.StartDate    = enrollment.StartDate.ToString("yyyy-MM-dd");
            }

            if (context.Student.Any(student => enrollmentStudentRequest.Index.Equals(student.IndexNumber)))
            {
                throw new BadRequestException("Student Index number not unique");
                ;
            }

            var salt = PasswordUtils.GenerateSalt();

            context.Student.Add(new Student
            {
                IndexNumber  = enrollmentStudentRequest.Index,
                FirstName    = enrollmentStudentRequest.FirstName,
                LastName     = enrollmentStudentRequest.LastName,
                BirthDate    = enrollmentStudentRequest.BirthDate,
                IdEnrollment = enrollmentResponse.IdEnrollment,
                Password     = PasswordUtils.CreateSaltedPasswordHash(enrollmentStudentRequest.Password, salt),
                Salt         = salt
            });

            context.SaveChanges();

            return(enrollmentResponse);
        }
Пример #16
0
        public EnrollmentResponse EnrollStudent(EnrollStudentRequest request)
        {
            var enr = new EnrollmentResponse();
            // request
            APBDContext context = new APBDContext();

            //istnienie studiow
            Studies studies = context.Studies.Where(x => x.Name == request.Studies).FirstOrDefault();

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

            //wpis do tabeli enrollment
            //czy wpis istnieje
            Enrollment enrollment = context.Enrollment
                                    .Where(x => x.IdStudy == studies.IdStudy)
                                    .Where(x => x.Semester == 1)
                                    .FirstOrDefault();

            // jesli nie to dodaj wpis
            if (enrollment == null)
            {
                enrollment = new Enrollment
                {
                    Semester     = 1,
                    StartDate    = DateTime.Today,
                    IdEnrollment = context.Enrollment.Select(x => x.IdEnrollment).Max() + 1,
                    IdStudy      = studies.IdStudy
                };
                context.Enrollment.Add(enrollment);
            }

            //sprawdzenie unikalnosci indeksu
            if (context.Student.Select(x => x.IndexNumber).Any(x => x == request.IndexNumber))
            {
                return(null);
            }

            //dodanie studenta
            Student student = new Student
            {
                IndexNumber  = request.IndexNumber,
                FirstName    = request.FirstName,
                LastName     = request.LastName,
                BirthDate    = DateTime.ParseExact(request.BirthDate, "yyyy-mm-dd", System.Globalization.CultureInfo.InvariantCulture),
                IdEnrollment = enrollment.IdEnrollment
            };

            context.Student.Add(student);
            context.SaveChanges();

            // stworzenie Enrollmentu

            enr.Semester  = enrollment.Semester;
            enr.StudyName = studies.Name;
            enr.StartDate = enrollment.StartDate.ToString();

            return(enr);
        }
Пример #17
0
        public EnrollmentResponse enrollment(EnrollmentRequest enrollment)
        {
            using (SqlConnection connect = new SqlConnection(conString))
                using (SqlCommand command = new SqlCommand())
                {
                    command.Connection = connect;
                    connect.Open();
                    var tran = connect.BeginTransaction();
                    command.Transaction = tran;
                    try
                    {
                        // sprawdzam, czy sa studia
                        command.CommandText = "select IdStudy from Studies where Name=@StudiesName";
                        command.Parameters.AddWithValue("StudiesName", enrollment.Studies);
                        SqlDataReader dr = command.ExecuteReader();
                        if (!dr.Read())
                        {
                            dr.Close();
                            tran.Rollback();
                            return(null);
                        }
                        int StudiesId = dr.GetInt32(0);
                        dr.Close();
                        // pobieram najnowszy rekord z tabeli enrollments dla studiów i semestru
                        command.CommandText = "select IdEnrollment from Enrollment where Semester=1 AND IdStudy=@IdStudy";
                        command.Parameters.AddWithValue("IdStudy", StudiesId);
                        dr = command.ExecuteReader();
                        int enrollmentId = 0;
                        if (!dr.Read())
                        {
                            dr.Close();

                            // dodaję wpis w tabeli Enrollment
                            DateTime currentDateTime = DateTime.Now;
                            command.CommandText = "INSERT INTO Enrollment(Semester, IdStudy, StartDate) VALUES(1, @IdStudy, @CurrDateTime)";
                            command.Parameters.AddWithValue("IdStudy", StudiesId);
                            command.Parameters.AddWithValue("CurrDateTime", currentDateTime);
                            command.ExecuteNonQuery();

                            command.CommandText = "select IdEnrollment from Enrollment where Semester=1 AND IdStudy=@IdStudy";
                            command.Parameters.Add("@IdStudy");
                            command.Parameters["@IdStudy"].Value = StudiesId;
                            dr = command.ExecuteReader();
                            dr.Read();
                            enrollmentId = dr.GetInt32(0);
                        }
                        else
                        {
                            enrollmentId = dr.GetInt32(0);
                        }
                        dr.Close();

                        // dodaję wpis w tabeli Enrollment
                        command.CommandText = "INSERT INTO Student(IndexNumber, FirstName, LastName, BirthDate, IdEnrollment) VALUES (@StudentId, @FirstName, @LastName, @BirtyDay, @EnrollmentId)";
                        command.Parameters.AddWithValue("StudentId", enrollment.IndexNumber);
                        command.Parameters.AddWithValue("FirstName", enrollment.FirstName);
                        command.Parameters.AddWithValue("LastName", enrollment.LastName);
                        command.Parameters.AddWithValue("BirtyDay", Convert.ToDateTime(enrollment.BirthDate));
                        command.Parameters.AddWithValue("EnrollmentId", enrollmentId);
                        command.ExecuteNonQuery();
                        tran.Commit();

                        var enrollmentResponse = new EnrollmentResponse();
                        enrollmentResponse.EnrollmentId = enrollmentId;
                        enrollmentResponse.IndexNumber  = enrollment.IndexNumber;
                        enrollmentResponse.FirstName    = enrollment.FirstName;
                        enrollmentResponse.LastName     = enrollment.LastName;
                        enrollmentResponse.BirthDate    = enrollment.BirthDate;

                        return(enrollmentResponse);
                    } catch (SqlException e)
                    {
                        tran.Rollback();
                        return(null);
                    }
                }
        }
Пример #18
0
        /// <summary>
        /// Deserialize JSON into a FHIR EnrollmentResponse
        /// </summary>
        public static void DeserializeJsonProperty(this EnrollmentResponse current, ref Utf8JsonReader reader, JsonSerializerOptions options, string propertyName)
        {
            switch (propertyName)
            {
            case "identifier":
                if ((reader.TokenType != JsonTokenType.StartArray) || (!reader.Read()))
                {
                    throw new JsonException($"EnrollmentResponse error reading 'identifier' expected StartArray, found {reader.TokenType}! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                }

                current.Identifier = new List <Identifier>();

                while (reader.TokenType != JsonTokenType.EndArray)
                {
                    Hl7.Fhir.Model.Identifier v_Identifier = new Hl7.Fhir.Model.Identifier();
                    v_Identifier.DeserializeJson(ref reader, options);
                    current.Identifier.Add(v_Identifier);

                    if (!reader.Read())
                    {
                        throw new JsonException($"EnrollmentResponse error reading 'identifier' array, read failed! depth: {reader.CurrentDepth}, pos: {reader.BytesConsumed}");
                    }
                    if (reader.TokenType == JsonTokenType.EndObject)
                    {
                        reader.Read();
                    }
                }

                if (current.Identifier.Count == 0)
                {
                    current.Identifier = null;
                }
                break;

            case "status":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.StatusElement = new Code <Hl7.Fhir.Model.FinancialResourceStatusCodes>();
                    reader.Skip();
                }
                else
                {
                    current.StatusElement = new Code <Hl7.Fhir.Model.FinancialResourceStatusCodes>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral <Hl7.Fhir.Model.FinancialResourceStatusCodes>(reader.GetString()));
                }
                break;

            case "_status":
                if (current.StatusElement == null)
                {
                    current.StatusElement = new Code <Hl7.Fhir.Model.FinancialResourceStatusCodes>();
                }
                ((Hl7.Fhir.Model.Element)current.StatusElement).DeserializeJson(ref reader, options);
                break;

            case "request":
                current.Request = new Hl7.Fhir.Model.ResourceReference();
                ((Hl7.Fhir.Model.ResourceReference)current.Request).DeserializeJson(ref reader, options);
                break;

            case "outcome":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.OutcomeElement = new Code <Hl7.Fhir.Model.ClaimProcessingCodes>();
                    reader.Skip();
                }
                else
                {
                    current.OutcomeElement = new Code <Hl7.Fhir.Model.ClaimProcessingCodes>(Hl7.Fhir.Utility.EnumUtility.ParseLiteral <Hl7.Fhir.Model.ClaimProcessingCodes>(reader.GetString()));
                }
                break;

            case "_outcome":
                if (current.OutcomeElement == null)
                {
                    current.OutcomeElement = new Code <Hl7.Fhir.Model.ClaimProcessingCodes>();
                }
                ((Hl7.Fhir.Model.Element)current.OutcomeElement).DeserializeJson(ref reader, options);
                break;

            case "disposition":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.DispositionElement = new FhirString();
                    reader.Skip();
                }
                else
                {
                    current.DispositionElement = new FhirString(reader.GetString());
                }
                break;

            case "_disposition":
                if (current.DispositionElement == null)
                {
                    current.DispositionElement = new FhirString();
                }
                ((Hl7.Fhir.Model.Element)current.DispositionElement).DeserializeJson(ref reader, options);
                break;

            case "created":
                if (reader.TokenType == JsonTokenType.Null)
                {
                    current.CreatedElement = new FhirDateTime();
                    reader.Skip();
                }
                else
                {
                    current.CreatedElement = new FhirDateTime(reader.GetString());
                }
                break;

            case "_created":
                if (current.CreatedElement == null)
                {
                    current.CreatedElement = new FhirDateTime();
                }
                ((Hl7.Fhir.Model.Element)current.CreatedElement).DeserializeJson(ref reader, options);
                break;

            case "organization":
                current.Organization = new Hl7.Fhir.Model.ResourceReference();
                ((Hl7.Fhir.Model.ResourceReference)current.Organization).DeserializeJson(ref reader, options);
                break;

            case "requestProvider":
                current.RequestProvider = new Hl7.Fhir.Model.ResourceReference();
                ((Hl7.Fhir.Model.ResourceReference)current.RequestProvider).DeserializeJson(ref reader, options);
                break;

            // Complex: EnrollmentResponse, Export: EnrollmentResponse, Base: DomainResource
            default:
                ((Hl7.Fhir.Model.DomainResource)current).DeserializeJsonProperty(ref reader, options, propertyName);
                break;
            }
        }
Пример #19
0
        /// <summary>
        /// Serialize a FHIR EnrollmentResponse into JSON
        /// </summary>
        public static void SerializeJson(this EnrollmentResponse current, Utf8JsonWriter writer, JsonSerializerOptions options, bool includeStartObject = true)
        {
            if (includeStartObject)
            {
                writer.WriteStartObject();
            }
            writer.WriteString("resourceType", "EnrollmentResponse");
            // Complex: EnrollmentResponse, Export: EnrollmentResponse, Base: DomainResource (DomainResource)
            ((Hl7.Fhir.Model.DomainResource)current).SerializeJson(writer, options, false);

            if ((current.Identifier != null) && (current.Identifier.Count != 0))
            {
                writer.WritePropertyName("identifier");
                writer.WriteStartArray();
                foreach (Identifier val in current.Identifier)
                {
                    val.SerializeJson(writer, options, true);
                }
                writer.WriteEndArray();
            }

            if (current.StatusElement != null)
            {
                if (current.StatusElement.Value != null)
                {
                    writer.WriteString("status", Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.StatusElement.Value));
                }
                if (current.StatusElement.HasExtensions() || (!string.IsNullOrEmpty(current.StatusElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_status", false, current.StatusElement.Extension, current.StatusElement.ElementId);
                }
            }

            if (current.Request != null)
            {
                writer.WritePropertyName("request");
                current.Request.SerializeJson(writer, options);
            }

            if (current.OutcomeElement != null)
            {
                if (current.OutcomeElement.Value != null)
                {
                    writer.WriteString("outcome", Hl7.Fhir.Utility.EnumUtility.GetLiteral(current.OutcomeElement.Value));
                }
                if (current.OutcomeElement.HasExtensions() || (!string.IsNullOrEmpty(current.OutcomeElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_outcome", false, current.OutcomeElement.Extension, current.OutcomeElement.ElementId);
                }
            }

            if (current.DispositionElement != null)
            {
                if (!string.IsNullOrEmpty(current.DispositionElement.Value))
                {
                    writer.WriteString("disposition", current.DispositionElement.Value);
                }
                if (current.DispositionElement.HasExtensions() || (!string.IsNullOrEmpty(current.DispositionElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_disposition", false, current.DispositionElement.Extension, current.DispositionElement.ElementId);
                }
            }

            if (current.CreatedElement != null)
            {
                if (!string.IsNullOrEmpty(current.CreatedElement.Value))
                {
                    writer.WriteString("created", current.CreatedElement.Value);
                }
                if (current.CreatedElement.HasExtensions() || (!string.IsNullOrEmpty(current.CreatedElement.ElementId)))
                {
                    JsonStreamUtilities.SerializeExtensionList(writer, options, "_created", false, current.CreatedElement.Extension, current.CreatedElement.ElementId);
                }
            }

            if (current.Organization != null)
            {
                writer.WritePropertyName("organization");
                current.Organization.SerializeJson(writer, options);
            }

            if (current.RequestProvider != null)
            {
                writer.WritePropertyName("requestProvider");
                current.RequestProvider.SerializeJson(writer, options);
            }

            if (includeStartObject)
            {
                writer.WriteEndObject();
            }
        }
Пример #20
0
        public EnrollmentResponse EnrollStudent(EnrollStudentRequest request)
        {
            var enr = new EnrollmentResponse();

            // request
            using (var con = new SqlConnection(ConStr))
                using (var com = new SqlCommand())
                {
                    com.Connection = con;
                    con.Open();
                    var tran = con.BeginTransaction();
                    com.Transaction = tran;

                    // istnienie studiów
                    com.CommandText = "select idStudy from Studies where Name=@Name";
                    com.Parameters.AddWithValue("Name", request.Studies);
                    SqlDataReader sdr = com.ExecuteReader();
                    if (!sdr.Read())
                    {
                        sdr.Close();
                        tran.Rollback();
                        return(null);
                    }
                    int idStudy = (int)sdr["IdStudy"];
                    sdr.Close();

                    // wpis w tabeli enrollment
                    int idEnrollment;
                    com.CommandText = "select IdEnrollment from Enrollment" +
                                      " where idStudy=@idStudy and Semester=1" +
                                      " order by IdEnrollment";
                    com.Parameters.AddWithValue("idStudy", idStudy);
                    sdr = com.ExecuteReader();
                    if (!sdr.Read())
                    {
                        sdr.Close();

                        //pobranie max idEnrollment
                        int idMaxEnroll = 0;
                        com.CommandText = "select max(idEnrollment) as idEnrollment from Enrollment";
                        sdr             = com.ExecuteReader();
                        if (sdr.Read())
                        {
                            idMaxEnroll = (int)sdr["idEnrollment"];
                        }
                        sdr.Close();
                        idEnrollment = idMaxEnroll + 1;

                        //dodanie wpisu
                        com.CommandText = "insert into Enrollment(Semester, IdStudy, StartDate, idEnrollment) " +
                                          " values(@Semester,@IdStudy,@StartDate, @idEnroll);";
                        com.Parameters.AddWithValue("Semester", 1);
                        com.Parameters.AddWithValue("StartDate", DateTime.Today);
                        com.Parameters.AddWithValue("idEnroll", idEnrollment);
                        com.ExecuteNonQuery();
                    }
                    else
                    {
                        idEnrollment = (int)sdr["IdEnrollment"];
                        sdr.Close();
                    }

                    //sprawdzenie unikalnosci indeksu
                    com.CommandText = "select LastName from Student" +
                                      " where IndexNumber=@IndexNumber";
                    com.Parameters.AddWithValue("IndexNumber", request.IndexNumber);
                    sdr = com.ExecuteReader();
                    if (sdr.Read())
                    {
                        sdr.Close();
                        tran.Rollback();
                        return(null);
                    }
                    sdr.Close();

                    //dodanie studenta
                    com.CommandText = "insert into Student" +
                                      "(IndexNumber, FirstName, LastName, BirthDate, IdEnrollment) " +
                                      "values(@IndexNumber, @FirstName, @LastName, @BirthDate, @IdEnrollment) ";
                    com.Parameters.AddWithValue("FirstName", request.FirstName);
                    com.Parameters.AddWithValue("LastName", request.LastName);
                    com.Parameters.AddWithValue("BirthDate", request.BirthDate);
                    com.Parameters.AddWithValue("IdEnrollment", idEnrollment);
                    com.ExecuteNonQuery();

                    tran.Commit();

                    // stworzenie Enrollmentu
                    com.CommandText = "select Semester, Name, StartDate from Studies, Enrollment " +
                                      "where Studies.IdStudy=Enrollment.IdStudy " +
                                      "and idEnrollment=@IdEnrollment ";

                    sdr = com.ExecuteReader();
                    sdr.Read();
                    enr.Semester  = (int)(sdr["Semester"]);
                    enr.StudyName = sdr["Name"].ToString();
                    enr.StartDate = sdr["StartDate"].ToString();
                }
            return(enr);
        }
Пример #21
0
        public EnrollmentResponse EnrollNewStudent(EnrollmentStudentRequest enrollmentStudentRequest)
        {
            using var connection = new SqlConnection(AppSettingsUtils.GetConnectionString());
            using var command    = new SqlCommand { Connection = connection };
            connection.Open();
            var transaction = connection.BeginTransaction();

            command.Transaction = transaction;

            command.CommandText = "SELECT s.IdStudy FROM Studies s WHERE s.Name = @StudiesName";
            command.Parameters.AddWithValue("StudiesName", enrollmentStudentRequest.Studies);
            var dataReader = command.ExecuteReader();

            if (!dataReader.Read())
            {
                throw new ResourceNotFoundException(
                          $"Studies by name {enrollmentStudentRequest.Studies} does not exist in database");
            }
            var idStudy = Parse(dataReader["IdStudy"].ToString());

            dataReader.Close();
            command.Parameters.Clear();
            command.CommandText =
                "SELECT * FROM Enrollment E WHERE E.Semester = 1 AND E.IdStudy = @IdStudy";
            command.Parameters.AddWithValue("IdStudy", idStudy);
            dataReader = command.ExecuteReader();

            var enrollmentResponse = new EnrollmentResponse();

            if (!dataReader.Read())
            {
                dataReader.Close();
                command.Parameters.Clear();

                command.CommandText =
                    @"INSERT INTO Enrollment(IdEnrollment, Semester, StartDate, IdStudy) 
                OUTPUT INSERTED.IdEnrollment, INSERTED.Semester, INSERTED.StartDate, INSERTED.IdStudy 
                VALUES((SELECT MAX(E.IdEnrollment) FROM Enrollment E) + 1, @Semester, @StartDate, @IdStudy);";
                command.Parameters.AddWithValue("Semester", 1);
                command.Parameters.AddWithValue("StartDate", DateTime.Now);
                command.Parameters.AddWithValue("IdStudy", idStudy);

                enrollmentResponse.IdEnrollment = Parse(command.ExecuteScalar().ToString());
                enrollmentResponse.Semester     = Parse(command.Parameters["Semester"].Value.ToString());
                enrollmentResponse.IdStudy      = Parse(command.Parameters["IdStudy"].Value.ToString());
                enrollmentResponse.StartDate    =
                    DateTime.Parse(command.Parameters["StartDate"].Value.ToString()).ToString("yyyy-MM-dd");
            }
            else
            {
                enrollmentResponse.IdEnrollment = Parse(dataReader["IdEnrollment"].ToString());
                enrollmentResponse.Semester     = Parse(dataReader["Semester"].ToString());
                enrollmentResponse.IdStudy      = Parse(dataReader["IdStudy"].ToString());
                enrollmentResponse.StartDate    =
                    DateTime.Parse(dataReader["StartDate"].ToString()).ToString("yyyy-MM-dd");
            }

            dataReader.Close();
            command.Parameters.Clear();
            command.CommandText = "SELECT S.IndexNumber FROM Student S WHERE IndexNumber = @indexNumber";
            command.Parameters.AddWithValue("indexNumber", enrollmentStudentRequest.Index);
            dataReader = command.ExecuteReader();
            if (dataReader.Read())
            {
                throw new BadRequestException("Student Index number not unique");;
            }

            dataReader.Close();
            command.Parameters.Clear();
            var salt = PasswordUtils.GenerateSalt();

            command.CommandText =
                @"INSERT INTO Student(IndexNumber, FirstName, LastName, BirthDate, IdEnrollment, Password, Salt) 
                VALUES (@IndexNumber, @FirstName, @LastName, @BirthDate, @IdEnrollment, @Password, @Salt)";
            command.Parameters.AddWithValue("IndexNumber", enrollmentStudentRequest.Index);
            command.Parameters.AddWithValue("FirstName", enrollmentStudentRequest.FirstName);
            command.Parameters.AddWithValue("LastName", enrollmentStudentRequest.LastName);
            command.Parameters.AddWithValue("BirthDate", enrollmentStudentRequest.BirthDate);
            command.Parameters.AddWithValue("IdEnrollment", enrollmentResponse.IdEnrollment);
            command.Parameters.AddWithValue("Password",
                                            PasswordUtils.CreateSaltedPasswordHash(enrollmentStudentRequest.Password, salt));
            command.Parameters.AddWithValue("Salt", salt);
            command.ExecuteNonQuery();

            transaction.Commit();
            return(enrollmentResponse);
        }
Пример #22
0
        public IActionResult EnrollStudent(EnrollStudentRequest request)
        {
            //mapowanie obiektu reguest
            //business models
            //mapowanie obiektu response
            Console.WriteLine("37");
            var enrollStudentRequest = new EnrollStudentRequest();

            enrollStudentRequest.IndexNumber = request.IndexNumber;
            enrollStudentRequest.FirstName   = request.FirstName;
            enrollStudentRequest.LastName    = request.LastName;
            enrollStudentRequest.BirthDate   = (System.DateTime)request.BirthDate;
            enrollStudentRequest.Semester    = request.Semester;
            enrollStudentRequest.Studies     = request.Studies;


            using (var con = new SqlConnection(ConString))
                using (var com = new SqlCommand())
                {
                    com.Connection = con;
                    con.Open();
                    SqlTransaction transaction = con.BeginTransaction();
                    com.Transaction = transaction;



                    //Does exist this study?
                    try
                    {
                        com.CommandText = "select IdStudy from studies where name like @studies ;";
                        com.Parameters.AddWithValue("studies", enrollStudentRequest.Studies);

                        var dr = com.ExecuteReader();

                        if (!dr.Read())
                        {
                            return(BadRequest("Studia nie istnieja"));
                        }

                        int idStudies = (int)dr["IdStudy"];
                        dr.Close();
                        //Does enrollment exist?
                        com.CommandText = "select IdEnrollment from Enrollment where semester=1 and IdStudy=@idStudies and StartDate>=CONVERT(DATE, GETDATE());";
                        com.Parameters.AddWithValue("idStudies", idStudies);

                        var dr11 = com.ExecuteReader();

                        int idEnrollmet;
                        if (!dr11.Read())
                        {
                            com.CommandText = " insert into enrollment (IdEnrollment, Semester, IdStudy, StartDate) values ((select MAX(IdEnrollment)+1 from enrollment), 1, @idSt,CONVERT(DATE, GETDATE()));";
                            com.Parameters.AddWithValue("idSt", idStudies);
                            dr11.Close();
                            com.ExecuteNonQuery();


                            com.CommandText = "select b.IdEnrollment from (select * from Enrollment where semester=1 and IdStudy=@idS) b where StartDate=(select MAX(a.StartDate) from (select * from Enrollment where semester=1 and IdStudy=@idS)a);";
                            com.Parameters.AddWithValue("idS", idStudies);

                            var dr1 = com.ExecuteReader();
                            idEnrollmet = (int)dr1["IdEnrollment"]; return(Ok("92"));

                            dr1.Close();
                            return(Ok("oooooooooooooooo"));
                        }
                        else
                        {
                            idEnrollmet = (int)dr11["IdEnrollment"];
                            dr11.Close();
                        }

                        //Is the indexNumber of student unique?

                        com.CommandText = "select * from Student where IndexNumber like @id;";
                        com.Parameters.AddWithValue("id", enrollStudentRequest.IndexNumber);

                        var dr4 = com.ExecuteReader();
                        if (dr4.Read())
                        {
                            dr4.Close();
                            transaction.Rollback();
                            return(BadRequest("Index number is not unique !!!"));
                        }


                        //Add new student
                        com.CommandText = "insert into student (IndexNumber, FirstName,LastName, BirthDate, IdEnrollment) values (@IndexNumber, @FirstName,@LastName,@BirthDate,@IdEnrollment);";

                        com.Parameters.AddWithValue("IndexNumber", enrollStudentRequest.IndexNumber);
                        com.Parameters.AddWithValue("FirstName", enrollStudentRequest.FirstName);
                        com.Parameters.AddWithValue("LastName", enrollStudentRequest.LastName);
                        com.Parameters.AddWithValue("BirthDate", enrollStudentRequest.BirthDate);
                        com.Parameters.AddWithValue("IdEnrollment", idEnrollmet);
                        if (!dr4.IsClosed)
                        {
                            dr4.Close();
                        }
                        com.ExecuteNonQuery();

                        //return Ok("92");
                        transaction.Commit();

                        var response = new EnrollmentResponse();
                        response.Semester = "1";
                        return(Created("WWWWWWEEEEEEEEEEEEELLLLLLLLLLL DOOOOOOOOOONE", response));
                    }
                    catch (SqlException ex)
                    {
                        transaction.Rollback();
                    }
                }

            return(BadRequest("SUUUUUUUUUUUUUUUUUUKAAAAAAAAAAAAAAAAAAAA"));
        }
Пример #23
0
        public EnrollmentResponse EnrollStudent(EnrollmentRequest request)
        {
            using (var connection = new SqlConnection(@"Data Source=db-mssql;Initial Catalog=2019SBD;Integrated Security=True"))
            {
                using (var command = new SqlCommand())
                {
                    connection.Open();
                    command.Connection = connection;
                    var tran = connection.BeginTransaction();
                    command.Transaction = tran;

                    // Check if studies exists
                    command.CommandText = "select * FROM Studies WHERE Name=@Name";
                    command.Parameters.AddWithValue("Name", request.Studies);

                    var reader = command.ExecuteReader();
                    if (!reader.Read())
                    {
                        return(null);
                    }
                    int idStudies = (int)reader["IdStudy"];

                    reader.Close();

                    command.CommandText = "select * FROM Enrollment WHERE Semester=1 AND IdStudy=@IdStudy";
                    command.Parameters.AddWithValue("IdStudy", idStudies);

                    var idEnrollment = 0;
                    var reader2      = command.ExecuteReader();
                    if (!reader2.Read())
                    {
                        command.CommandText = "SELECT * FROM Enrollment WHERE IdEnrollment = (SELECT MAX(IdEnrollment) FROM Enrollment)";
                        reader2.Close();

                        var reader3 = command.ExecuteReader();
                        reader3.Read();
                        idEnrollment = reader3.GetInt32(0);
                        reader3.Close();
                        command.CommandText = "INSERT INTO Enrollment (IdEnrollment, Semester, IdStudy, StartDate) VALUES(@IdEnrollment, @Semester, @ids, @StartDate);";
                        command.Parameters.AddWithValue("IdEnrollment", idEnrollment + 1);
                        command.Parameters.AddWithValue("Semester", 1);
                        command.Parameters.AddWithValue("ids", idStudies);
                        command.Parameters.AddWithValue("StartDate", DateTime.Now.ToString());

                        var reader4 = command.ExecuteReader();
                        reader4.Close();
                    }
                    else
                    {
                        idEnrollment = (int)reader2["IdEnrollment"];
                        reader2.Close();
                    }

                    // check if student with index number exists
                    command.CommandText = "select * FROM Student WHERE IndexNumber=@IndexNumber";
                    command.Parameters.AddWithValue("IndexNumber", request.IndexNumber);

                    var reader5 = command.ExecuteReader();
                    if (!reader5.Read())
                    {
                        reader5.Close();
                        // create new student
                        command.CommandText = "INSERT INTO Student(IndexNumber, FirstName, LastName, Birthdate, IdEnrollment) VALUES (@IndexNumber2, @FirstName2, @LastName2, @Birthdate2, @IdEnrollment2)";
                        command.Parameters.AddWithValue("IndexNumber2", request.IndexNumber);
                        command.Parameters.AddWithValue("FirstName2", request.FirstName);
                        command.Parameters.AddWithValue("LastName2", request.LastName);
                        command.Parameters.AddWithValue("Birthdate2", request.DateOfBirth.ToString());
                        command.Parameters.AddWithValue("IdEnrollment2", idEnrollment);

                        var reader6 = command.ExecuteReader();
                        reader6.Close();
                    }
                    else
                    {
                        reader5.Close();
                    }

                    tran.Commit();
                }
            }

            var response = new EnrollmentResponse
            {
                LastName = request.LastName,
                Semester = 1
            };

            return(response);
        }
Пример #24
0
        public EnrollmentResponse PromoteStudentsEntity(PromoteStudentsRequest promoteStudentsRequest)
        {
            var semester    = promoteStudentsRequest.Semester;
            var studiesName = promoteStudentsRequest.Studies;
            var context     = new StudentDbContext();

            var studies = context.Studies
                          .FirstOrDefault(stud => studiesName.Equals(stud.Name));

            if (studies == null)
            {
                throw new ResourceNotFoundException("Studies with name = " + studiesName + " dont exist");
            }

            var enrollment = context.Enrollment
                             .FirstOrDefault(enroll => semester.Equals(enroll.Semester) &&
                                             studies.IdStudy.Equals(enroll.IdStudy));

            if (enrollment == null)
            {
                throw new ResourceNotFoundException("Enrollment with idStudies = "
                                                    + studies.IdStudy + " and semester = " + semester
                                                    + " dont exist");
            }

            var enrollmentNew = context.Enrollment.FirstOrDefault(enrollment =>
                                                                  (semester + 1).Equals(enrollment.Semester) &&
                                                                  studies.IdStudy.Equals(enrollment.IdStudy));

            if (enrollmentNew == null)
            {
                enrollmentNew = new Enrollment
                {
                    IdEnrollment = context.Enrollment.Select(enroll => enroll.IdEnrollment)
                                   .OrderByDescending(i => i).First() + 1,
                    Semester  = semester + 1,
                    IdStudy   = studies.IdStudy,
                    StartDate = DateTime.Today
                };

                context.Enrollment.Add(enrollmentNew);
            }

            var students = context.Student.Where(student
                                                 => enrollment.IdEnrollment.Equals(student.IdEnrollment))
                           .ToList();

            students.ForEach(student =>
            {
                student.IdEnrollment = enrollmentNew.IdEnrollment;
            });

            context.SaveChanges();

            var response = new EnrollmentResponse
            {
                Semester     = enrollmentNew.Semester,
                IdStudy      = enrollmentNew.IdStudy,
                IdEnrollment = enrollmentNew.IdEnrollment,
                StartDate    = enrollmentNew.StartDate.ToString("yyyy-MM-dd")
            };

            return(response);
        }
        public EnrollmentResponse EnrollStudent(EnrollmentRequest request)
        {
            int _semester = 1;
            EnrollmentResponse response;

            using (var connection = new SqlConnection(SqlServerDb.connectionString))
            {
                using (var command = new SqlCommand())
                {
                    command.Connection = connection;
                    connection.Open();
                    var transaction = connection.BeginTransaction();
                    command.Transaction = transaction;

                    // let's check if all the passed values are valid
                    if (request.IndexNumber.ToString() == null || request.FirstName.ToString() == null ||
                        request.LastName.ToString() == null || request.BirthDate == null || request.Studies.ToString() == null)
                    {
                        return(null);
                    }

                    // let's check if the requested studies exist in the Studies table
                    command.CommandText = @"SELECT IdStudy FROM Studies WHERE Name=@study;";
                    command.Parameters.AddWithValue("study", request.Studies);

                    var dataReader1 = command.ExecuteReader();
                    if (!dataReader1.Read())
                    {
                        return(null);
                    }
                    int _idStudy = int.Parse(dataReader1["IdStudy"].ToString());
                    dataReader1.Close();

                    // for the existing study, let's find an entry with semester=1
                    DateTime currentDate = DateTime.Now;
                    command.CommandText = @"SELECT MAX(IdEnrollment) AS MaxId FROM Enrollment 
                                        WHERE Semester=1 AND IdStudy=@idStudy;";
                    command.Parameters.AddWithValue("idStudy", _idStudy);

                    var dataReader2 = command.ExecuteReader();
                    int latestEntry = 0;

                    if (dataReader2.Read())
                    {
                        var result = dataReader2["MaxId"].ToString();
                        if (!string.IsNullOrEmpty(result))
                        {
                            latestEntry = int.Parse(result);
                            dataReader2.Close();
                        }
                        else
                        {
                            dataReader2.Close();
                            command.CommandText = @"SELECT MAX(IdEnrollment) AS MaxId FROM Enrollment;";
                            var dataReader3 = command.ExecuteReader();
                            // let's check if there any enrollment exists
                            if (dataReader3.Read())
                            {
                                var maxId = dataReader3["MaxId"].ToString();
                                if (!string.IsNullOrEmpty(maxId))
                                {
                                    latestEntry = int.Parse(maxId);
                                }

                                latestEntry++;
                                dataReader3.Close();
                                command.CommandText = @"INSERT INTO Enrollment VALUES (@idEnroll, @_semester, @_idStudy, @_startDate)";
                                command.Parameters.AddWithValue("idEnroll", latestEntry);
                                command.Parameters.AddWithValue("_semester", _semester);
                                command.Parameters.AddWithValue("_idStudy", _idStudy);
                                command.Parameters.AddWithValue("_startDate", currentDate);
                                command.ExecuteNonQuery();
                            }
                        }
                    }

                    // here, we check if newly entered index number is assigned to another student.
                    // If a student already exists with the given index number, we return error
                    // If not, then with that index number, we insert a new student into Students table
                    command.CommandText = @"SELECT FirstName FROM Student WHERE IndexNumber=@idStudent;";
                    command.Parameters.AddWithValue("idStudent", request.IndexNumber);
                    using var dataReader4 = command.ExecuteReader();
                    if (!dataReader4.Read())
                    {
                        dataReader4.Close();
                        command.CommandText =
                            @"INSERT INTO Student VALUES (@id, @name, @surname, CONVERT(DATE, @dob, 103), @idE, @password);";
                        command.Parameters.AddWithValue("@id", request.IndexNumber);
                        command.Parameters.AddWithValue("@name", request.FirstName);
                        command.Parameters.AddWithValue("@surname", request.LastName);
                        command.Parameters.AddWithValue("@dob", request.BirthDate);
                        command.Parameters.AddWithValue("@idE", latestEntry);
                        command.Parameters.AddWithValue("@password", "default");

                        command.ExecuteNonQuery();
                    }
                    else
                    {
                        // returning error if the given id is already assigned to another student
                        return(null);
                    }

                    transaction.Commit();

                    // Done :)
                    response           = new EnrollmentResponse();
                    response.FirstName = request.FirstName;
                    response.LastName  = request.LastName;
                    response.Studies   = request.Studies;
                    response.Semester  = _semester;

                    return(response);
                }
            }
        }
Пример #26
0
        public EnrollmentStatus PromoteStudents(PromoteStudentsRequest promoteStudentsRequest)
        {
            EnrollmentStatus registerStudentStatus = new EnrollmentStatus();

            using (var client = new SqlConnection(SqlConn))
                using (var command = new SqlCommand())
                {
                    command.Connection = client;
                    client.Open();

                    try
                    {
                        command.CommandText = $"SELECT IdEnrollment FROM Enrollment WHERE Enrollment.Semester = @semester AND IdStudy = (SELECT IdStudy FROM Studies WHERE Studies.Name = @name);";
                        command.Parameters.AddWithValue("semester", promoteStudentsRequest.Semester);
                        command.Parameters.AddWithValue("name", promoteStudentsRequest.Studies);

                        var dataReader = command.ExecuteReader();

                        if (!dataReader.Read())
                        {
                            registerStudentStatus.enrollment = null;
                            registerStudentStatus.Status     = 400;
                            registerStudentStatus.Message    = "Nie ma takiego semestru dla tych studiów";
                            return(registerStudentStatus);
                        }

                        dataReader.Close();

                        command.CommandText = "PromoteStudents";
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Clear();
                        command.Parameters.AddWithValue("@Studies", promoteStudentsRequest.Studies);
                        command.Parameters.AddWithValue("@Semester", promoteStudentsRequest.Semester);

                        int rowAffected = command.ExecuteNonQuery();

                        command.CommandText = $"SELECT * FROM Enrollment WHERE Enrollment.Semester = @semester AND IdStudy = (SELECT IdStudy FROM Studies WHERE Studies.Name = @name);";
                        command.CommandType = CommandType.Text;
                        command.Parameters.Clear();
                        command.Parameters.AddWithValue("@name", promoteStudentsRequest.Studies);
                        command.Parameters.AddWithValue("@semester", promoteStudentsRequest.Semester + 1);

                        dataReader = command.ExecuteReader();

                        if (!dataReader.Read())
                        {
                            registerStudentStatus.enrollment = null;
                            registerStudentStatus.Status     = 400;
                            registerStudentStatus.Message    = "Błąd bazy!";
                            return(registerStudentStatus);
                        }

                        EnrollmentResponse enrollment = new EnrollmentResponse()
                        {
                            IdEnrollment = int.Parse((dataReader["IdEnrollment"]).ToString()),
                            Semester     = promoteStudentsRequest.Semester + 1,
                            IdStudy      = int.Parse((dataReader["IdStudy"]).ToString()),
                            StartDate    = DateTime.Parse(dataReader["StartDate"].ToString()),
                        };


                        registerStudentStatus.enrollment = enrollment;
                        registerStudentStatus.Status     = 201;
                        registerStudentStatus.Message    = "Promowany";
                    }
                    catch (SqlException exc)
                    {
                        registerStudentStatus.enrollment = null;
                        registerStudentStatus.Status     = 400;
                        registerStudentStatus.Message    = "Wyjątek bazy danych";
                    }

                    return(registerStudentStatus);
                }
        }
Пример #27
0
        public EnrollmentStatus RegisterStudent(RegistrationStudentRequest registrationStudentRequest)
        {
            EnrollmentStatus registerStudentStatus = new EnrollmentStatus();

            using (var client = new SqlConnection(SqlConn))
                using (var command = new SqlCommand())
                {
                    command.Connection = client;
                    client.Open();

                    var transaction = client.BeginTransaction();
                    command.Transaction = transaction;
                    try
                    {
                        command.CommandText = $"SELECT IdStudy FROM STUDIES WHERE Name=@name";
                        command.Parameters.AddWithValue("name", registrationStudentRequest.Studies);

                        var dataReader = command.ExecuteReader();

                        if (!dataReader.Read())
                        {
                            dataReader.Close();
                            transaction.Rollback();
                            registerStudentStatus.enrollment = null;
                            registerStudentStatus.Status     = 400;
                            registerStudentStatus.Message    = "Nie ma takich studiów";
                            return(registerStudentStatus);
                        }

                        string IdStudy = dataReader["IdStudy"].ToString();

                        dataReader.Close();
                        command.CommandText = $"SELECT IdEnrollment, StartDate FROM Enrollment WHERE Enrollment.Semester = 1  AND Enrollment.IdStudy = @IdStudy AND Enrollment.StartDate = (SELECT MAX(StartDate) FROM Enrollment WHERE Enrollment.Semester = 1  AND Enrollment.IdStudy = @IdStudy);";
                        command.Parameters.AddWithValue("IdStudy", IdStudy);

                        dataReader = command.ExecuteReader();
                        DateTime StartDate    = DateTime.Now;
                        int      IdEnrollemnt = -1;

                        if (!dataReader.Read())
                        {
                            command.CommandText = $"INSERT INTO Enrollment VALUES(SELECT MAX(IdEnrollment) + 1 FROM Enrollment WHERE Enrollment.IdStudy = @IdStudy) + 1, 1, @IdStudy, @StartDate)";
                            command.Parameters.AddWithValue("IdStudy", IdStudy);
                            command.Parameters.AddWithValue("StartDate", DateTime.Now);
                            command.ExecuteReader();

                            dataReader.Close();
                            command.CommandText = $"SELECT IdEnrollment, StartDate FROM Enrollment WHERE Enrollment.Semester = 1  AND Enrollment.IdStudy = @IdStudy AND Enrollment.StartDate = (SELECT MAX(StartDate) FROM Enrollment WHERE Enrollment.Semester = 1  AND Enrollment.IdStudy = @IdStudy);";
                            command.Parameters.AddWithValue("IdStudy", IdStudy);

                            dataReader = command.ExecuteReader();
                            dataReader.Read();
                        }
                        else
                        {
                            StartDate = DateTime.Parse(dataReader["StartDate"].ToString());
                        }

                        IdEnrollemnt = int.Parse(dataReader["IdEnrollment"].ToString());

                        dataReader.Close();
                        command.CommandText = $"SELECT IndexNumber FROM Student WHERE IndexNumber = @IndexNumber";
                        command.Parameters.AddWithValue("IndexNumber", registrationStudentRequest.IndexNumber);
                        dataReader = command.ExecuteReader();

                        if (dataReader.Read())
                        {
                            dataReader.Close();
                            transaction.Rollback();
                            registerStudentStatus.enrollment = null;
                            registerStudentStatus.Status     = 400;
                            registerStudentStatus.Message    = "Student o tym numerze indeksu już zapisany";
                            return(registerStudentStatus);
                        }
                        dataReader.Close();


                        command.CommandText = $"INSERT INTO Student VALUES(@IndexNumber, @FirstName, @LastName, @BirthDate, @IdEnrollment)";
                        command.Parameters.Clear();
                        command.Parameters.AddWithValue("IndexNumber", registrationStudentRequest.IndexNumber);
                        command.Parameters.AddWithValue("FirstName", registrationStudentRequest.FirstName);
                        command.Parameters.AddWithValue("LastName", registrationStudentRequest.LastName);
                        command.Parameters.AddWithValue("BirthDate", registrationStudentRequest.BirthDate);
                        command.Parameters.AddWithValue("IdEnrollment", IdEnrollemnt);
                        command.ExecuteNonQuery();
                        transaction.Commit();

                        EnrollmentResponse enrollment = new EnrollmentResponse()
                        {
                            IdEnrollment = IdEnrollemnt,
                            Semester     = 1,
                            IdStudy      = int.Parse(IdStudy),
                            StartDate    = StartDate,
                        };

                        registerStudentStatus.enrollment = enrollment;
                        registerStudentStatus.Status     = 201;
                        registerStudentStatus.Message    = "Student added";
                    }
                    catch (SqlException exc)
                    {
                        transaction.Rollback();
                        registerStudentStatus.enrollment = null;
                        registerStudentStatus.Status     = 400;
                        registerStudentStatus.Message    = "Nastąpił wyjątek";
                    }
                }
            return(registerStudentStatus);
        }
Пример #28
0
        public EnrollmentResponse EnrollStudent(Models.Student student)
        {
            if (student.IndexNumber == null || student.Firstname == null || student.Lastname == null || student.BirthDate == null || student.Studies == null)
            {
                return(null);
            }
            else
            {
                int result1;
                //int idEnrollment;
                //client.Open();
                //com.Connection = client;
                //var tran = client.BeginTransaction();
                //com.Transaction = tran;
                //com.CommandText = "select * from Studies where Name=@index";
                //com.Parameters.AddWithValue("index", student.Studies);

                var result = _context.Studies.Select(e => new {
                    e.IdStudy,
                    e.Name
                }).Where(d => d.Name.Equals(student.Studies));


                //var dr = com.ExecuteReader();

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

                int idStudies = result.Select(e => e.IdStudy).First();


                //dr.Close();

                var fromEnr = _context.Enrollment.Select(e => e).Where(e => e.Semester == 1 && e.IdStudy == idStudies);


                //com.CommandText = "SELECT * FROM Enrollment WHERE Semester=1 AND IdStudy=@IdStud";

                //com.Parameters.AddWithValue("IdStud", idStudies);

                //var dr2 = com.ExecuteReader();

                if (fromEnr == null)
                {
                    //dr2.Close();
                    //com.CommandText = "Select max(idenrollment) from enrollment";

                    result1 = _context.Enrollment.Max(e => e.IdEnrollment);

                    //var dr3 = com.ExecuteReader();

                    //dr3.Read();

                    //idEnrollment = dr3.GetInt32(0);

                    //dr3.Close();

                    var newEnroll = new Entities.Enrollment()
                    {
                        IdEnrollment = result1 + 1,
                        Semester     = 1,
                        IdStudy      = idStudies,
                        StartDate    = DateTime.Now
                    };

                    _context.Enrollment.Add(newEnroll);

                    _context.SaveChanges();


                    //com.CommandText = "INSERT INTO Enrollment(idEnrollment, semester, idStudy,StartDate) VALUES (@idE, @Semester,@IdStudy,@sd)";
                    //com.Parameters.AddWithValue("idE", idEnrollment + 1);
                    //com.Parameters.AddWithValue("Semester", 1);
                    //com.Parameters.AddWithValue("IdStudy", idStudies);
                    //com.Parameters.AddWithValue("sd", DateTime.Now.ToString());

                    //var dr6 = com.ExecuteNonQuery();
                }
                else
                {
                    result1 = fromEnr.Select(e => e.IdEnrollment).First();
                }

                var dont2 = _context.Student.Select(e => new { e.IndexNumber }).Where(d => d.IndexNumber.Equals(student.IndexNumber)).FirstOrDefault();

                //com.CommandText = "SELECT * FROM Student WHERE IndexNumber =@indexs";
                //com.Parameters.AddWithValue("indexs", student.IndexNumber);
                //var dr5 = com.ExecuteReader();

                if (dont2 != null)
                {
                    return(null);
                }

                //com.Parameters.AddWithValue("IdStuds", idStudies);

                _context.Add(new Entities.Student()
                {
                    FirstName    = student.Firstname,
                    IndexNumber  = student.IndexNumber,
                    LastName     = student.Lastname,
                    BirthDate    = DateTime.Now,
                    IdEnrollment = result1
                });

                _context.SaveChanges();

                //com.CommandText = "INSERT INTO Student(IndexNumber, FirstName, LastName,Birthdate,IdEnrollment) VALUES (@Indexn,@FirstName, @LastName,@Birthdate,@Studies)";
                ////...
                //com.Parameters.AddWithValue("FirstName", student.Firstname);
                //com.Parameters.AddWithValue("Indexn", student.IndexNumber);
                //com.Parameters.AddWithValue("LastName", student.Lastname);
                //com.Parameters.AddWithValue("Birthdate", DateTime.Parse(student.BirthDate));
                //com.Parameters.AddWithValue("Studies", idEnrollment);

                ////...
                //com.ExecuteNonQuery();


                var hello = _context.Enrollment.Select(e => e).Where(e => e.IdStudy == idStudies && e.Semester == 1 && e.StartDate == _context.Enrollment.Where(e => e.IdStudy == idStudies).Max(e => e.StartDate));

                //com.CommandText = "Select * from enrollment where idstudy=@iDstuds and semester=1 and StartDate=(select max(StartDate) from Enrollment where IdStudy=@IdStuds)";
                //tran.Commit();
                //var dr4 = com.ExecuteReader();


                var enrollment = new Models.Enrollment();

                enrollment.Idenrollment = hello.First().IdEnrollment;
                enrollment.semester     = hello.First().Semester;
                enrollment.IdStudy      = hello.First().IdStudy;
                enrollment.StartDate    = hello.First().StartDate.ToString();

                var er = new EnrollmentResponse(enrollment);

                return(er);
            }
        }