public async Task <IActionResult> Post([FromBody] Cohort cohort)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"INSERT INTO Cohort (Id, CohortName)
                                        OUTPUT INSERTED.Id
                                        VALUES (@id, @cohortName)";
                    cmd.Parameters.Add(new SqlParameter("@id", cohort.Id));
                    cmd.Parameters.Add(new SqlParameter("@cohortName", cohort.CohortName));

                    int newId = (int)cmd.ExecuteScalar();
                    cohort.Id = newId;
                    return(CreatedAtRoute("GetCohort", new { id = newId }, cohort));
                }
            }
        }
Esempio n. 2
0
        public CreateEmptyCohortHandlerTestsFixture()
        {
            Db = new ProviderCommitmentsDbContext(new DbContextOptionsBuilder <ProviderCommitmentsDbContext>()
                                                  .UseInMemoryDatabase(Guid.NewGuid().ToString())
                                                  .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning))
                                                  .Options);
            CohortId = 8768;
            Cohort   = new Cohort {
                Id = CohortId
            };

            EncodingServiceMock = new Mock <IEncodingService>();

            CohortDomainServiceMock = new Mock <ICohortDomainService>();
            CohortDomainServiceMock.Setup(x => x.CreateEmptyCohort(It.IsAny <long>(), It.IsAny <long>(), It.IsAny <long>(), It.IsAny <UserInfo>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(Cohort);

            UserInfo = new UserInfo();
        }
        private async Task CheckQueryResponse(Action <GetCohortSummaryQueryResult> assert, DraftApprenticeshipDetails apprenticeshipDetails = null)
        {
            var autoFixture = new Fixture();

            var account = new Account(autoFixture.Create <long>(), "", "", "", DateTime.UtcNow)
            {
                LevyStatus = LevyStatus
            };

            AccountLegalEntity = new AccountLegalEntity(account, 1, 1, "", "", autoFixture.Create <string>(),
                                                        OrganisationType.Charities, "", DateTime.UtcNow);
            Provider = new Provider {
                Name = autoFixture.Create <string>()
            };

            CohortId = autoFixture.Create <long>();
            Cohort   = autoFixture.Build <Cohort>().Without(o => o.Apprenticeships).Without(o => o.TransferRequests).Without(o => o.Messages)
                       .Without(o => o.AccountLegalEntity).Without(o => o.Provider).Without(o => o.TransferSender)
                       .Create();
            Cohort.AccountLegalEntity = AccountLegalEntity;
            Cohort.Provider           = Provider;

            Cohort.IsDeleted = CohortIsDeleted;
            if (!HasTransferSender)
            {
                Cohort.TransferSenderId = null;
            }

            if (apprenticeshipDetails != null)
            {
                Cohort.Apprenticeships.Add(new DraftApprenticeship(apprenticeshipDetails, Cohort.WithParty));
            }

            // arrange
            var fixtures = new GetCohortSummaryHandlerTestFixtures()
                           .AddCommitment(CohortId, Cohort, WithParty, LatestMessageCreatedByEmployer, LatestMessageCreatedByProvider, Approvals, ChangeOfPartyRequestId);

            // act
            var response = await fixtures.GetResult(new GetCohortSummaryQuery(CohortId));

            // Assert
            assert(response);
        }
        public CanAccessApprenticeshipQueryHandlerTestsFixture SeedData(bool isApproved = true)
        {
            _cohort = new Cohort
            {
                EmployerAccountId = _accountId,
                CommitmentStatus  = CommitmentStatus.Active,
                EditStatus        = EditStatus.Both,
                LastAction        = LastAction.None,
                Originator        = Originator.Unknown,
                ProviderId        = _providerId,
                Id = _cohortId,
            };

            if (isApproved)
            {
                var apprenticeship = new Apprenticeship
                {
                    Id           = _apprenticeshipId,
                    CommitmentId = _cohortId,
                    Cohort       = _cohort
                };

                _cohort.Apprenticeships.Add(apprenticeship);

                Db.Apprenticeships.Add(apprenticeship);
            }
            else
            {
                var apprenticeship = new DraftApprenticeship()
                {
                    Id           = _apprenticeshipId,
                    CommitmentId = _cohortId,
                    Cohort       = _cohort
                };
                _cohort.Apprenticeships.Add(apprenticeship);
            }

            Db.Cohorts.Add(_cohort);

            Db.SaveChanges();

            return(this);
        }
Esempio n. 5
0
        public ActionResult Create([Bind(Include = "CohortID,Name")] Cohort cohort)
        {
            var cohorts = _unitOfWork.CohortRepository.Get();

            if (cohorts.Any(c => c.Name.Equals(cohort.Name)))
            {
                TempData["DuplicateName"] = "A cohort with that name already exists.";
                return(View("Create", cohort));
            }

            if (ModelState.IsValid)
            {
                _unitOfWork.CohortRepository.Insert(cohort);
                _unitOfWork.Save();
                return(RedirectToAction("Index"));
            }

            return(View("Create", cohort));
        }
        public ActionResult Edit([Bind(Include = "ID,Code,CohortDescription,Number,Notes")] Cohort cohort)
        {
            if (ModelState.IsValid)
            {
                Cohort cohortInDB = db.Cohorts.Single(c => c.ID == cohort.ID);
                cohortInDB.Code = cohort.Code;
                cohortInDB.CohortDescription = cohort.CohortDescription;
                cohortInDB.Number            = cohort.Number;
                cohortInDB.Notes             = cohort.Notes;

                Person userperson = db.People.SingleOrDefault(p => p.ID == 0);
                cohortInDB.Modifier = userperson;
                cohortInDB.Modified = DateTime.Now;
                // db.Entry(cohort).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(cohort));
        }
Esempio n. 7
0
        /// <summary>
        /// Returns the first 3 digits of the first release identifier in the cohort (this is very hic specific).
        /// </summary>
        /// <returns></returns>
        private string GetFirstProCHIPrefix()
        {
            var ect = Cohort.ExternalCohortTable;

            var db = ect.Discover();

            using (var con = db.Server.GetConnection())
            {
                con.Open();

                string sql = "SELECT  TOP 1 LEFT(" + Cohort.GetReleaseIdentifier() + ",3) FROM " + ect.TableName + " WHERE " + Cohort.WhereSQL();

                using (var cmd = db.Server.GetCommand(sql, con))
                {
                    cmd.CommandTimeout = CohortCountTimeoutInSeconds;
                    return((string)cmd.ExecuteScalar());
                }
            }
        }
Esempio n. 8
0
        private void ResetCohort(Cohort cohort)
        {
            var employees = cohort.Employees;

            foreach (var employee in employees)
            {
                var evalsToDelete = employee.Evaluations.Where(e => !e.IsComplete()).ToList();
                foreach (var eval in evalsToDelete)
                {
                    _unitOfWork.EvaluationRepository.Delete(eval);
                    _unitOfWork.Save();
                }
            }

            cohort.Employees.Clear();
            cohort.Type1Assigned = false;
            cohort.Type2Assigned = false;
            _unitOfWork.Save();
        }
Esempio n. 9
0
        public async Task Delete_Cohort()
        {
            // Note: with many of these methods, I'm creating dummy data and then testing to see if I can delete it. I'd rather do that for now than delete something else I (or a user) created in the database, but it's not essential-- we could test deleting anything

            // Create a new coffee in the db
            Cohort newCohort55 = await CreateDummyCohort();

            // Delete it
            await deleteDummyCohort(newCohort55);

            using (var client = new APIClientProvider().Client)
            {
                // Try to get it again
                HttpResponseMessage response = await client.GetAsync($"{url}{newCohort55.Id}");

                // Make sure it's really gone
                Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            }
        }
Esempio n. 10
0
        public ActionResult Edit(CohortViewModel cohortVM)
        {
            if (cohortVM == null)
            {
                return(new HttpStatusCodeResult(422));
            }

            if (!ModelState.IsValid)
            {
                ViewBag.StrainList         = new SelectList(db.Strains.Where(p => p.Status == "Current").AsEnumerable(), "StrainID", "StrainName");
                ViewBag.SexList            = new SelectList(db.Options.Where(c => c.Status == "Current" && c.OptionFields.OptionFieldName == "Sex").AsEnumerable(), "OptionID", "OptionValue");
                ViewBag.MultiPARTProjectID = cohortVM.MultiPARTProjectID;

                return(View(cohortVM));
            }

            if (!_projectuservalidationservice.UserCanEditProject(cohortVM.MultiPARTProjectID))
            {
                ViewBag.ErrorMessage = "Access Denied. Please contact administrator for further assistance.";
                return(View("Error"));
            }

            Cohort cohort = new Cohort()
            {
                CohortID = cohortVM.CohortID,
                MultiPARTProjectMultiPARTProjectID = cohortVM.MultiPARTProjectID,
                CohortLabel    = cohortVM.CohortLabel,
                StrainStrainID = cohortVM.StrainID,
                SampleSize     = cohortVM.SampleSize ?? 0,
                SexID          = cohortVM.SexID,
                MinAge         = cohortVM.MinAge ?? 0,
                MaxAge         = cohortVM.MaxAge ?? 0,
                MinWeight      = cohortVM.MinWeight ?? 0,
                MaxWeight      = cohortVM.MaxWeight ?? 0,
                Details        = cohortVM.Details,

                LastUpdatedBy = (int)Membership.GetUser().ProviderUserKey
            };

            db.Entry(cohort).State = EntityState.Modified;
            db.SaveChanges();
            return(RedirectToAction("Details", "MultiPARTProject", new { projectid = cohortVM.MultiPARTProjectID }));
        }
        public static Cohort EditCohort(int id, Cohort cohort)
        {
            // TODO: Add update logic here
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @" UPDATE Cohort
                                             SET Designation = @des
                                             WHERE Id = @id";
                    cmd.Parameters.Add(new SqlParameter("@des", cohort.Designation));
                    cmd.Parameters.Add(new SqlParameter("@id", id));

                    int rowsAffected = cmd.ExecuteNonQuery();
                }
            }
            return(cohort);
        }
