public void SetUp() { _posts = new List<Post>(); _post = new Post { Title = "Test Title", Body= "This is a test post" }; _posts.Add(_post); _postService = MockRepository.GenerateMock<IPostService>(); _controller = new SiteController(_postService); }
public void AssignOrganizationAdminPostHasHttpPostAttribute() { var mediator = new Mock <IMediator>(); var controller = new SiteController(null, null, mediator.Object); var model = new AssignOrganizationAdminModel { UserId = It.IsAny <string>(), OrganizationId = It.IsAny <int>() }; var attribute = controller.GetAttributesOn(x => x.AssignOrganizationAdmin(model)).OfType <HttpPostAttribute>().SingleOrDefault(); Assert.NotNull(attribute); }
public async Task DeleteUserSendsUserQueryWithCorrectUserId() { var mediator = new Mock <IMediator>(); const string userId = "foo_id"; mediator.Setup(x => x.SendAsync(It.Is <UserQuery>(q => q.UserId == userId))).ReturnsAsync(new EditUserModel()); var controller = new SiteController(null, null, mediator.Object); await controller.DeleteUser(userId); mediator.Verify(m => m.SendAsync(It.Is <UserQuery>(q => q.UserId == userId)), Times.Once); }
public void SearchForCorrectUserWhenManagingApiKeys() { var mediator = new Mock <IMediator>(); var logger = new Mock <ILogger <SiteController> >(); string userId = Guid.NewGuid().ToString(); mediator.Setup(x => x.Send(It.Is <UserByUserIdQuery>(q => q.UserId == userId))).Returns(new ApplicationUser()); var controller = new SiteController(null, logger.Object, mediator.Object); controller.ManageApiKeys(userId); mediator.Verify(m => m.Send(It.Is <UserByUserIdQuery>(q => q.UserId == userId)), Times.Once); }
private SiteController AddRobotPlaneSite(KineticHierarchyController parent, XmlNode site_xml, XmlUtils.Defaults defaults) { Vector3 mujoco_size = XmlUtils.GetVector3WithDefaults(site_xml, defaults, "size", Vector3.one); return(SiteController.CreatePlane( parent, XmlUtils.GetString(site_xml, "name", null), XmlUtils.GetVector3WithDefaults(site_xml, defaults, "pos", Vector3.zero), XmlUtils.GetRotationWithDefaults(site_xml, defaults, Quaternion.identity) * Quaternion.Euler(90.0f, 0.0f, 0.0f), 2 * new Vector3(mujoco_size.x / 10.0f, 0.0f, mujoco_size.y / 10.0f))); }
public async Task AssignApiRoleQueriesForCorrectId() { var mediator = new Mock <IMediator>(); var logger = new Mock <ILogger <SiteController> >(); string userId = Guid.NewGuid().ToString(); mediator.Setup(x => x.Send(It.Is <UserByUserIdQuery>(q => q.UserId == userId))).Returns(new ApplicationUser()); var controller = new SiteController(null, logger.Object, mediator.Object); await controller.AssignApiAccessRole(userId); mediator.Verify(m => m.Send(It.Is <UserByUserIdQuery>(q => q.UserId == userId)), Times.Once); }
public void EditUserGetSendsUserByUserIdQueryWithCorrectUserId() { var mediator = new Mock <IMediator>(); var logger = new Mock <ILogger <SiteController> >(); string userId = It.IsAny <string>(); mediator.Setup(x => x.Send(It.Is <UserByUserIdQuery>(q => q.UserId == userId))) .Returns(new ApplicationUser()); var controller = new SiteController(null, logger.Object, mediator.Object); controller.EditUser(userId); mediator.Verify(m => m.Send(It.Is <UserByUserIdQuery>(q => q.UserId == userId)), Times.Once); }
public async Task RevokeOrganizationAdminSendsUserByUserIdQueryWithCorrectUserId() { var mediator = new Mock <IMediator>(); var logger = new Mock <ILogger <SiteController> >(); string userId = It.IsAny <string>(); mediator.Setup(x => x.Send(It.Is <UserByUserIdQuery>(q => q.UserId == userId))).Returns(new ApplicationUser()); var controller = new SiteController(null, logger.Object, mediator.Object); await controller.RevokeOrganizationAdmin(userId); mediator.Verify(m => m.Send(It.Is <UserByUserIdQuery>(q => q.UserId == userId)), Times.Once); }
public void RemoveParentCategoryShouldMoveUsersFromParentToChildCategory() { User user2 = new User("user2"); SiteController siteController = new SiteController(); this.user.AssignToCategory(this.category); user2.AssignToCategory(this.category); this.category.AssignChildCategory(this.category2); siteController.RemoveCategory(category); CollectionAssert.AreEqual(new User[] { this.user, user2 }, this.category2.Users, "Users from parent category weren't assigned to child category."); }
public async Task DeleteUserReturnsTheCorrectViewModel() { var mediator = new Mock <IMediator>(); const string userId = "foo_id"; mediator.Setup(x => x.SendAsync(It.IsAny <UserQuery>())).ReturnsAsync(new EditUserModel()); var controller = new SiteController(null, null, mediator.Object); var result = await controller.DeleteUser(userId); var model = ((ViewResult)result).ViewData.Model as DeleteUserModel; Assert.Equal(model.UserId, userId); Assert.IsType <DeleteUserModel>(model); }
public async Task EditUserPostSendsUserByUserIdQueryWithCorrectUserId() { var mediator = new Mock <IMediator>(); EditUserModel model = new EditUserModel() { UserId = "1234", }; mediator.Setup(x => x.Send(It.Is <UserByUserIdQuery>(q => q.UserId == model.UserId))) .Returns(new ApplicationUser()); var controller = new SiteController(null, null, mediator.Object); await controller.EditUser(model); mediator.Verify(m => m.Send(It.Is <UserByUserIdQuery>(q => q.UserId == model.UserId)), Times.Once); }
public void EditUserGetReturnsCorrectViewModelWhenOrganizationIdIsNull() { { var mediator = new Mock <IMediator>(); string userId = It.IsAny <string>(); mediator.Setup(x => x.Send(It.Is <UserByUserIdQuery>(q => q.UserId == userId))) .Returns(new ApplicationUser()); var controller = new SiteController(null, null, mediator.Object); var result = controller.EditUser(userId); var model = ((ViewResult)result).ViewData.Model as EditUserModel; Assert.Equal(model.Organization, null); Assert.IsType <EditUserModel>(model); } }
private bool AddRobotSite(KineticHierarchyController parent, XmlNode site_xml, XmlUtils.Defaults defaults) { defaults = defaults.Resolve(XmlUtils.GetString(site_xml, "class", null)).GetSubclass("site"); SiteController site = null; string type = XmlUtils.GetStringWithDefaults(site_xml, defaults, "type", "sphere"); if ("box".Equals(type)) { site = AddRobotBoxSite(parent, site_xml, defaults); } else if ("plane".Equals(type)) { site = AddRobotPlaneSite(parent, site_xml, defaults); } else if (type == null || "sphere".Equals(type)) { site = AddRobotSphereSite(parent, site_xml, defaults); } else if ("cylinder".Equals(type)) { site = AddRobotCylinderSite(parent, site_xml, defaults); } else if ("capsule".Equals(type)) { site = AddRobotCapsuleSite(parent, site_xml, defaults); } else { Logger.Error("RobotLoader::AddRobotSite::Unsupported site type: {0} in {1}.", type, site_xml.OuterXml); return(false); } if (site == null) { Logger.Error("RobotLoader::AddRobotSite::Cannot instantiate site."); return(false); } ResolveMaterial(site_xml, defaults, site); return(true); }
public void Deactivated_ViewResult() { // Arrange SiteController controller = new SiteController(); // Act IActionResult result = controller.Deactivated(); // Assert Assert.NotNull(result); ViewResult viewResult = Assert.IsType <ViewResult>(result); Assert.NotNull(viewResult.Model); TemplateViewModel templateViewModel = Assert.IsType <TemplateViewModel>(viewResult.Model); Assert.Equal("Deactivated", templateViewModel.Header); Assert.Equal("Your account has been disabled. Please, contact us for further information.", templateViewModel.Text); Assert.Equal("Template", viewResult.ViewName); }
/// <summary> /// An on-click method that adds a site to the database, adds assigns a new survey word to the site, and adds a "Not Applicable" unit associated with the new site. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void AddSite_Click(object sender, EventArgs e) { SiteController sysmgr = new SiteController(); SurveyWordController swControl = new SurveyWordController(); UnitController unControl = new UnitController(); string siteName = AddSiteTextBox.Text.Trim(); int admin = int.Parse(Session["adminID"].ToString()); MessageUserControl.TryRun(() => { sysmgr.AddSite(siteName, admin); // adds the site to the database swControl.NewSite_NewWord(siteName); // assigns a survey word to the site unControl.NewSite_NewUnit(siteName, admin); // adds the Not Applicable Unit option to the site ListView1.DataBind(); AddSiteTextBox.Text = ""; }, "Success", "Successfully added the new site: \"" + siteName + "\""); }
public void Contact_ViewResult() { // Arrange SiteController controller = new SiteController(); // Act IActionResult result = controller.Contact(); // Assert Assert.NotNull(result); ViewResult viewResult = Assert.IsType <ViewResult>(result); Assert.NotNull(viewResult.Model); TemplateViewModel templateViewModel = Assert.IsType <TemplateViewModel>(viewResult.Model); Assert.Equal("Contact", templateViewModel.Header); Assert.Equal("Lorem ipsum", templateViewModel.Text); Assert.Equal("Template", viewResult.ViewName); }
public async Task EditUserPostInvokesUpdateUserWithCorrectUserWhenUsersAssociatedSkillsAreNotNullAndThereIsAtLeastOneAssociatedSkillForTheUser() { var mediator = new Mock <IMediator>(); EditUserModel model = new EditUserModel() { UserId = It.IsAny <string>(), AssociatedSkills = new List <UserSkill>() { new UserSkill() { SkillId = 1, Skill = new Skill() { Id = 1 } } } }; var user = new ApplicationUser() { Id = model.UserId, AssociatedSkills = new List <UserSkill>() { new UserSkill() { SkillId = 2, Skill = new Skill() { Id = 2 } } } }; mediator.Setup(x => x.Send(It.Is <UserByUserIdQuery>(q => q.UserId == model.UserId))) .Returns(user); var controller = new SiteController(null, null, mediator.Object); await controller.EditUser(model); mediator.Verify(m => m.SendAsync(It.Is <UpdateUser>(q => q.User.AssociatedSkills[0] == model.AssociatedSkills[0])), Times.Once); }
public void IndexReturnsCorrectViewModel() { var mediator = new Mock <IMediator>(); var users = new List <ApplicationUser>() { new ApplicationUser { Id = It.IsAny <string>() }, new ApplicationUser { Id = It.IsAny <string>() } }; mediator.Setup(x => x.Send(It.IsAny <AllUsersQuery>())).Returns(users); var controller = new SiteController(null, null, mediator.Object); var result = controller.Index(); var model = ((ViewResult)result).ViewData.Model as SiteAdminModel; Assert.Equal(model.Users.Count(), users.Count()); Assert.IsType <SiteAdminModel>(model); }
/// <summary> /// Default Web Page Method use to initialize pages and check if the user is logged in. /// Initialize drop down lists alert labels /// </summary> /// <param name="sender">Contains a reference to the control/object that raised the event.</param> /// <param name="e">Contains the event data.</param> protected void Page_Load(object sender, EventArgs e) { // this is for the client side input values to be retained after the page loads when a validation error is triggered (so the text is not lost) string startingPeriodInput = Request.Form["StartingPeriodInput"]; string endingPeriodInput = Request.Form["EndingPeriodInput"]; this.startingInputValue = startingPeriodInput; this.endingInputValue = endingPeriodInput; // Redirect user to login if not logged in if (Session["securityID"] == null) { Response.Redirect("~/Admin/Login.aspx"); } else if (!IsPostBack) { // Initialize Meal Controller, Meal List, Site Controller, and SitePOCO List variable MealController mealController = new MealController(); List <MealPOCO> mealList = mealController.GetMealList(); SiteController siteController = new SiteController(); List <SitePOCO> siteList = siteController.GetSiteList(); // Initialize Alert Label Alert.Visible = false; Alert.Text = ""; // Iniitalize and setup Meal Drop down list MealDropDownList.DataSource = mealList; MealDropDownList.DataValueField = "mealID"; MealDropDownList.DataTextField = "mealName"; MealDropDownList.DataBind(); // Iniitalize and setup Site/Hospital Drop down list HospitalDropDownList.DataSource = siteList; HospitalDropDownList.DataValueField = "siteID"; HospitalDropDownList.DataTextField = "siteName"; HospitalDropDownList.DataBind(); } // Initialize Alert Label Alert.Text = ""; Alert.Visible = false; }
/// <summary> ///Checks if the correct passcode was entered. If passcode is correct user will be re-directed to the survey page, if not an error message will be thrown. /// </summary> /// <param name="sender">Contains a reference to the control/object that raised the event.</param> /// <param name="e">Contains the event data of the event that triggered the method.</param> protected void SubmitButton_Click(object sender, EventArgs e) { //Calls utility controllter Utility utility = new Utility(); //Creates a empty list to store Active Site's Passcodes List <string> PasscodeList = new List <string>(); SiteController sysmgr = new SiteController(); PasscodeList = sysmgr.Site_PasscodeList(); //Passcode entered from textbox string passcode = SurveyPasscode.Text; //Check if passcode entered on page matches any in list MessageUserControl.TryRun(() => { utility.checkValidString(SurveyPasscode.Text); for (int SitePasscode = 0; SitePasscode < PasscodeList.Count; SitePasscode++) { //Passcode matches if (passcode.ToUpper() == PasscodeList[SitePasscode].ToUpper()) { //Redirects the user to survey page correct passcode is passed to survey page Response.Redirect("Survey.aspx?passcode=" + passcode); } else if (passcode == "") { // No Passcode is entered show message MessageUserControl.ShowInfoError("No Passcode Entered", "Please enter the passcode to access the survey."); } else { // Passcode is incorrect show message MessageUserControl.ShowInfoError("Incorrect Passcode", "Passcode entered was incorrect. Please try again."); SurveyPasscode.Text = ""; } } }); }
public async Task EditUserPostSendsUpdateUserWithCorrectUserWhenUsersAssociatedSkillsAreNotNull() { var mediator = new Mock <IMediator>(); EditUserModel model = new EditUserModel() { UserId = It.IsAny <string>(), AssociatedSkills = new List <UserSkill>() { new UserSkill() { Skill = It.IsAny <Skill>() } } }; mediator.Setup(x => x.Send(It.Is <UserByUserIdQuery>(q => q.UserId == model.UserId))) .Returns(new ApplicationUser()); var controller = new SiteController(null, null, mediator.Object); await controller.EditUser(model); mediator.Verify(m => m.SendAsync(It.Is <UpdateUser>(q => q.User.AssociatedSkills[0].Skill == model.AssociatedSkills[0].Skill)), Times.Once); }
protected void InsertUser_Click(object sender, CommandEventArgs e) { MessageUserControl.TryRun(() => { SiteController sitemgr = new SiteController(); // find the site that the user is being inserted in Site site = sitemgr.Site_FindById(int.Parse(SiteAddDropDownList.SelectedValue)); MessageUserControl.Visible = true; if (string.IsNullOrWhiteSpace(FirstNameTextBox.Text)) { throw new Exception("First name is a required field, please enter a valid first name value"); } else if (string.IsNullOrWhiteSpace(LastNameTextBox.Text)) { throw new Exception("Last name is a required field, please enter a valid last name value"); } else if (string.IsNullOrWhiteSpace(RequestedPasswordLabel.Text)) { throw new Exception("Password is a required field, please enter a valid password value"); } else if (string.IsNullOrWhiteSpace(RoleMemberships.SelectedValue)) { throw new Exception("Role is required for every employee please enter a valid role for before inserting the employee"); } else if (string.IsNullOrWhiteSpace(UserNameLabel.Text)) { throw new Exception("Please assign the user a username"); } else if (site.Disabled) { // refresh the site dropdown list without disabled sites if the user attempted to insert a user into a disabled site SiteAddDropDownList.DataBind(); throw new Exception("Please select a site which is not deactivated"); } else { UserProfile user = new UserProfile(); Utility utility = new Utility(); user.UserName = UserNameLabel.Text; user.FirstName = FirstNameTextBox.Text; user.LastName = LastNameTextBox.Text; user.SiteId = int.Parse(SiteAddDropDownList.SelectedValue); user.RequestedPassword = RequestedPasswordLabel.Text; var roleList = new List <string>(); roleList.Add(RoleMemberships.SelectedValue); user.RoleMemberships = roleList; user.Active = (disabledCheckBox.Checked); utility.checkValidString(user.UserName); utility.checkValidString(user.FirstName); utility.checkValidString(user.LastName); utility.checkValidString(user.RequestedPassword); UserManager sysmgr = new UserManager(); sysmgr.AddUser(user); if (User.IsInRole(SecurityRoles.SuperUser)) { // if the user is a SuperUser then let the user see all users and all sites in dropdown lists SiteAddDropDownList.DataSourceID = "SiteList"; SiteAddDropDownList.DataValueField = "SiteId"; SiteAddDropDownList.DataTextField = "SiteName"; SiteCheckBoxList.Enabled = true; SiteCheckBoxList.Visible = true; SiteScrollDiv.Visible = true; UserListView.DataSourceID = "UserListViewODS"; UserListView.DataSource = null; } else if (User.IsInRole(SecurityRoles.AdminEdits)) { // if the user is an AdminEdit do not show him users with the superuser role and do not show him the admin site SiteAddDropDownList.DataSourceID = null; List <Site> info = new List <Site>(); info.Add(sitemgr.Site_FindById(sysmgr.GetUserSiteId(User.Identity.Name))); SiteAddDropDownList.DataSource = info; SiteAddDropDownList.DataTextField = "SiteName"; SiteAddDropDownList.DataValueField = "SiteId"; UserListView.DataSourceID = ""; UserListView.DataSource = sysmgr.ListUser_BySearchParams("", new List <int>(new int[] { sitemgr.Site_FindById(sysmgr.GetUserSiteId(User.Identity.Name)).SiteId }), new List <string>(), 3); SiteCheckBoxList.Enabled = false; SiteCheckBoxList.Visible = false; SiteScrollDiv.Visible = false; } UserListView.DataBind(); LookupUsers(); CancelButton_Command(sender, e); MessageUserControl.Visible = true; } }, "Success", "New user has been added."); }
public void SetupContext() { mock = new Mock <IRepository>(); controller = new SiteController(mock.Object); }
/// <summary> /// Default Web Page Method use to initialize pages and check if the user is logged in and if it passes the required filters for generating reports. /// </summary> /// <param name="sender">Contains a reference to the control/object that raised the event.</param> /// <param name="e">Contains the event data.</param> protected void Page_Load(object sender, EventArgs e) { // Set the visibility for Alert Message Label to hidden. Alert.Visible = false; // Check if the user is logged in. Redirect to Admin Login page if the user doesn't have a securityId if (Session["securityID"] == null) { Response.Redirect("~/Admin/Login.aspx"); } else { // Initialize and set filter variable with the type of FilterPOCO and retrieve the Session state with an ID of "filter" that is passed from the ViewReportFilter page // to be use for the generating report. FilterPOCO filter = (FilterPOCO)(Session["filter"]); // Check if the filter has a value. Redirect the user to ViewReportFilter page if the the filter doesn't have any values. if (filter == null) { Response.Redirect("~/Admin/ViewReportFilter.aspx"); } else { // Instantiate Report Controller, Meal Controller, Site Controller, Site Name, FinalReportPOCO and Meal variable. ReportController reportMgr = new ReportController(); MealController mealMgr = new MealController(); Meal meal = new Meal(); FinalReportPOCO report = new FinalReportPOCO(); SiteController siteMgr = new SiteController(); string siteName = ""; // Initialize report by calling GenerateOverAllReport method from Report Controller which return a FinalReportPOCO object. report = reportMgr.GenerateOverAllReport(filter.startingDate, filter.endDate, filter.siteID, filter.mealID); // Initialize Site Name variable by calling DisplaySiteName method from Site Controller which return a string. siteName = siteMgr.DisplaySiteName(filter.siteID); // Check if siteName is null, change the Site Name variable to "All sites". if (siteName == null) { siteName = "All sites"; } // Initialize Meal variable by calling GetMeal method from Meal Controller which return a Meal object. meal = mealMgr.GetMeal(filter.mealID); // Check if meal variable is null. if (meal == null) { // If meal variable is null change the FilterDescription Label Text to the described markup. FilterDescription.Text = "Report from " + siteName + " from " + filter.startingDate.ToString("MMMM-dd-yyyy") + " to " + filter.endDate.ToString("MMMM-dd-yyyy") + " with no meal filter."; } else { // If meal variable is not null change the FilterDescription Label Text to the described markup. FilterDescription.Text = "Report from " + siteName + " from " + filter.startingDate.ToString("MMMM-dd-yyyy") + " to " + filter.endDate.ToString("MMMM-dd-yyyy") + " with a meal filter of " + meal.meal_name + "."; } // Set the TotalNumberOfSubmittedSurvey Label Text to the described markup. TotalNumberOfSubmittedSurvey.Text = "Total number of submitted survey with the given criteria: " + report.SubmittedSurveyList.Count().ToString() + " surveys submitted."; // Check if the SubmittedSurveyList from report variable has atleast 1 survey. if (report.SubmittedSurveyList.Count < 1) { // Hide TotalNumberOfSubmittedSurvey Label. TotalNumberOfSubmittedSurvey.Visible = false; // Display EmptyMessage Label. EmptyMessage.Visible = true; // Set EmptyMessage Label to "No Submitted Survey Found. Please check your filter". EmptyMessage.Text = "No Submitted Survey Found. Please check your filter"; } } } }
/// <summary> /// Handles all the events caused by clicking any button in the ActiveSiteListView. /// </summary> /// <param name="sender">Contains a reference to the control/object that raised the event.</param> /// <param name="e">Contains the event data of the event that triggered the method.</param> protected void SiteListView_ItemCommand(object sender, ListViewCommandEventArgs e) { MessageUserControl.Visible = false; int siteId = 1; // If the cancel button is pressed the CommandArgument will be null so we do not want to try to convert it to string. // Otherwise we want to get the siteId of the row the user clicked the button on. if (!e.CommandName.Equals("Cancel")) { siteId = int.Parse(e.CommandArgument.ToString()); } // If the user presses the "Update" button we grab the values they input into the textboxes and then run Site_Update using them as the parameters. // Afterwords we must set EditIndex to -1 to deactivate edit mode on the updated field. if (e.CommandName.Equals("Change")) { // Grabs the index of the current item in the listview. int i = e.Item.DisplayIndex; // Gets the values the user has input into the textboxs and assigns them to a string variable. TextBox siteNameBox = ActiveSiteListView.Items[i].FindControl("SiteNameTextBox") as TextBox; string siteName = siteNameBox.Text; TextBox descriptionBox = ActiveSiteListView.Items[i].FindControl("DescriptionTextBox") as TextBox; string description = descriptionBox.Text; TextBox passcodeBox = ActiveSiteListView.Items[i].FindControl("PasscodeTextBox") as TextBox; string passcode = passcodeBox.Text; MessageUserControl.TryRun(() => { MessageUserControl.Visible = true; // Validation for special characters. Utility utility = new Utility(); utility.checkValidString(siteName); utility.checkValidString(description); utility.checkValidString(passcode); // Updates the selected site, turns off the edit mode and rebinds all active site listviews. SiteController sysmgr = new SiteController(); sysmgr.Site_Update(siteId, siteName, description, passcode); ActiveSiteListView.DataSourceID = ActiveSiteListODS.ID; ActiveSiteListView.EditIndex = -1; ActiveSiteListView.DataBind(); AddSiteListView.DataBind(); // Clears the search field and re-enables all the controls that are disabled during edit mode. ActiveSearchBox.Text = ""; ActiveSearchButton.Enabled = true; ActiveClearButton.Enabled = true; DataPager pager = ActiveSiteListView.FindControl("ActiveDataPager") as DataPager; pager.Visible = true; }, "Success", "Site has been updated"); } // If the user presses deactivate we simply take the siteId from above and deactivate the site it is attributed to. else if (e.CommandName.Equals("Deactivate")) { MessageUserControl.TryRun(() => { MessageUserControl.Visible = true; // Deactivates the current site. SiteController sysmgr = new SiteController(); sysmgr.Site_Deactivate(siteId); }, "Success", "Site has been deactivated"); // Rebinds all listviews and resets the ODS' to their defaults rather than the search ODS. ActiveSiteListView.DataSourceID = ActiveSiteListODS.ID; DeactivatedSiteListView.DataSourceID = DeactivatedSiteListODS.ID; ActiveSiteListView.DataBind(); AddSiteListView.DataBind(); DeactivatedSiteListView.DataBind(); } }
private void ClearData() { listCameras = CameraController.GetCameras(); listCatalogues = CatalogueController.GetCatalogues(); listColorSpaces = ColorSpaceController.GetColorSpaces(); listFileFormats = FileFormatController.GetFileFormats(); listOptics = OpticsController.GetOptics(); listPhotographers = PhotographerController.GetPhotographers(); listScopes = ScopeController.GetScopes(); listSites = SiteController.GetSites(); tbCollectionId.Text = "(adding)"; tbDateTime.Text = ""; tbComments.Text = ""; tbFile.Text = ""; tbMetadataFile.Text = ""; tbObjectId.Text = ""; tbObjectTitle.Text = ""; tbResolutionX.Text = ""; tbResolutionY.Text = ""; tbTotalFrames.Value = 1; cbCamera.Items.Clear(); foreach (var item in listCameras) { cbCamera.Items.Add(item.LongName); } cbCatalogue.Items.Clear(); foreach (var item in listCatalogues) { cbCatalogue.Items.Add(item.LongName); } cbColorSpace.Items.Clear(); foreach (var item in listColorSpaces) { cbColorSpace.Items.Add(item.Name); } cbFileFormat.Items.Clear(); foreach (var item in listFileFormats) { cbFileFormat.Items.Add(item.LongName); } cbPhotographer.Items.Clear(); foreach (var item in listPhotographers) { cbPhotographer.Items.Add(item.GetInformalName()); } cbScope.Items.Clear(); foreach (var item in listScopes) { cbScope.Items.Add(item.GetScopeName()); } clbOptics.Items.Clear(); foreach (var item in listOptics) { clbOptics.Items.Add(item.Id + "| " + item.GetOpticName()); } cbSite.Items.Clear(); foreach (var item in listSites) { cbSite.Items.Add(item.Name); } lblStatus.Text = "Loaded all assets."; }
protected void Page_Load(object sender, EventArgs e) { // if the participant doesn't take a survey if (Session["takingSurvey"] == null) { //abandon the session Session.Abandon(); //redirect the participant to the survey access page Response.Redirect("~/"); } if (!IsPostBack) { SiteController site = new SiteController(); //allows access to the site controller //displays the hospital name at the top of the survey SiteName.Text = "Hospital: <span style=font-weight:bold;>" + site.DisplaySiteName(Convert.ToInt32(Session["siteID"])) + "</span>"; //Populate question labels QuestionTextController sysmgr = new QuestionTextController(); //allows access to the question text controller Q1.Text = "1. " + sysmgr.GetQuestion1(); Q1A.Text = sysmgr.GetQuestion1A(); Q1B.Text = sysmgr.GetQuestion1B(); Q1C.Text = sysmgr.GetQuestion1C(); Q1D.Text = sysmgr.GetQuestion1D(); Q1E.Text = sysmgr.GetQuestion1E(); Q2.Text = "2. " + sysmgr.GetQuestion2(); Q3.Text = "3. " + sysmgr.GetQuestion3(); Q4.Text = "4. " + sysmgr.GetQuestion4(); Q5.Text = "5. " + sysmgr.GetQuestion5(); //if there is a session value for unit if (Session["Unit"] != null) { //choose selected unit UnitDropDownList.SelectedValue = Session["Unit"].ToString(); UnitDropDownList.SelectedItem.Selected = true; } //if there is a session value for participant type if (Session["ParticipantType"] != null) { //choose selected participant type ParticipantTypeDropDownList.SelectedValue = Session["ParticipantType"].ToString(); ParticipantTypeDropDownList.SelectedItem.Selected = true; } //if there is a session value for meal type if (Session["MealType"] != null) { //choose selected meal type MealTypeDropDownList.SelectedValue = Session["MealType"].ToString(); MealTypeDropDownList.SelectedItem.Selected = true; } //if there is a session for Q1A if (Session["Q1A"] != null) { //choose selected Q1A Q1AResponse.SelectedValue = Session["Q1A"].ToString(); Q1AResponse.SelectedItem.Selected = true; } //if there is a session for Q1B if (Session["Q1B"] != null) { //choose selected Q1B Q1BResponse.SelectedValue = Session["Q1B"].ToString(); Q1BResponse.SelectedItem.Selected = true; } //if there is a session for Q1C if (Session["Q1C"] != null) { //choose selected Q1C Q1CResponse.SelectedValue = Session["Q1C"].ToString(); Q1CResponse.SelectedItem.Selected = true; } //if there is a session for Q1D if (Session["Q1D"] != null) { //choose selected Q1D Q1DResponse.SelectedValue = Session["Q1D"].ToString(); Q1DResponse.SelectedItem.Selected = true; } //if there is a session for Q1E if (Session["Q1E"] != null) { //choose selected Q1E Q1EResponse.SelectedValue = Session["Q1E"].ToString(); Q1EResponse.SelectedItem.Selected = true; } //if there is a session for Q2 if (Session["Q2"] != null) { //choose selected Q2 Q2Response.SelectedValue = Session["Q2"].ToString(); Q2Response.SelectedItem.Selected = true; } //if there is a session for Q3 if (Session["Q3"] != null) { //choose selected Q3 Q3Response.SelectedValue = Session["Q3"].ToString(); Q3Response.SelectedItem.Selected = true; } //if there is a session for Q4 if (Session["Q4"] != null) { //choose selected Q4 Q4Response.SelectedValue = Session["Q4"].ToString(); Q4Response.SelectedItem.Selected = true; } //if there is a session for Q5 if (Session["Q5"] != null) { //choose selected Q5 Question5.Text = Session["Q5"].ToString(); } } }
/// <summary> ///Loads the page. For the survey page Page_Load checks the database to see if questions exist or no active units exist on Site. If no questions or no active units exist the user will be redirected to the SurveyAccessPage. /// </summary> /// <param name="sender">Contains a reference to the control/object that raised the event.</param> /// <param name="e">Contains the event data of the event that triggered the method.</param> protected void Page_Load(object sender, EventArgs e) { //Counts the number of questions QuestionController Qsysmgr = new QuestionController(); int NumberOfQuestions = Qsysmgr.Question_Count(); //Checks to see if there is questions if (NumberOfQuestions == 0) { string error = "nodataquestions"; //Redirects to survey access page Response.Redirect("SurveyAccess.aspx?error=" + error); } else { //Obtains correct passcode from survey access page Utility utility = new Utility(); string passcode = Request.QueryString["passcode"]; SiteController sysmgr = new SiteController(); //uses the passcode to obtain site id int siteid = sysmgr.GetIdFromPasscode(passcode); //Checks if units exists for site if (UnitCheck(siteid) == 0 && passcode != null) { string error = "nounitsinsite"; Response.Redirect("SurveyAccess.aspx?error=" + error); } //changes the units drop down according to site that enters password UnitListODS.SelectParameters["siteId"].DefaultValue = siteid.ToString(); UnitListODS.Select(); //Checks if site exists if (siteid == 0) { //Redirects to survey access page Response.Redirect("SurveyAccess.aspx"); } //List of labels List <Label> QuestionsLabelList = new List <Label>(); QuestionsLabelList.Add(Q1Label); QuestionsLabelList.Add(Q1ALabel); QuestionsLabelList.Add(Q1BLabel); QuestionsLabelList.Add(Q1CLabel); QuestionsLabelList.Add(Q1DLabel); QuestionsLabelList.Add(Q1ELabel); QuestionsLabelList.Add(Q2Label); QuestionsLabelList.Add(Q3Label); QuestionsLabelList.Add(Q4Label); QuestionsLabelList.Add(Q5Label); //List of Question text List <string> QuestionTextList = new List <string>(); //List of Sub question starters List <string> SubQuestionCharList = new List <string>(); SubQuestionCharList.Add("a) "); SubQuestionCharList.Add("b) "); SubQuestionCharList.Add("c) "); SubQuestionCharList.Add("d) "); SubQuestionCharList.Add("e) "); // counter for questions int questioncharcounter = 1; //counter for subquestions int subquestioncharcounter = 0; //For loop for adding question text to labels for (int question = 1; question < QuestionsLabelList.Count(); question++) { //if statement which determines if label is subquestion or question if (QuestionTextList.Count() >= 1 && QuestionTextList.Count() < 6) { //Subquestion text if (QuestionTextList.Count == 1) { question = question - 1; } QuestionTextList.Add(SubQuestionCharList[subquestioncharcounter] + Qsysmgr.GetQuestionText(question).SubquestionText + ":"); subquestioncharcounter++; } //Question text else { QuestionTextList.Add(questioncharcounter.ToString() + ") " + Qsysmgr.GetQuestionText(question).QuestionText); questioncharcounter++; } } //If the amount of question texts are equal to the amount of question labels if (QuestionTextList.Count == QuestionsLabelList.Count()) { //adds text to labels int counter = 0; foreach (var Label in QuestionsLabelList) { Label.Text = QuestionTextList[counter]; counter++; } } } }
// Sites private void btnSitesSave_Click(object sender, EventArgs e) { // Valiations: if (tbSiteName.Text.Length == 0) { errorProvider.SetError(tbSiteName, "Must provide a value."); } else { errorProvider.SetError(tbSiteName, ""); } if (tbSiteLongtitude.Text.Length == 0) { errorProvider.SetError(tbSiteLongtitude, "Must provide a value."); } else { errorProvider.SetError(tbSiteLongtitude, ""); } if (tbSiteLatitude.Text.Length == 0) { errorProvider.SetError(tbSiteLatitude, "Must provide a value."); } else { errorProvider.SetError(tbSiteLatitude, ""); } if (cbSiteLongtitudeType.SelectedIndex == -1) { errorProvider.SetError(cbSiteLongtitudeType, "Must provide a value."); } else { errorProvider.SetError(cbSiteLongtitudeType, ""); } if (cbSiteLatitudeType.SelectedIndex == -1) { errorProvider.SetError(cbSiteLatitudeType, "Must provide a value."); } else { errorProvider.SetError(cbSiteLatitudeType, ""); } // Save new/changes: int id = 0; string name = tbSiteName.Text; float longtitude = float.Parse(tbSiteLongtitude.Text); float latitude = float.Parse(tbSiteLatitude.Text); Site.LongtitudeTypes longtitudeType = (Site.LongtitudeTypes)cbSiteLongtitudeType.SelectedIndex; Site.LatitudeTypes latitudeType = (Site.LatitudeTypes)cbSiteLatitudeType.SelectedIndex; if (emSites == EditingModes.Add) { id = 0; } else { id = currentSite.Id; } Site candidate = new Site(id, name, longtitude, longtitudeType, latitude, latitudeType);; if (emSites == EditingModes.Add) { id = SiteController.AddSite(candidate); } else { SiteController.EditSite(id, candidate); } // Reload data: lblStatus.Text = "Issuing sites saving command... "; currentSite = SiteController.GetSites(new List <int>() { id })[0]; LoadSiteData(currentSite); PrepareDataLists(); lblStatus.Text += "Complete."; }
public async Task <ServiceResult> Insert(Post s) { if (s == null || string.IsNullOrWhiteSpace(s.Name)) { return(ServiceResponse.Error("Invalid Post sent to server.")); } PostManager postManager = new PostManager(Globals.DBConnectionKey, Request.Headers?.Authorization?.Parameter); if (!string.IsNullOrWhiteSpace(s.UUID)) { var res = postManager.Get(s.UUID); if (res.Code == 200) { return(this.Update(s)); } } string authToken = this.GetAuthToken(Request); UserSession us = SessionManager.GetSession(authToken); if (us == null) { return(ServiceResponse.Error("You must be logged in to access this function.")); } //if (us.Captcha?.ToUpper() != s.Captcha?.ToUpper()) // return ServiceResponse.Error("Invalid code."); if (string.IsNullOrWhiteSpace(us.UserData)) { return(ServiceResponse.Error("Couldn't retrieve user data.")); } if (CurrentUser == null) { return(ServiceResponse.Error("You must be logged in to access this function.")); } s.Author = CurrentUser.Name; if (s.Status.EqualsIgnoreCase("publish") && (s.PublishDate == DateTime.MinValue || s.PublishDate == null)) { s.PublishDate = DateTime.UtcNow; } if (string.IsNullOrWhiteSpace(s.AccountUUID) || s.AccountUUID == SystemFlag.Default.Account) { s.AccountUUID = CurrentUser.AccountUUID; } if (string.IsNullOrWhiteSpace(s.CreatedBy)) { s.CreatedBy = CurrentUser.UUID; } if (s.DateCreated == DateTime.MinValue) { s.DateCreated = DateTime.UtcNow; } if (s.Sticky == true && CurrentUser.SiteAdmin != true) { s.Sticky = false; } if (s.PublishDate < DateTime.Now && CurrentUser.SiteAdmin == false) { return(ServiceResponse.Error("Publish date cannot be in the past.")); } var result = postManager.Insert(s); if (result.Code != 200) { return(result); } SiteController site = new SiteController(); await site.SendMessage(new GreenWerx.Models.Logging.EmailMessage() { Subject = "New Post by:" + CurrentUser.Name, Body = "Moderate new post by:" + CurrentUser.Name + "<br/>" + s.Name + "<br/>" + "link to post" + "<br/>" + s.Body + "<br/>" + "", DateCreated = DateTime.UtcNow, EmailTo = Globals.Application.AppSetting("SiteEmail"), EmailFrom = Globals.Application.AppSetting("SiteEmail") }); return(result); }
void PrepareDataLists() { // Populate all hard-coded combo-box values. cbOpticType.Items.Clear(); foreach (var item in Enum.GetValues(typeof(Optic.OpticTypes))) { cbOpticType.Items.Add(item); } cbScopeMountType.Items.Clear(); foreach (var item in Enum.GetValues(typeof(Scope.MountTypes))) { cbScopeMountType.Items.Add(item); } cbSiteLongtitudeType.Items.Clear(); foreach (var item in Enum.GetValues(typeof(Site.LongtitudeTypes))) { cbSiteLongtitudeType.Items.Add(item); } cbSiteLatitudeType.Items.Clear(); foreach (var item in Enum.GetValues(typeof(Site.LatitudeTypes))) { cbSiteLatitudeType.Items.Add(item); } // Query database for all values. listCameras = CameraController.GetCameras(); listCatalogues = CatalogueController.GetCatalogues(); listColorSpaces = ColorSpaceController.GetColorSpaces(); listFileFormats = FileFormatController.GetFileFormats(); listOptics = OpticsController.GetOptics(); listPhotographers = PhotographerController.GetPhotographers(); listScopes = ScopeController.GetScopes(); listSites = SiteController.GetSites(); // Populate list boxes. lbCameras.Items.Clear(); foreach (var item in listCameras) { lbCameras.Items.Add(item.Id + " " + item.LongName + " " + (item.MaxResolution.Width * item.MaxResolution.Height / 1000000).ToString() + "MP"); } lbCatalogues.Items.Clear(); foreach (var item in listCatalogues) { lbCatalogues.Items.Add(item.Id + " " + item.LongName); } lbColorSpaces.Items.Clear(); foreach (var item in listColorSpaces) { lbColorSpaces.Items.Add(item.Id + " " + item.Name); } lbFileFormats.Items.Clear(); foreach (var item in listFileFormats) { lbFileFormats.Items.Add(item.Id + " " + item.LongName); } lbOptics.Items.Clear(); foreach (var item in listOptics) { lbOptics.Items.Add(item.Id + " " + item.Value + " " + item.OpticType.ToString()); } lbPhotographers.Items.Clear(); foreach (var item in listPhotographers) { lbPhotographers.Items.Add(item.Id + " " + item.LastName + ", " + item.FirstName); } lbScopes.Items.Clear(); foreach (var item in listScopes) { lbScopes.Items.Add(item.Id + " " + item.Manufacturer + " " + item.Name); } lbSites.Items.Clear(); foreach (var item in listSites) { lbSites.Items.Add(item.Id + " " + item.Name); } // Populate specific database fields for every tab. cbCamerasColorSpaces.Items.Clear(); foreach (var item in listColorSpaces) { cbCamerasColorSpaces.Items.Add(item.Name); } }