public ActionResult Edit(int?id) { if (id == null) { return(RedirectToAction("PatientsList", new { QueueType = "OPD" })); } RegistrationData registrationData = new RegistrationData(); registrationData.BloodGroups = db.BloodGroups.ToList(); registrationData.Categories = db.Companies.ToList(); registrationData.IdentificationTypes = db.IdentificationTypes.ToList(); registrationData.MainCategories = db.CompanyTypes.ToList(); registrationData.MaritalStatus = db.MaritalStatus.ToList(); registrationData.Relationships = db.Relationships.ToList(); registrationData.Salutations = db.Salutations.ToList(); registrationData.Religions = db.Religions.ToList(); if (db.Patients.Find(id) == null) { return(RedirectToAction("PatientsList", new { QueueType = "OPD" })); } registrationData.Patient = db.Patients.Find(id); return(View("EditRegistration", registrationData)); }
public static string CreateToken(RegistrationData rd) { string obj = JsonSerializer.Serialize <RegistrationData>(rd); string token = SecurityMethods.GetSHA1Hash(obj); return(token); }
public Company CreateCompany(AddCompanyViewModel model, RegistrationData registrData, ContactInfo contactInfo) { string logoPath = String.Empty; if (model.Logo != null) { var path = Path.Combine( environment.WebRootPath, $"images\\{model.NameCompany}\\Logo"); fileUploadService.Upload(path, model.Logo.FileName, model.Logo); logoPath = $"images/{model.NameCompany}/Logo/{model.Logo.FileName}"; } Company company = new Company { NameCompany = model.NameCompany, LegalFormId = model.LegalFormId, PropertyTypeId = model.PropertyTypeId, INN = model.InnCompany, CodeOKPO = model.OkpoCompany, RegistrationNumberSocialFund = model.RegistrationNumberSocialFund, ResidencyId = model.ResidencyId, CountryId = model.CountryId, NumberOfEmployees = model.NumberOfEmployees, RegistrationDataId = registrData.Id, ContactInfoId = contactInfo.Id, Logo = logoPath }; context.Companies.Add(company); context.SaveChanges(); return(company); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { regData = (SerializationUtils.Deserialize(Request.Form["regData"]) ?? TempData["regData"] ?? new RegistrationData()) as RegistrationData; TryUpdateModel(regData); }
public Account RegisterNewAccount(RegistrationData registrationData) { long accountId = CreateNewAccount(registrationData); if (accountId == -1) { es.ThrowInfoException("Login {0} is already in use", registrationData.Login); } if (accountId == -2) { es.ThrowInfoException("Email {0} is already in use", registrationData.Email); } Account result = GetFullAccountByLogin(registrationData.Login); if (op.Value.Emails.SendRegisterEmailConfirmaion) { mas.SendRegisterConfirmation(result); } if (op.Value.Notifications.NotifyAdminAccountRegistered) { mas.NotifyAdminAccountRegistered(result); } return(result); }
public void sendRegistrationData(RegistrationData registrationData, MethodReferenceWithResponse responseHandler) { Response response = (Response)gameObject.AddComponent("Response"); Debug.Log("Sending registration request to Kii Cloud"); if (registrationData.password.Equals(registrationData.passwordConfirm)) { Debug.Log("Creating user builder"); KiiUser.Builder builder; builder = KiiUser.BuilderWithName(registrationData.username); builder.WithEmail(registrationData.email); KiiUser user = builder.Build(); try { Debug.Log("Registering..."); user.Register(registrationData.password); response.error = false; response.message = ""; Debug.Log("User registration successful"); } catch (Exception e) { response.error = true; response.message = e.Message; Debug.Log(e.Message); } } else { response.error = true; response.message = "Passwords don't match!"; } // Calling response handler: responseHandler(response); }
public async Task <IActionResult> Register([FromBody] RegistrationData registration_data) { string username = registration_data.Username, email = registration_data.Email, email_confirmation = registration_data.EmailConfirmation, password = registration_data.Password, password_confirmation = registration_data.PasswordConfirmation; // Check if all required parameters are present and if the user does not allready exits if (!ModelState.IsValid || email != email_confirmation || password != password_confirmation) { return(BadRequest()); } var existingAdmin = _context.Admin.FirstOrDefault(t => t.Username == username || t.Email == email); if (existingAdmin != null) { return(BadRequest()); } // Register the new user var hassedPassword = PasswordHasher.Hash(password); var newAdmin = new Admin() { Username = username, CreatedDate = DateTime.Now, EmailConfirmed = false, Email = email, PasswordHash = hassedPassword.PasswordHash, PasswordSalt = hassedPassword.PasswordSalt }; _context.Admin.Add(newAdmin); _context.SaveChanges(); newAdmin.EmailConfirmed = false; _context.Admin.Update(newAdmin); _context.SaveChanges(); // Update the securitystamp of the user await UserManager().UpdateSecurityStampAsync(newAdmin); // Send an email to inform the Admin var token = await UserManager().GenerateEmailConfirmationTokenAsync(newAdmin); var uri = Url.ActionContext.HttpContext.Request.Scheme + "://" + Url.ActionContext.HttpContext.Request.Host.Value + Url.Action("ConfirmEmailPage", new { userId = newAdmin.Id, token = token }); var subject = "Admin account created"; var to = new EmailAddress(newAdmin.Email); var plainTextContent = $"Hello {newAdmin.Username}\n\nYour Admin account has just been created. Click on the link to active you account\n{uri}"; var htmlContent = $"Hello {newAdmin.Username}<br /><br />Your Admin account has just been created. Click on the link to active you account<br /><a href='{uri}'>{uri}</a><br />"; var subsitutions = new Dictionary <string, string> { { ":subject", subject } }; await _mailService.SendEmailAsync(to, subject, plainTextContent, htmlContent, subsitutions); return(Ok(newAdmin)); }
/// <summary> /// Registers the device with the server. /// </summary> /// <param name="mac">Device's Mac address</param> /// <param name="sn">Device's Serial Number</param> /// <param name="model">Device's Model. Note that the model must be first created in the partner.syncpro.io portal</param> /// <param name="fwVersion">Device's FW version</param> /// <param name="partnerId">PartnerID - claim your at [email protected]</param> /// <returns> /// Returns the devices uuid and accessKey, which should be saved locally and used for every future API call. /// If fails, returns null. /// </returns> public static RegisterDeviceResponse RegisterDevice(string partnerId, string mac, string sn, string model, string fwVersion) { //First, assemble device registration data RegistrationData deviceRegData = new RegistrationData(mac, sn, model, fwVersion, partnerId); //Send registration request with device registration data as string HttpsClientResponse res = WebMethods.RegisterDevice(deviceRegData); if (res.Code == 422) { //Device is already registers throw new DeviceAlreadyRegisteredException("Error 422: Device is already registered"); } if (res.Code == 404) { //Could not find supported device throw new DeviceModelNotFoundException("Error 404: Could not find supported device"); } if (res.Code != 201) { Logging.Notice(@"SyncProApi \ RegisterDevice", res.Code.ToString() + ":" + res.ContentString); //Todo: Throw exception - Device already registered. return(null); } return(JsonConvert.DeserializeObject <RegisterDeviceResponse>(res.ContentString)); }
public void Test_RegisterForCourse_StudentIsProfessor() { MockDatabase <CourseSchedule> mockDB = new MockDatabase <CourseSchedule>(c => c.CourseSchedules); RegistrationData data = new RegistrationData(mockDB.Context); Student student = new Student { StudentSchedules = new List <StudentSchedule>(), PersonId = 5 }; CourseSchedule schedule = new CourseSchedule { Capacity = 3, StudentSchedules = new List <StudentSchedule> { new StudentSchedule(), new StudentSchedule() }, Schedule = new Schedule { StartTime = new TimeSpan(8, 0, 0), TimeBlocks = 1 }, ProfessorId = 5 }; mockDB.AddDataEntry(schedule); data.RegisterForCourse(student, schedule); Assert.Equal(schedule.StudentSchedules.ToList().Count, 2); mockDB.MockContext.Verify(m => m.SaveChanges(), Times.Never()); }
public PersonalInformationViewModel(RegistrationData data) { FirstName = data.FirstName; LastName = data.LastName; Centre = data.Centre; Email = data.Email; }
/// <summary> /// Creates a new instance of <see cref="OpenGenericFactoryRegistrationSource"/>. /// </summary> /// <param name="registrationData">Registration data.</param> /// <param name="activatorData">Activator data.</param> public OpenGenericFactoryRegistrationSource( RegistrationData registrationData, SimpleActivatorData activatorData) { _registrationData = registrationData ?? throw new ArgumentNullException(nameof(registrationData)); _activatorData = activatorData ?? throw new ArgumentNullException(nameof(activatorData)); }
public void SummaryPost_with_valid_information_registers_expected_admin() { // Given const int centreId = 7; const int jobGroupId = 1; const string email = "right@email"; const string professionalRegistrationNumber = "PRN1234"; var model = new SummaryViewModel { Terms = true, }; var data = new RegistrationData { FirstName = "First", LastName = "Name", Centre = centreId, JobGroup = jobGroupId, PasswordHash = "hash", Email = email, ProfessionalRegistrationNumber = professionalRegistrationNumber, HasProfessionalRegistrationNumber = true, }; controller.TempData.Set(data); A.CallTo(() => centresDataService.GetCentreAutoRegisterValues(centreId)).Returns((false, email)); A.CallTo(() => userDataService.GetAdminUserByEmailAddress(email)).Returns(null); A.CallTo(() => registrationService.RegisterCentreManager(A <AdminRegistrationModel> ._, A <int> ._, A <bool> ._)) .DoesNothing(); // When var result = controller.Summary(model); // Then A.CallTo( () => registrationService.RegisterCentreManager( A <AdminRegistrationModel> .That.Matches( a => a.FirstName == data.FirstName && a.LastName == data.LastName && a.Email == data.Email ! && a.Centre == data.Centre !.Value && a.PasswordHash == data.PasswordHash ! && a.Active && a.Approved && a.IsCentreAdmin && a.IsCentreManager && !a.IsContentManager && !a.ImportOnly && !a.IsContentCreator && !a.IsTrainer && !a.IsSupervisor && a.ProfessionalRegistrationNumber == professionalRegistrationNumber ), jobGroupId, true ) ) .MustHaveHappened(); result.Should().BeRedirectToActionResult().WithActionName("Confirmation"); }
public static AbstractUser CreateUser(RegistrationData regData) { AbstractUser user; switch (regData.RootType) { case RootEnum.Candidate: user = new CandidateUser(++Instance.LastId); Instance._specificUserLists[typeof(CandidateUser)].Add(user); break; case RootEnum.Manager: user = new ManagerUser(++Instance.LastId); Instance._specificUserLists[typeof(ManagerUser)].Add(user); break; case RootEnum.Interviewer: user = new InterviewerUser(++Instance.LastId); Instance._specificUserLists[typeof(InterviewerUser)].Add(user); break; case RootEnum.Admin: user = new AdminUser(++Instance.LastId); Instance._specificUserLists[typeof(AdminUser)].Add(user); break; default: throw new ArgumentOutOfRangeException(nameof(regData.RootType), regData.RootType, null); } user.Profile = regData.Profile; return(user); }
/// <summary> /// This method passes an Registration Data record to the API to insert the record into the Registration Table in the Event /// Registration database. /// </summary> /// <param name="data"> /// The data. /// </param> /// <returns> /// The <see cref="RegistrationData"/>. /// </returns> private RegistrationData AddRegistration(Form data) { this.logger.Trace($"Calling Interface.AddNewRegistration from public form"); Dictionary <string, string> detailList = new Dictionary <string, string>(); detailList.Add("School Name", data.SchoolName); detailList.Add("Grad Year", data.GradYear.ToString()); RegistrationData reg = new RegistrationData { FirstName = data.FirstName, LastName = data.LastName, Address = data.Address, City = data.City, State = data.State, Zipcode = data.Zipcode, EmailAddress = data.EmailAddress, Details = JsonConvert.SerializeObject(detailList), PhoneNumber = data.PhoneNumber, NumberAttending = data.NbrAttending, ProgramEventGuid = Guid.Parse(data.SelectedEvent), DuplicateCheck = false }; // todo: change this to return a status flag, message and data // returns a registration data record with ID, GUID, var response = Interface.AddNewRegistration(EventRegistrationId, reg); // RegistrationData newReg = Interface.AddNewRegistration(EventRegistrationId, reg); // ADD CODE TO CHECK FOR A DUP ERROR //if (!good reponse) // ?SEt error return(response); }
public UserViewData Register([FromBody] RegistrationData registration_data) { string username = registration_data.Username, email = registration_data.Email, email_confirmation = registration_data.EmailConfirmation; if (username != null && username != "" && email != null && email != "" && email == email_confirmation) { var item = _context.User.FirstOrDefault(t => t.Username == username || t.Email == email); if (item == null) { var new_password_text = PasswordHasher.RandomPassword; var new_password = PasswordHasher.Hash(new_password_text); item = new User() { Id = _context.User.Max(i => i.Id) + 1, Username = username, Email = email, PasswordHash = new_password.PasswordHash, PasswordSalt = new_password.PasswordSalt }; var apiKey = StaticMailer._mailOptions.MailApiToken; var client = new SendGridClient(apiKey); var from = new EmailAddress(StaticMailer._mailOptions.MailFrom); var subject = "User account created with temporary password."; var to = new EmailAddress(item.Email); var plainTextContent = $"Your User temporary password has set. Your username and password combination is \n\nUsername: {item.Username}\nPassword: {new_password_text}\n"; var htmlContent = $"Your User temporary password has set. Your username and password combination is <br />Username: {item.Username}<br />Password: {new_password_text}<br />"; var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); var response = client.SendEmailAsync(msg).Result; _context.User.Add(item); _context.SaveChanges(); return(UserViewData.FromUser(item)); } } throw new Exception("Cannot register."); }
public void Test_ScheduleCourse_ProfessorIsTeachingCourseAtSameTime() { MockDatabase <CourseSchedule> mockDB = new MockDatabase <CourseSchedule>(c => c.CourseSchedules); RegistrationData data = new RegistrationData(mockDB.Context); CourseSchedule existingCourseSchedule = new CourseSchedule { Schedule = new Schedule { StartTime = new TimeSpan(8, 0, 0), TimeBlocks = 2 } }; Person professor = new Person { PersonId = 5, CourseSchedules = new List <CourseSchedule> { existingCourseSchedule } }; Schedule schedule = new Schedule { StartTime = new TimeSpan(9, 30, 0), TimeBlocks = 1 }; Course course = new Course { CourseSchedules = new List <CourseSchedule> { existingCourseSchedule } }; data.ScheduleCourse(course, schedule, professor, 3); mockDB.MockSet.Verify(m => m.Add(It.IsAny <CourseSchedule>()), Times.Never()); mockDB.MockContext.Verify(m => m.SaveChanges(), Times.Never()); }
public void Test_GetNumberOfStudentsInCourse() { MockDatabase <CourseSchedule> mockDB = new MockDatabase <CourseSchedule>(c => c.CourseSchedules); RegistrationData data = new RegistrationData(mockDB.Context); CourseSchedule schedule = new CourseSchedule { Capacity = 3, StudentSchedules = new List <StudentSchedule> { new StudentSchedule { Enrolled = true }, new StudentSchedule { Enrolled = false }, new StudentSchedule { Enrolled = true } } }; mockDB.AddDataEntry(schedule); int expected = 2; int actual = data.GetNumberOfStudentsInCourse(schedule); Assert.Equal(expected, actual); }
private void SetAdminRegistrationData(int centreId) { var adminRegistrationData = new RegistrationData(centreId); TempData.Clear(); TempData.Set(adminRegistrationData); }
private static IRegistrationData GetRegistrationData(RegulationType regulationType) { Console.WriteLine("Enter username"); var username = Console.ReadLine(); Console.WriteLine("Enter password"); var password = Console.ReadLine(); Console.WriteLine("Enter email"); var email = Console.ReadLine(); var regularData = new RegistrationData() { Username = username, Password = password, Email = email }; switch (regulationType) { case RegulationType.Regular: return(regularData); case RegulationType.Danish: return(GetDanishData(regularData)); case RegulationType.Polish: return(GetPolishData(regularData)); default: throw new NotImplementedException("Not implemented regulation type"); } }
public async Task PerformAnnouncement(RegistrationToken token) { var config = _configuration.Value; var registrationData = new RegistrationData() { EndpointPort = config.OwnHttpPort, RegistrationDate = DateTime.UtcNow, SessionId = token.SessionId, UserId = token.UserId, Username = token.Username }; var registrationJson = JsonConvert.SerializeObject(registrationData); using (var httpClient = new HttpClient()) { var request = new HttpRequestMessage(HttpMethod.Post, config.HubUrl + "/Registrations/AnnounceRegistration") { Content = new StringContent(registrationJson, Encoding.UTF8, "application/json") }; var response = await httpClient.SendAsync(request); if (!response.IsSuccessStatusCode) { System.Diagnostics.Debug.WriteLine("Non-Successful status code for registration"); } } }
public void sendRegistrationData(RegistrationData registrationData, MethodReferenceWithResponse responseHandler) { Response response = (Response)gameObject.AddComponent<Response>(); bool inHandler = true; Debug.Log("Attempting registration..."); if (registrationData.password.Equals (registrationData.passwordConfirm)) { Debug.Log("Creating user builder"); KiiUser.Builder builder; builder = KiiUser.BuilderWithName (registrationData.username); builder.WithEmail(registrationData.email); KiiUser user = builder.Build(); Debug.Log("Attempting signup..."); user.Register(registrationData.password, (KiiUser user2, Exception e) => { if (e != null) { response.error = true; response.message = "Signup failed: " + e.ToString(); inHandler = false; Debug.Log ("Signup failed: " + e.ToString()); } else { response.error = false; response.message = ""; inHandler = false; Debug.Log ("Signup succeeded"); } }); } else { response.error = true; response.message = "Passwords don't match!"; inHandler = false; } // Calling response handler: while(inHandler) {} responseHandler(response); }
private void txtCredit_TextChanged(object sender, EventArgs e) { TextBox txtCredit = (TextBox)sender; uint chknum; if (!uint.TryParse(txtCredit.Text, out chknum)) { lblAlertAdvisor.Text = "กรุณาระบุ จำนวนหน่วยกิตเป็นตัวเลขเท่านั้น"; } else { lblAlertAdvisor.Text = ""; int course_index = Convert.ToInt16(txtCredit.ID.Substring(6)); List <RegistrationData> ApproveRegisData = new List <RegistrationData>(); RegistrationData Select_Course = studentRegisData[course_index - 1]; if (Session["ApproveRegis"] != null) { ApproveRegisData = (List <RegistrationData>)Session["ApproveRegis"]; foreach (RegistrationData data in ApproveRegisData) { if (Select_Course.Academic_Year == data.Academic_Year && Select_Course.Semester == data.Semester && Select_Course.Course_Code == data.Course_Code && Select_Course.Sec_No == data.Sec_No && Select_Course.SubSec_No == data.SubSec_No) { data.Credit = Convert.ToUInt16(txtCredit.Text); } } Session["ApproveRegis"] = ApproveRegisData; } } }
public void Register_Returns_BadRequest( string email, string password, string firstName, string lastName) { // Arrange var loginService = Substitute.For <ILoginService>(); var registrationService = Substitute.For <IRegistrationService>(); var authController = new AuthController(loginService, registrationService); var registrationData = new RegistrationData() { Email = email, Password = password, FirstName = firstName, LastName = lastName }; // Act var actionResult = authController.Register(registrationData); // Assert var isBadRequest = actionResult is BadRequestObjectResult; isBadRequest.ShouldBeTrue(); }
public ActionResult UserProfile(UserProfileModel model) { // Set States on the model. We need to do this because only the value selected // in the DropDownList is posted back, not the whole list of states model.States = GetStatesFromDB(); model.Roles = GetRolesFromDB(); model.FacilityList = GetFacilityListFromDB(); // In case everything is fine - i.e. "FirstName", "LastName" and "State" are entered/selected, // redirect a user to the "ViewProfile" page, and pass the user object along via Session if (ModelState.IsValid) { // get ready to call service layer to do some work // pedestrain way RegistrationData regData1 = new RegistrationData { Name = model.GetName, State = model.State }; // kool kidz sez, yuz AutoMapper 5. Mapper.Initialize(cfg => cfg.CreateMap <UserProfileModel, RegistrationData>()); RegistrationData regData2 = Mapper.Map <RegistrationData>(model); // Call the service bool result = DoAllTheThings.RegisterUser(regData2); // Show results Session["UserProfileModel"] = model; return(RedirectToAction("ViewProfile")); } // Something is not right - re-render the registration page, keeping user-entered data // and display validation errors return(View(model)); }
public void ChangeStatus(RegistrationData model) { try { Registration obj = (from a in dbRegistration.Table where a.Id == model.Id select a).FirstOrDefault <Registration>(); if (obj.Status == true) { obj.Status = false; } else { obj.Status = true; } dbRegistration.Update(obj); dbRegistration.SaveChanges(); } catch (Exception) { throw; } }
private static void CreateHeader(DateTime start, DateTime end) { RegistrationData registrationData = GetRegistrationData(); ColumnText column1 = Document.GetNewColumn(50, Document.Height - 17, 100, 100); Document.AddParagraph(Resources.TXT_GV_212, column1, Document.GetLargeFont(true)); //VOSA Logo var rawData = ImageHelper.LoadFromResourcesAsByteArray("Vosa"); Document.AddImage(rawData, 100, 45, Document.Width - 115, Document.Height - 60); var column2 = new ColumnText(Document.ContentByte); column2.SetSimpleColumn(50, Document.Height - 50, 500, 100); Document.AddParagraph(Resources.TXT_REGISTER_OF_TACHOGRAPH_PLAQUES_ISSUES, column2, Document.GetLargeFont(true)); Document.DrawLine(50, Document.Top - 38, 540, Document.Top - 38); ColumnText column3 = Document.GetNewColumn(50, Document.Height - 80, 200, 100); Document.AddParagraph(Resources.TXT_NAME_OF_TACHOGRAPH_CENTER, column3); Document.DrawLine(200, Document.Top - 63, 540, Document.Top - 63); //Tachograph Centre Name ColumnText centreNameColumn = Document.GetNewColumn(210, Document.Height - 80, 600, 100); Document.AddSmallParagraph(GetCompanyName(registrationData), centreNameColumn); ColumnText column4 = Document.GetNewColumn(50, Document.Height - 105, 220, 100); Document.AddParagraph(Resources.TXT_SEAL_OF_TACHOGRAPH_CENTER, column4); Document.DrawLine(220, Document.Top - 87, 320, Document.Top - 87); //Seal number ColumnText sealNumberColumn = Document.GetNewColumn(230, Document.Height - 104, 300, 100); Document.AddSmallParagraph(registrationData.SealNumber, sealNumberColumn); ColumnText column5 = Document.GetNewColumn(50, Document.Height - 130, 435, 100); Document.AddParagraph(Resources.TXT_REGISTER_BETWEEN, column5); Document.DrawLine(145, Document.Top - 111, 220, Document.Top - 111); //Register Start Date ColumnText startColumn = Document.GetNewColumn(145, Document.Height - 128, 220, 100); Document.AddSmallParagraph(start.ToString(Constants.DateFormat), startColumn); ColumnText column6 = Document.GetNewColumn(230, Document.Height - 130, 435, 100); Document.AddParagraph(Resources.TXT_AND, column6); Document.DrawLine(258, Document.Top - 111, 344, Document.Top - 111); //Register end date ColumnText endColumn = Document.GetNewColumn(258, Document.Height - 128, 350, 100); Document.AddSmallParagraph(end.ToString(Constants.DateFormat), endColumn); }
public LearnerInformationViewModel(RegistrationData data, bool isSelfRegistration) { JobGroup = data.JobGroup; ProfessionalRegistrationNumber = data.ProfessionalRegistrationNumber; HasProfessionalRegistrationNumber = data.HasProfessionalRegistrationNumber; IsSelfRegistrationOrEdit = isSelfRegistration; }
public void sendRegistrationData(RegistrationData registrationData, MethodReferenceWithResponse responseHandler) { Response response = (Response)gameObject.AddComponent<Response>(); Debug.Log("Sending registration request to Kii Cloud"); if (registrationData.password.Equals (registrationData.passwordConfirm)) { Debug.Log("Creating user builder"); KiiUser.Builder builder; builder = KiiUser.BuilderWithName (registrationData.username); builder.WithEmail(registrationData.email); KiiUser user = builder.Build(); try { Debug.Log("Registering..."); user.Register (registrationData.password); response.error = false; response.message = ""; Debug.Log ("User registration successful"); } catch (Exception e) { response.error = true; response.message = e.Message; Debug.Log (e.Message); } } else { response.error = true; response.message = "Passwords don't match!"; } // Calling response handler: responseHandler(response); }
public async Task StoreRegistrationAsync(RegistrationData registrationData) { if (registrationData is null) { throw new ArgumentNullException(nameof(registrationData)); } await InitAsync(); var currentRegistrations = await GetCurrentRegistrationsAsync(); if (currentRegistrations.Any(reg => reg.SessionId == registrationData.SessionId)) { return; } var matchingRegistrations = currentRegistrations.Where(reg => reg.UserId == registrationData.UserId).ToArray(); foreach (var registration in matchingRegistrations) { currentRegistrations.Remove(registration); } currentRegistrations.Add(registrationData); var updatedRegistrationsJson = JsonConvert.SerializeObject(currentRegistrations); await _redisDb.StringSetAsync(RegistrationsKey, updatedRegistrationsJson); }
public void SummaryPost_with_admin_registration_not_allowed_throws_error( bool autoRegistered, string autoRegisterManagerEmail, string userEmail ) { // Given const int centreId = 7; var model = new SummaryViewModel { Terms = true, }; var data = new RegistrationData { Centre = centreId, Email = userEmail }; controller.TempData.Set(data); A.CallTo(() => centresDataService.GetCentreName(centreId)).Returns("My centre"); A.CallTo(() => centresDataService.GetCentreAutoRegisterValues(centreId)) .Returns((autoRegistered, autoRegisterManagerEmail)); // When var result = controller.Summary(model); // Then result.Should().BeStatusCodeResult().WithStatusCode(500); }
public void PersonalInformationPost_with_correct_unique_email_is_allowed() { // Given const int centreId = 7; const string email = "right@email"; var model = new PersonalInformationViewModel { FirstName = "Test", LastName = "User", Centre = centreId, Email = email, }; var data = new RegistrationData(centreId); controller.TempData.Set(data); A.CallTo(() => centresDataService.GetCentreAutoRegisterValues(centreId)).Returns((false, email)); A.CallTo(() => userDataService.GetAdminUserByEmailAddress(email)).Returns(null); // When var result = controller.PersonalInformation(model); // Then A.CallTo(() => centresDataService.GetCentreAutoRegisterValues(centreId)).MustHaveHappened(1, Times.Exactly); A.CallTo(() => userDataService.GetAdminUserByEmailAddress(email)).MustHaveHappened(1, Times.Exactly); result.Should().BeRedirectToActionResult().WithActionName("LearnerInformation"); }
public void PersonalInformationPost_with_email_already_in_use_fails_validation() { // Given const int centreId = 7; const string email = "right@email"; var model = new PersonalInformationViewModel { FirstName = "Test", LastName = "User", Centre = centreId, Email = email, }; var data = new RegistrationData(centreId); controller.TempData.Set(data); A.CallTo(() => centresDataService.GetCentreAutoRegisterValues(centreId)).Returns((false, email)); A.CallTo(() => userDataService.GetAdminUserByEmailAddress(email)).Returns(new AdminUser()); // When var result = controller.PersonalInformation(model); // Then A.CallTo(() => centresDataService.GetCentreAutoRegisterValues(centreId)).MustHaveHappened(1, Times.Exactly); A.CallTo(() => userDataService.GetAdminUserByEmailAddress(email)).MustHaveHappened(1, Times.Exactly); controller.ModelState[nameof(PersonalInformationViewModel.Email)].ValidationState.Should() .Be(ModelValidationState.Invalid); result.Should().BeViewResult().WithDefaultViewName(); }
public void FromAndToMustDiffer() { var ad = new LightweightAdapterActivatorData(new TypedService(typeof(object)), (c, p, t) => new object()); var rd = new RegistrationData(new TypedService(typeof(object))); Assert.Throws<ArgumentException>(() => new LightweightAdapterRegistrationSource(rd, ad)); }
public AdaptingFromOneServiceToAnother() { var ad = new LightweightAdapterActivatorData(_from, (c, p, t) => new object()); var rd = new RegistrationData(_to); _subject = new LightweightAdapterRegistrationSource(rd, ad); _adaptedTo = _subject.RegistrationsFor(_to, s => _adaptedFrom); }
/// <summary> /// http://tent.io/docs/app-auth /// /// http://stackoverflow.com/questions/10654383/wcf-post-json-object /// /// http://blog.manglar.com/json-post-request/ /// </summary> /// <param name="server"></param> /// <param name="timeout"></param> /// <returns></returns> public static string RegisterApplication(string server, RegistrationData registrationData, int timeout = DEFAULT_TIMEOUT) { try { #region Request HttpWebRequest request = HttpWebRequest.Create(string.Format("{0}/apps", server)) as HttpWebRequest; request.Method = WebRequestMethods.Http.Post; request.Timeout = timeout; request.ContentType = TENT_CONTENT_TYPE; request.Accept = TENT_CONTENT_TYPE; DataContractJsonSerializer requestJsonSerializer = new DataContractJsonSerializer(typeof(RegistrationData)); StreamWriter writer = new StreamWriter(request.GetRequestStream()); requestJsonSerializer.WriteObject(writer.BaseStream, registrationData); writer.Close(); #endregion #region Response using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { if (response.StatusCode != HttpStatusCode.OK) { throw new Exception(String.Format( "Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription)); } else { DataContractJsonSerializer responseJsonSerializer = new DataContractJsonSerializer(typeof(RegistrationData)); RegistrationData jsonResponse = responseJsonSerializer.ReadObject(response.GetResponseStream()) as RegistrationData; // Testing - this whole thing isn't done yet. We're through step one, but now we need to keep slingin shit back and forth // until the OAuth is completed. MemoryStream ms = new MemoryStream(); responseJsonSerializer.WriteObject(ms, jsonResponse); ms.Position = 0; StreamReader sr = new StreamReader(ms); return sr.ReadToEnd(); } } #endregion } catch (Exception ex) { throw ex; } }
public OpenGenericRegistrationSource( RegistrationData registrationData, ReflectionActivatorData activatorData) { if (registrationData == null) throw new ArgumentNullException("registrationData"); if (activatorData == null) throw new ArgumentNullException("activatorData"); OpenGenericServiceBinder.EnforceBindable(activatorData.ImplementationType, registrationData.Services); _registrationData = registrationData; _activatorData = activatorData; }
public LightweightAdapterRegistrationSource( RegistrationData registrationData, LightweightAdapterActivatorData activatorData) { if (registrationData == null) throw new ArgumentNullException(nameof(registrationData)); if (activatorData == null) throw new ArgumentNullException(nameof(activatorData)); _registrationData = registrationData; _activatorData = activatorData; if (registrationData.Services.Contains(activatorData.FromService)) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, LightweightAdapterRegistrationSourceResources.FromAndToMustDiffer, activatorData.FromService)); }
private static void ScanAssembly(IComponentRegistry componentRegistry, Assembly assembly) { var types = assembly.GetTypes() .Where(type => (type.IsClass && !type.IsAbstract) && (!type.IsGenericTypeDefinition && !type.IsSubclassOf(typeof(Delegate)))) .ToArray(); foreach (var type in types) { var implementedInterfaces = GetImplementedInterfaces(type); if (!implementedInterfaces.Any()) continue; if (!HasMarkerAttribute(type)) { var interfaceName = "I" + type.Name; if (implementedInterfaces.All(interfaceType => interfaceType.Name != interfaceName)) continue; } var typedService = new TypedService(type); var data = new RegistrationData(typedService); data.AddServices( implementedInterfaces.Select( t => { if (t.FullName == null) { return new TypedService(t.GetGenericTypeDefinition()); } return new TypedService(t); }).ToArray()); if (IsSingleInstancing(typedService.ServiceType)) { data.Sharing = InstanceSharing.Shared; data.Lifetime = new RootScopeLifetime(); } else if (IsInstancingPerLifetimeScope(typedService.ServiceType)) { data.Sharing = InstanceSharing.Shared; data.Lifetime = new MatchingScopeLifetime(LifetimeScopeTags.RequestScope); } var registration = RegistrationBuilder.CreateRegistration( Guid.NewGuid(), data, new ConcreteReflectionActivatorData(typedService.ServiceType).Activator, data.Services); componentRegistry.Register(registration); } }
public LightweightAdapterRegistrationSource( RegistrationData registrationData, LightweightAdapterActivatorData activatorData) { if (registrationData == null) throw new ArgumentNullException("registrationData"); if (activatorData == null) throw new ArgumentNullException("activatorData"); _registrationData = registrationData; _activatorData = activatorData; if (registrationData.Services.Contains(activatorData.FromService)) throw new ArgumentException(string.Format( "The service {0} cannot be both the adapter's from and to parameters - these must differ.", activatorData.FromService)); }
public OpenGenericDecoratorRegistrationSource( RegistrationData registrationData, OpenGenericDecoratorActivatorData activatorData) { if (registrationData == null) throw new ArgumentNullException("registrationData"); if (activatorData == null) throw new ArgumentNullException("activatorData"); OpenGenericServiceBinder.EnforceBindable(activatorData.ImplementationType, registrationData.Services); if (registrationData.Services.Contains((Service)activatorData.FromService)) throw new ArgumentException(string.Format( "The service {0} cannot be both the adapter's from and to parameters - these must differ.", activatorData.FromService)); _registrationData = registrationData; _activatorData = activatorData; }
public OpenGenericDecoratorRegistrationSource( RegistrationData registrationData, OpenGenericDecoratorActivatorData activatorData) { if (registrationData == null) throw new ArgumentNullException("registrationData"); if (activatorData == null) throw new ArgumentNullException("activatorData"); OpenGenericServiceBinder.EnforceBindable(activatorData.ImplementationType, registrationData.Services); if (registrationData.Services.Contains((Service)activatorData.FromService)) throw new ArgumentException(string.Format( CultureInfo.CurrentCulture, OpenGenericDecoratorRegistrationSourceResources.FromAndToMustDiffer, activatorData.FromService)); _registrationData = registrationData; _activatorData = activatorData; }
public AssemblyRegistrar( CommandLineParser parser ) { m_parser = parser; m_regData = new RegistrationData( parser.RegistrationPath, parser.IsProtectOnly ); }
public void Notify(RegistrationData registrationData) { }
protected void btnSave_OnClick(object sender, EventArgs e) { Page.Validate(); if (Page.IsValid) { // step 1: create account using registration model (single user role) int curr_default_role_id = Convert.ToInt32(ddlUserRoles.SelectedValue); RegistrationData data = new RegistrationData(); data.scope_id = 1; data.invite_code = ""; data.space_code = ""; data.campaign_code = ""; data.mobile_number = ""; data.email = txtEmail.Text; data.username = txtUserName.Text; data.password = ""; data.firstname = txtFirstName.Text; data.lastname = txtLastName.Text; data.degrees = ""; data.position = ""; data.agency = ""; data.division = ""; data.address = ""; data.address2 = ""; data.city = ""; data.state = ""; data.postal_code = ""; data.work_phone = ""; data.first_event = ""; data.dob = ""; data.gender = ""; data.ethnicity = ""; data.race = ""; data.profession = ""; data.employment_setting = ""; data.employment_location = ""; data.employment_sites = ""; data.registration_type = "manager"; data.registration_notes = ""; data.default_role_id = curr_default_role_id; data.browser = ""; data.platform = ""; qPtl_User user = new qPtl_User(); user = UserFunctions.RegisterNewUser(data); user.RegistrationNotes = txtRegistrationNotes.Text; user.RegistrationType = ddlRegistrationTypes.SelectedValue; user.Update(); // process functional roles if (plhFunctionalRoles.Visible == true) { string sqlCode = string.Empty; string returnMessage = string.Empty; qDbs_SQLcode sql = new qDbs_SQLcode(); // first delete all existing roles sqlCode = "DELETE FROM qLrn_UserFunctionalRoles WHERE UserID = " + user.UserID; sql.ExecuteSQL(sqlCode); // create records for all new roles int n; string selectedItems = string.Empty; n = 0; foreach (ListItem item in cblFunctionalRoles.Items) { if (item.Selected) { sqlCode = "INSERT INTO qLrn_UserFunctionalRoles (UserID, FunctionalRoleID)"; sqlCode += " VALUES (" + user.UserID + "," + item.Value + ")"; sql.ExecuteSQL(sqlCode); if (n > 0) { selectedItems += "," + item.Value; } else { selectedItems += item.Value; } n++; } } int daysBetweenTrainings = 0; if (!String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["Learning_DaysBetweenTrainings"])) daysBetweenTrainings = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Learning_DaysBetweenTrainings"]); int daysTillUnavailable = 5000; DateTime seedDate = DateTime.Now; string trainingMode = "open"; string surveyRequired = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Learning_SurveyRequired"]); qLrn_UserTraining.manageUserTrainings(user.UserID, daysBetweenTrainings, daysTillUnavailable, trainingMode, "add", 0, seedDate, surveyRequired); // redirect to new user tools page Response.Redirect("member-profile.aspx?userID=" + user.UserID); } } }
public IEnumerable<IComponentRegistration> RegistrationsFor(Service service, Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor) { var serviceWithType = service as IServiceWithType; if (serviceWithType != null) { object instance; if (_core.TryResolve(serviceWithType.ServiceType, out instance)) { var data = new RegistrationData(service) { Sharing = InstanceSharing.Shared, Lifetime = new RootScopeLifetime() }; yield return RegistrationBuilder.CreateRegistration(Guid.NewGuid(), data, new ProvidedInstanceActivator(instance), new[] { service }); } } }
protected virtual void SetLifetimeScope(DependencyLifecycle lifecycle, RegistrationData data) { if (lifecycle == DependencyLifecycle.SingleInstance) { data.Sharing = InstanceSharing.Shared; data.Lifetime = new RootScopeLifetime(); return; } if (lifecycle == DependencyLifecycle.TransientInstance) { data.Sharing = InstanceSharing.None; data.Lifetime = new CurrentScopeLifetime(); return; } Should.MethodBeSupported(false, "SetLifetimeScope(DependencyLifecycle dependencyLifecycle, IRegistrationBuilder<object, ConcreteReflectionActivatorData, SingleRegistrationStyle> builder)"); }