Esempio n. 12
0
        // Adding viewmodel to display multiple Staff checkboxes
        private List <AssignedStaffData> PopulateAssignedStaffData(Cohort cohort)
        {
            var allStaffs = _context.Staff
                            .Include(s => s.Department).OrderBy(s => s.Name);
            var cohortStaffs = new HashSet <int>(cohort.CohortStaff.Select(c => c.StaffId));
            var viewModel    = new List <AssignedStaffData>();

            foreach (var staff in allStaffs)
            {
                viewModel.Add(new AssignedStaffData
                {
                    StaffId    = staff.Id,
                    StaffName  = staff.Name,
                    Assigned   = cohortStaffs.Contains(staff.Id),
                    Department = staff.Department.Name
                });
            }
            return(viewModel);
        }
        public ActionResult Post([FromBody] Cohort newCohort)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"INSERT INTO cohort (name)
                                             OUTPUT INSERTED.Id
                                             VALUES (@name)";
                    cmd.Parameters.Add(new SqlParameter("@name", newCohort.Name));


                    int newId = (int)cmd.ExecuteScalar();
                    newCohort.Id = newId;
                    return(CreatedAtRoute("GetCohort", new { id = newId }, newCohort));
                }
            }
        }
        public ActionResult Edit(int id, Cohort cohort)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"
                                    UPDATE Cohort 
                                    SET CohortName = @name
                                    WHERE Id = @id";
                    cmd.Parameters.Add(new SqlParameter("@name", cohort.CohortName));
                    cmd.Parameters.Add(new SqlParameter("@id", id));

                    cmd.ExecuteNonQuery();
                    return(RedirectToAction(nameof(Index)));
                }
            }
        }
Esempio n. 15
0
        // GET: Cohort/Edit/5
        public static void EditCohort(Cohort cohort)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"UPDATE Cohort
                            SET Designation = @designation                                                   
                            WHERE Id = @CohortId
                        ";
                    cmd.Parameters.Add(new SqlParameter("@CohortId", cohort.Id));
                    cmd.Parameters.Add(new SqlParameter("@designation", cohort.Designation));
                    cmd.Parameters.Add(new SqlParameter("@id", cohort.Id));

                    cmd.ExecuteNonQuery();
                }
            }
        }
Esempio n. 16
0
 public Cohort GetUserCohort(User user)
 {
     try
     {
         using (SqlConnection conn = new SqlConnection(_connectionString))
         {
             conn.Open();
             string cmd = $"SELECT * FROM cohorts " +
                          $"JOIN users ON users.cohortID = cohorts.cohortID " +
                          $"WHERE username = @username";
             Cohort cohort = conn.QuerySingle <Cohort>(cmd, new { username = user.Username });
             return(cohort);
         }
     }
     catch
     {
         return(null);
     }
 }
Esempio n. 17
0
        //Find all instructors in the database.Include each instructor's cohort.

        public List <Instructor> GetInstructorsWithCohort()
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT Instructor.Id, Instructor.FirstName, Instructor.LastName, Cohort.Id as CohortId, Cohort.Name as CohortName FROM Instructor
                    LEFT JOIN Cohort ON Instructor.CohortId = Cohort.Id";
                    SqlDataReader     reader      = cmd.ExecuteReader();
                    List <Instructor> Instructors = new List <Instructor>();
                    while (reader.Read())
                    {
                        int    InstructorIdPosition        = reader.GetOrdinal("Id");
                        int    InstructorIdValue           = reader.GetInt32(InstructorIdPosition);
                        int    InstructorFirstNamePosition = reader.GetOrdinal("FirstName");
                        string InstructorFirstNameValue    = reader.GetString(InstructorFirstNamePosition);
                        int    InstructorLastNamePosition  = reader.GetOrdinal("LastName");
                        string InstructorLastNameValue     = reader.GetString(InstructorLastNamePosition);
                        int    CohortIdPosition            = reader.GetOrdinal("CohortId");
                        int    CohortIdValue      = reader.GetInt32(CohortIdPosition);
                        int    CohortNamePosition = reader.GetOrdinal("CohortName");
                        string CohortNameValue    = reader.GetString(CohortNamePosition);
                        Cohort cohort             = new Cohort
                        {
                            Id   = CohortIdValue,
                            Name = CohortNameValue
                        };
                        Instructor instructor = new Instructor
                        {
                            Id        = InstructorIdValue,
                            FirstName = InstructorFirstNameValue,
                            LastName  = InstructorLastNameValue,
                            CohortId  = CohortIdValue,
                            cohort    = cohort
                        };
                        Instructors.Add(instructor);
                    }
                    reader.Close();
                    return(Instructors);
                }
            }
        }
Esempio n. 18
0
        public ActionResult <Cohort> UpdateStatus(string id, StatusAPI status)
        {
            // validate that session exists
            string sessionUserId;

            if (!Utils.ValidateSession(this.Request.Headers, out sessionUserId))
            {
                return(BadRequest("Session does not exists."));
            }

            Guid cohortId = Utils.ToGuid(id, false);

            if (cohortId == Guid.Empty)
            {
                return(BadRequest("Cohort id is not valid (" + id + ")"));
            }

            string sid    = Utils.ToGuid(id, false).ToString("B");
            Cohort cohort = Program.MedialynxData.cohortDBAPI.GetById(sid);

            if (cohort == null)
            {
                return(NotFound("Cohort with id=" + sid + " not found"));
            }

            if ((int)cohort.Status != status.Status)
            {
                cohort.Status = (ObjectStatus)status.Status;

                Program.MedialynxData.cohortDBAPI.Update(cohort);

                Program.MedialynxData.historyDBAPI.Add(
                    new HistoryItem(
                        sessionUserId,
                        sid,
                        this.GetType().ToString(),
                        "Cohort Status was updated. id: " + id
                        )
                    );
            }
            return(CreatedAtAction(nameof(GetById), new { id = cohort.Id }, cohort));
        }
            public async Task Test_Get_Single_Cohort()
            {
                using (HttpClient client = new APIClientProvider().Client)
                {
                    Cohort newCohort = await createCohortTest(client);

                    HttpResponseMessage response = await client.GetAsync($"api/cohort/{newCohort.Id}");

                    response.EnsureSuccessStatusCode();

                    string responseBody = await response.Content.ReadAsStringAsync();

                    Cohort cohort = JsonConvert.DeserializeObject <Cohort>(responseBody);

                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    Assert.Equal("Test", newCohort.Name);

                    deleteTest(newCohort, client);
                }
            }
Esempio n. 20
0
        private void CreateCohortDetailsTable(XWPFDocument document)
        {
            var table = InsertTable(document, 2, 4);

            int tableLine = 0;

            SetTableCell(table, tableLine, 0, "Version");
            SetTableCell(table, tableLine, 1, "Description");
            SetTableCell(table, tableLine, 2, "Date Extracted");
            SetTableCell(table, tableLine, 3, "Unique Individuals");
            tableLine++;

            SetTableCell(table, tableLine, 0, Cohort.GetExternalData().ExternalVersion.ToString());
            SetTableCell(table, tableLine, 1, string.Format("{0} (ID={1}, OriginID={2})", Cohort, Cohort.ID, Cohort.OriginID));//description fetched from remote table

            var lastExtracted = ExtractionResults.Any() ? ExtractionResults.Max(r => r.DateOfExtraction).ToString() : "Never";

            SetTableCell(table, tableLine, 2, lastExtracted);
            SetTableCell(table, tableLine, 3, Cohort.CountDistinct.ToString("N0"));
        }
        public GroupFormationService()
        {
            Nancy.Json.JsonSettings.MaxJsonLength = int.MaxValue;
            //Nancy.Json.JsonSettings.MaxRecursions = 100;
            //Nancy.Json.JsonSettings.RetainCasing = true;


            // you can find some example data generated and readable/written with ParticipantReaderWriter.cs in folder /bin/Debug/
            // i.e. "DemoEntries_100Pers_3Hom_3Het_RandomValues.xml"
            Get["/"] = x => { return("This is the GroupAlService. Send the participant data to / users / preferences /{ groupSize}"); };

            Post["/users/preferences/{GroupSize}"] = parameters =>
            {
                var xmlString = this.Request.Body.AsString();
                List <Participant>      particpants = new XMLParticipantReaderWriter().ReadParticipantsFromString(xmlString);
                GroupFormationAlgorithm gfGbG       = new GroupFormationAlgorithm(particpants, new GroupALGroupCentricMatcher(), new GroupALEvaluator(), new GroupALOptimizer(new GroupALGroupCentricMatcher()), parameters.GroupSize);
                Cohort result = gfGbG.DoOneFormation();
                return(result);
            };
        }
        //---------------------------------------------------------------------

        /// <summary>
        /// Makes the set of biomass cohorts at a site based on the age cohorts
        /// at the site, using a specified method for computing a cohort's
        /// initial biomass.
        /// </summary>
        /// <param name="ageCohorts">
        /// A sorted list of age cohorts, from oldest to youngest.
        /// </param>
        /// <param name="site">
        /// Site where cohorts are located.
        /// </param>
        /// <param name="initialBiomassMethod">
        /// The method for computing the initial biomass for a new cohort.
        /// </param>

        public static ISiteCohorts MakeBiomassCohorts(List <Landis.Library.AgeOnlyCohorts.ICohort> ageCohorts, ActiveSite site)

        {
            PlugIn.Cohorts[site] = new Library.BiomassCohortsPnET.SiteCohorts();

            Hydrology.Initialize(site);

            Hydrology.AnnualTranspiration[site] = 0;
            CanopyBiomass.CanopyLAI[site]       = 0;

            if (ageCohorts.Count == 0)
            {
                return(PlugIn.Cohorts[site]);
            }

            System.DateTime SpinUpDate = PlugIn.StartDate.AddYears(-(ageCohorts[0].Age) + ((successionTimestep == 1) ? -1 : 0));

            while (SpinUpDate.CompareTo(PlugIn.StartDate) < 0)
            {
                CanopyBiomass.SubCanopyPAR[site] = Static.PAR0[SpinUpDate];

                //  Add those cohorts that were born at the current year
                foreach (Library.AgeOnlyCohorts.ICohort ageonlycohort in ageCohorts)
                {
                    if (PlugIn.StartDate.Year - SpinUpDate.Year == ageonlycohort.Age)
                    {
                        Cohort cohort = new Cohort(ageonlycohort.Species, 1, ConstantParameters.InitialFol, 0, 0, 0, 0, SpinUpDate.Year, true);
                        PlugIn.Cohorts[site].AddNewCohort(cohort);
                        CohortOutput.WriteHeader(site, cohort);
                        SiteOutput.WriteHeader(site);
                    }
                }

                PlugIn.GrowCohorts(site, SpinUpDate, SpinUpDate.AddYears(1), false);

                SpinUpDate = SpinUpDate.AddYears(1);
            }


            return(PlugIn.Cohorts[site]);
        }
        // GET: StudentsController/Create
        public ActionResult Create()
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = @"SELECT Cohort.Id, Cohort.Name FROM Cohort";

                    SqlDataReader reader = cmd.ExecuteReader();

                    // Create a new instance of our view model
                    StudentCohortViewModel viewModel = new StudentCohortViewModel();
                    while (reader.Read())
                    {
                        // Map the raw data to our cohort model
                        Cohort cohort = new Cohort
                        {
                            Id   = reader.GetInt32(reader.GetOrdinal("Id")),
                            Name = reader.GetString(reader.GetOrdinal("Name"))
                        };

                        // Use the info to build our SelectListItem
                        SelectListItem cohortOptionTag = new SelectListItem()
                        {
                            Text  = cohort.Name,
                            Value = cohort.Id.ToString()
                        };

                        // Add the select list item to our list of dropdown options
                        viewModel.cohorts.Add(cohortOptionTag);
                    }

                    reader.Close();


                    // send it all to the view
                    return(View(viewModel));
                }
            }
        }
Esempio n. 24
0
        public void Arrange()
        {
            _cohort = new Cohort()
            {
                Id = 123
            };
            _cohorts = new List <Cohort>
            {
                new Cohort()
                {
                    Id = 123
                }
            };

            _apprenticeships = new List <Apprenticeship>
            {
                new Apprenticeship {
                    ApprenticeshipStatus = ApprenticeshipStatus.Approved, FirstName = "FirstName", LastName = "LastName"
                }
            };

            _mockCommitmentsV2Service = new Mock <ICommitmentV2Service>();
            _policy = Policy.NoOpAsync();
            var registryPolicy = new PolicyRegistry();

            registryPolicy.Add(Constants.DefaultServiceTimeout, _policy);

            _mockCommitmentsV2Service
            .Setup(c => c.GetApprenticeships(_accountId))
            .ReturnsAsync(_apprenticeships);

            _mockCommitmentsV2Service
            .Setup(c => c.GetCohorts(_accountId))
            .ReturnsAsync(_cohorts);

            _mockCommitmentsV2Service
            .Setup(c => c.GetDraftApprenticeships(_cohort))
            .ReturnsAsync(_apprenticeships);

            _commitmentsV2ServiceWithTimeout = new CommitmentsV2ServiceWithTimeout(_mockCommitmentsV2Service.Object, registryPolicy);
        }
Esempio n. 25
0
        public async Task <IActionResult> Get(string q)
        {
            using (SqlConnection conn = Connection)
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    string command = "SELECT i.Id AS 'Instructor Id', firstName, i.lastName, i.slackHandle, i.cohortId,  c.cohortName, c.Id FROM Instructor i JOIN Cohort c on i.cohortId = c.Id";
                    if (q != null)
                    {
                        command += $" WHERE i.firstName LIKE '{q}' OR i.lastName LIKE '{q}' OR i.slackHandle LIKE '{q}'";
                    }
                    cmd.CommandText = command;
                    SqlDataReader     reader      = cmd.ExecuteReader();
                    List <Instructor> instructors = new List <Instructor>();

                    while (reader.Read())
                    {
                        Cohort cohort = new Cohort
                        {
                            Id         = reader.GetInt32(reader.GetOrdinal("Id")),
                            cohortName = reader.GetString(reader.GetOrdinal("cohortName"))
                        };
                        Instructor instructor = new Instructor
                        {
                            Id            = reader.GetInt32(reader.GetOrdinal("Instructor Id")),
                            firstName     = reader.GetString(reader.GetOrdinal("firstName")),
                            lastName      = reader.GetString(reader.GetOrdinal("lastName")),
                            slackHandle   = reader.GetString(reader.GetOrdinal("slackHandle")),
                            cohortId      = reader.GetInt32(reader.GetOrdinal("cohortId")),
                            currentCohort = cohort
                        };

                        instructors.Add(instructor);
                    }
                    reader.Close();

                    return(Ok(instructors));
                }
            }
        }
Esempio n. 26
0
        /// <summary>
        /// This method executes when the user clicks the edit button for a cohort
        /// and it opens the cohort edit div so that the user can edit the selected cohort
        /// </summary>
        /// <param name="sender">The lbEditCohort LinkButton</param>
        /// <param name="e">The Click event</param>
        protected void lbEditCohort_Click(object sender, EventArgs e)
        {
            //Get the calling button
            LinkButton editButton = (LinkButton)sender;

            //Get the specific repeater item
            GridViewDataItemTemplateContainer item = (GridViewDataItemTemplateContainer)editButton.Parent;

            //Get the hidden field with the PK for deletion
            HiddenField hfCohortPK = (HiddenField)item.FindControl("hfCohortPK");

            //Get the PK from the hidden field
            int?cohortPK = (String.IsNullOrWhiteSpace(hfCohortPK.Value) ? (int?)null : Convert.ToInt32(hfCohortPK.Value));

            if (cohortPK.HasValue)
            {
                using (PyramidContext context = new PyramidContext())
                {
                    //Get the cohort to edit
                    Cohort editCohort = context.Cohort.Find(cohortPK.Value);

                    //Fill the inputs
                    lblAddEditCohort.Text      = "Edit Cohort";
                    txtCohortName.Value        = editCohort.CohortName;
                    deCohortStartDate.Value    = editCohort.StartDate.ToString("MM/dd/yyyy");
                    deCohortEndDate.Value      = (editCohort.EndDate.HasValue ? editCohort.EndDate.Value.ToString("MM/dd/yyyy") : "");
                    ddCohortState.SelectedItem = ddCohortState.Items.FindByValue(editCohort.StateFK);
                    hfAddEditCohortPK.Value    = cohortPK.Value.ToString();
                }

                //Show the cohort div
                divAddEditCohort.Visible = true;

                //Set focus to the cohort name field
                txtCohortName.Focus();
            }
            else
            {
                msgSys.ShowMessageToUser("danger", "Error", "An error occurred while attempting to load the selected cohort!", 20000);
            }
        }
Esempio n. 27
0
        //
        // GET: /Cohort/AddResearchgroup?cohortid=5

        public ActionResult AddResearchgroup(int cohortid)
        {
            Cohort cohort = db.Cohorts.Find(cohortid);

            if (cohort == null)
            {
                return(new HttpStatusCodeResult(422));
            }
            if (cohort.Status != "Current")
            {
                return(new HttpStatusCodeResult(422));
            }

            if (!_projectuservalidationservice.UserCanEditProject(cohort.MultiPARTProjectMultiPARTProjectID))
            {
                ViewBag.ErrorMessage = "Access Denied. Please contact administrator for further assistance.";
                return(View("Error"));
            }

            var existingRGIDs = db.ResearchgroupCohortAssignments.Where(rca => rca.Status == "Current" && rca.CohortID == cohortid).Select(rca => rca.ResearchgroupID);

            ViewBag.ResearchgroupList = new SelectList(
                db.Researchgroups.Where(r => db.ResearchgroupInMultiPARTProjects.Where(rm => rm.Status == "Current" &&
                                                                                       rm.MultiPARTProjectMultiPARTProjectID == cohort.MultiPARTProjectMultiPARTProjectID

                                                                                       && !existingRGIDs.Contains(rm.ResearchgroupResearchgroupID) &&
                                                                                       rm.Options.OptionValue == "Wet Lab").Select(rm => rm.ResearchgroupResearchgroupID).Contains(r.ResearchgroupID)).AsEnumerable(),
                "ResearchgroupID", "ResearchgroupName");

            ViewBag.cohortid    = cohortid;
            ViewBag.cohortlabel = cohort.CohortLabel;

            ResearchgroupCohortAssignmentViewModel rcaVM = new ResearchgroupCohortAssignmentViewModel
            {
                CohortID           = cohortid,
                MultiPARTProjectID = cohort.MultiPARTProjectMultiPARTProjectID,
                CohortLabel        = cohort.CohortLabel
            };

            return(View(rcaVM));
        }
Esempio n. 28
0
 public void changeCohort(Cohort newCohort = null)
 {
     if (cohort != soloCohort)
     {
         cohort.removeMember(this);
         if (task != null && (task.nature == Task.actions.give || task.nature == Task.actions.take))
         {
             cohort.TaskAbandoned(task, dispensed);
         }
         Stop();
     }
     if (newCohort == null || newCohort.Equals(soloCohort))
     {
         newCohort = soloCohort;
     }
     else
     {
         newCohort.addMember(this);
     }
     cohort = newCohort;
 }
Esempio n. 29
0
 public ActionResult Create(Cohort cohort)
 {
     try
     {
         using (SqlConnection conn = Connection)
         {
             conn.Open();
             using (SqlCommand cmd = conn.CreateCommand())
             {
                 cmd.CommandText = @"INSERT INTO Cohort VALUES (@CohortName)";
                 cmd.Parameters.Add(new SqlParameter("@CohortName", cohort.CohortName));
                 cmd.ExecuteNonQuery();
                 return(RedirectToAction(nameof(Index)));
             }
         }
     }
     catch
     {
         return(View());
     }
 }
        public List <Cohort> Get(string cohortId = "{00000000-0000-0000-0000-000000000000}")
        {
            Guid          id      = Utils.ToGuid(cohortId);
            List <Cohort> cohorts = new List <Cohort>();

            using (var dbContext = new MedialynxDbCohortContext()) {
                if (id != Guid.Empty)
                {
                    string sid    = id.ToString("B");
                    Cohort cohort = dbContext.Cohorts.FirstOrDefault(c => c != null && c.Id == sid);
                    cohorts.Add(cohort);
                }
                else
                {
                    // Add all cohorts
                    cohorts.AddRange(dbContext.Cohorts);
                }
            }
            cohorts.Sort(new CohortComparer());
            return(cohorts);
        }
        public SiteConditions GetFromKey(uint key)
        {
            SiteConditions s=null;
            if (initialSites.TryGetValue(key, out s) && siteoutput == null)
            {
                hydrology = s.hydrology;
                establishment = s.Establishment;

                cohorts = new SiteCohorts();
                foreach (ISpeciesCohorts speciesCohorts in s.cohorts)
                {
                    foreach (Cohort cohort in speciesCohorts)
                    {
                        Cohort newcohort = new Cohort(cohort);
                        cohorts.AddNewCohort(newcohort, PlugIn.TStep);
                    }
                }
                forestfloor = s.forestfloor;
                canopylaimax = s.CanopyLAImax;
            }
            return s;
        }
        public void AddNewCohort(ISpecies species, ActiveSite site)
        {
            //System.Console.WriteLine("AddNewCohort " + site + " " + species.Name);
            siteconditions[site].NewCohorts[species]++;

            Cohort cohort = new Cohort(species, 1, ConstantParameters.InitialFol, 0, ConstantParameters.InitialWood, 0, ConstantParameters.InitialRoot, year);

            siteconditions[site].Establishment.Establishments[species]++;

            if (HasSiteOutput[site] == true)
            {
                CohortOutput.WriteHeader(site, cohort);
            }

            siteconditions[site].AddNewCohort(cohort, PlugIn.TStep);
        }
        public void BiomassSpinUp(List<Landis.Library.AgeOnlyCohorts.ICohort> ageCohorts, ActiveSite site)
        {
            if (ageCohorts.Count == 0)
            {
                return;
            }
            System.DateTime SpinUpDate;

            // OLD: SpinUpDate = PlugIn.StartDate.AddYears(-(ageCohorts[0].Age) + ((successionTimestep == 1) ? -1 : 0));

            SpinUpDate = PlugIn.StartDate.AddYears(-(ageCohorts[0].Age));

            while (SpinUpDate.CompareTo(PlugIn.StartDate) < 0)
            {
                //  Add those cohorts that were born at the current year
                foreach (Library.AgeOnlyCohorts.ICohort ageonlycohort in ageCohorts)
                {
                    if (PlugIn.StartDate.Year - SpinUpDate.Year == ageonlycohort.Age)
                    {
                        Cohort cohort = new Cohort(ageonlycohort.Species, 1, ConstantParameters.InitialFol, 0, ConstantParameters.InitialWood, ConstantParameters.InitialFol, ConstantParameters.InitialRoot, SpinUpDate.Year);

                        AddNewCohort(cohort, PlugIn.TStep);

                        if (siteoutput != null)
                        {
                            CohortOutput.WriteHeader(site, cohort);
                        }
                    }
                }
                GrowCohorts(SpinUpDate, SpinUpDate.AddYears(1), false);

                SpinUpDate = SpinUpDate.AddYears(1);
            }
        }
 public void AddNewCohort(Cohort cohort, int SuccessionTimeStep)
 {
     cohorts.AddNewCohort(cohort, SuccessionTimeStep);
 }
 public CohortBiomass(Cohort Cohort)
 {
     this.cohort = Cohort;
 }
        //---------------------------------------------------------------------
        /// <summary>
        /// Grows all cohorts at a site for a specified number of years.  The
        /// dead pools at the site also decompose for the given time period.
        /// </summary>
        public void AddNewCohort(ISpecies species, ActiveSite site)
        {
            PlugIn.NewCohorts[site][species]++;
            Cohort cohort = new Cohort(species, 1, ConstantParameters.InitialFol, 0,0, 0, 0, year, false);

            CohortOutput.WriteHeader(site, cohort);

            PlugIn.Cohorts[site].AddNewCohort(cohort);
        }
        //---------------------------------------------------------------------
        /// <summary>
        /// Makes the set of biomass cohorts at a site based on the age cohorts
        /// at the site, using a specified method for computing a cohort's
        /// initial biomass.
        /// </summary>
        /// <param name="ageCohorts">
        /// A sorted list of age cohorts, from oldest to youngest.
        /// </param>
        /// <param name="site">
        /// Site where cohorts are located.
        /// </param>
        /// <param name="initialBiomassMethod">
        /// The method for computing the initial biomass for a new cohort.
        /// </param>
        public static ISiteCohorts MakeBiomassCohorts(List<Landis.Library.AgeOnlyCohorts.ICohort> ageCohorts,ActiveSite site)
        {
            PlugIn.Cohorts[site] = new Library.BiomassCohortsPnET.SiteCohorts();

            Hydrology.Initialize(site);

            Hydrology.AnnualTranspiration[site] = 0;
            CanopyBiomass.CanopyLAI[site] = 0;

            if (ageCohorts.Count == 0)
            {
                return PlugIn.Cohorts[site];
            }

            System.DateTime SpinUpDate = PlugIn.StartDate.AddYears(-(ageCohorts[0].Age) + ((successionTimestep == 1) ? -1 : 0));

            while (SpinUpDate.CompareTo(PlugIn.StartDate) < 0)
            {
                CanopyBiomass.SubCanopyPAR[site] = Static.PAR0[SpinUpDate];

                //  Add those cohorts that were born at the current year
                foreach (Library.AgeOnlyCohorts.ICohort ageonlycohort in ageCohorts)
                {
                    if (PlugIn.StartDate.Year - SpinUpDate.Year == ageonlycohort.Age)
                    {
                        Cohort cohort = new Cohort(ageonlycohort.Species, 1, ConstantParameters.InitialFol, 0, 0, 0, 0, SpinUpDate.Year, true);
                        PlugIn.Cohorts[site].AddNewCohort(cohort);
                        CohortOutput.WriteHeader(site, cohort);
                        SiteOutput.WriteHeader(site);
                    }
                }

                PlugIn.GrowCohorts(site, SpinUpDate, SpinUpDate.AddYears(1), false);

                SpinUpDate = SpinUpDate.AddYears(1);
            }

            return PlugIn.Cohorts[site];
        }