protected void btnUpdate_Click( object sender, EventArgs e ) { if ( Page.IsValid && person != null) { PersonService personService = new PersonService(); person.GivenName = txtFirstName.Text; person.NickName = txtNickName.Text; person.LastName = txtLastName.Text; if ( person.Guid == Guid.Empty ) personService.Add( person, CurrentPersonId ); personService.Save( person, CurrentPersonId ); } }
protected void Page_Load( object sender, EventArgs e ) { person = CurrentPage.GetCurrentContext( "Rock.Model.Person" ) as Rock.Model.Person; if (person == null) { PersonService personService = new PersonService(); person = new Person(); personService.Add( person, CurrentPersonId ); } if ( !IsPostBack ) { txtFirstName.Text = person.FirstName; txtNickName.Text = person.NickName; txtLastName.Text = person.LastName; } }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); var userLoginService = new UserLoginService( rockContext ); var userLogin = userLoginService.Queryable().Where( a => a.ApiKey == tbKey.Text ).FirstOrDefault(); if ( userLogin != null && userLogin.PersonId != int.Parse( hfRestUserId.Value ) ) { // this key already exists in the database. Show the error and get out of here. nbWarningMessage.Text = "This API Key already exists. Please enter a different one, or generate one by clicking the 'Generate Key' button below. "; nbWarningMessage.Visible = true; return; } rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var changes = new List<string>(); var restUser = new Person(); if ( int.Parse( hfRestUserId.Value ) != 0 ) { restUser = personService.Get( int.Parse( hfRestUserId.Value ) ); } else { personService.Add( restUser ); rockContext.SaveChanges(); restUser.Aliases.Add( new PersonAlias { AliasPersonId = restUser.Id, AliasPersonGuid = restUser.Guid } ); } // the rest user name gets saved as the last name on a person History.EvaluateChange( changes, "Last Name", restUser.LastName, tbName.Text ); restUser.LastName = tbName.Text; restUser.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid() ).Id; if ( cbActive.Checked ) { restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id; } else { restUser.RecordStatusValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid() ).Id; } if ( restUser.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), restUser.Id, changes ); } } } // the description gets saved as a system note for the person var noteType = new NoteTypeService( rockContext ) .Get( Rock.SystemGuid.NoteType.PERSON_TIMELINE.AsGuid() ); var noteService = new NoteService( rockContext ); var note = noteService.Get( noteType.Id, restUser.Id ).FirstOrDefault(); if ( note == null ) { note = new Note(); noteService.Add( note ); } note.NoteTypeId = noteType.Id; note.EntityId = restUser.Id; note.Text = tbDescription.Text; rockContext.SaveChanges(); // the key gets saved in the api key field of a user login (which you have to create if needed) var entityType = new EntityTypeService( rockContext ) .Get( "Rock.Security.Authentication.Database" ); userLogin = userLoginService.GetByPersonId( restUser.Id ).FirstOrDefault(); if ( userLogin == null ) { userLogin = new UserLogin(); userLoginService.Add( userLogin ); } if ( string.IsNullOrWhiteSpace( userLogin.UserName ) ) { userLogin.UserName = Guid.NewGuid().ToString(); } userLogin.IsConfirmed = true; userLogin.ApiKey = tbKey.Text; userLogin.PersonId = restUser.Id; userLogin.EntityTypeId = entityType.Id; rockContext.SaveChanges(); } ); NavigateToParentPage(); }
/// <summary> /// Handles the Click event of the lbSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbSave_Click( object sender, EventArgs e ) { var rockContext = new RockContext(); rockContext.WrapTransaction( () => { var personService = new PersonService( rockContext ); var changes = new List<string>(); Person business = null; if ( int.Parse( hfBusinessId.Value ) != 0 ) { business = personService.Get( int.Parse( hfBusinessId.Value ) ); } if ( business == null ) { business = new Person(); personService.Add( business ); } // Business Name History.EvaluateChange( changes, "Last Name", business.LastName, tbBusinessName.Text ); business.LastName = tbBusinessName.Text; // Phone Number var businessPhoneTypeId = new DefinedValueService( rockContext ).GetByGuid( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK ) ).Id; string oldPhoneNumber = string.Empty; string newPhoneNumber = string.Empty; var phoneNumber = business.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == businessPhoneTypeId ); if ( phoneNumber != null ) { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } if ( !string.IsNullOrWhiteSpace( PhoneNumber.CleanNumber( pnbPhone.Number ) ) ) { if ( phoneNumber == null ) { phoneNumber = new PhoneNumber { NumberTypeValueId = businessPhoneTypeId }; business.PhoneNumbers.Add( phoneNumber ); } phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode ); phoneNumber.Number = PhoneNumber.CleanNumber( pnbPhone.Number ); phoneNumber.IsMessagingEnabled = cbSms.Checked; phoneNumber.IsUnlisted = cbUnlisted.Checked; newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } else { if ( phoneNumber != null ) { business.PhoneNumbers.Remove( phoneNumber ); new PhoneNumberService( rockContext ).Delete( phoneNumber ); } } History.EvaluateChange( changes, string.Format( "{0} Phone", DefinedValueCache.GetName( businessPhoneTypeId ) ), oldPhoneNumber, newPhoneNumber ); // Record Type - this is always "business". it will never change. business.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id; // Record Status int? newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); History.EvaluateChange( changes, "Record Status", DefinedValueCache.GetName( business.RecordStatusValueId ), DefinedValueCache.GetName( newRecordStatusId ) ); business.RecordStatusValueId = newRecordStatusId; // Record Status Reason int? newRecordStatusReasonId = null; if ( business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE ) ).Id ) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange( changes, "Record Status Reason", DefinedValueCache.GetName( business.RecordStatusReasonValueId ), DefinedValueCache.GetName( newRecordStatusReasonId ) ); business.RecordStatusReasonValueId = newRecordStatusReasonId; // Email business.IsEmailActive = true; History.EvaluateChange( changes, "Email", business.Email, tbEmail.Text ); business.Email = tbEmail.Text.Trim(); var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum<EmailPreference>(); History.EvaluateChange( changes, "EmailPreference", business.EmailPreference, newEmailPreference ); business.EmailPreference = newEmailPreference; if ( business.IsValid ) { if ( rockContext.SaveChanges() > 0 ) { if ( changes.Any() ) { HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), business.Id, changes ); } } } // Add/Update Family Group var familyGroupType = GroupTypeCache.GetFamilyGroupType(); int adultRoleId = familyGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var adultFamilyMember = UpdateGroupMember( business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext ); business.GivingGroup = adultFamilyMember.Group; // Add/Update Known Relationship Group Type var knownRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() ); int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var knownRelationshipOwner = UpdateGroupMember( business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext ); // Add/Update Implied Relationship Group Type var impliedRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS.AsGuid() ); int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid() ) ) .Select( r => r.Id ) .FirstOrDefault(); var impliedRelationshipOwner = UpdateGroupMember( business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext ); rockContext.SaveChanges(); // Every business should have an alias record with same id. If it's missing, create it if ( !business.Aliases.Any( a => a.AliasPersonId == business.Id ) ) { // refetch the business to make sure we have an Id business = personService.Get( business.Id ); if ( business != null ) { business.Aliases.Add( new PersonAlias { AliasPersonId = business.Id, AliasPersonGuid = business.Guid } ); rockContext.SaveChanges(); } } // Location int workLocationTypeId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK ).Id; var groupLocationService = new GroupLocationService( rockContext ); var workLocation = groupLocationService.Queryable( "Location" ) .Where( gl => gl.GroupId == adultFamilyMember.Group.Id && gl.GroupLocationTypeValueId == workLocationTypeId ) .FirstOrDefault(); if ( string.IsNullOrWhiteSpace( acAddress.Street1 ) ) { if ( workLocation != null ) { groupLocationService.Delete( workLocation ); History.EvaluateChange( changes, "Address", workLocation.Location.ToString(), string.Empty ); } } else { var oldValue = string.Empty; var newLocation = new LocationService( rockContext ).Get( acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country ); if ( workLocation != null ) { oldValue = workLocation.Location.ToString(); } else { workLocation = new GroupLocation(); groupLocationService.Add( workLocation ); workLocation.GroupId = adultFamilyMember.Group.Id; workLocation.GroupLocationTypeValueId = workLocationTypeId; } workLocation.Location = newLocation; History.EvaluateChange( changes, "Address", oldValue, newLocation.ToString() ); } rockContext.SaveChanges(); hfBusinessId.Value = business.Id.ToString(); } ); ShowSummary( hfBusinessId.Value.AsInteger() ); }
/// <summary> /// Finds the person if they're logged in, or by email and name. If not found, creates a new person. /// </summary> /// <returns></returns> private Person FindPerson() { Person person; var personService = new PersonService(); if ( CurrentPerson != null ) { person = CurrentPerson; } else { person = personService.GetByEmail( tbEmail.Text ) .FirstOrDefault( p => p.FirstName == tbFirstName.Text && p.LastName == tbLastName.Text ); } if ( person == null ) { var definedValue = DefinedValueCache.Read( new Guid( GetAttributeValue( "DefaultConnectionStatus" ) ) ); person = new Person { FirstName = tbFirstName.Text, LastName = tbLastName.Text, Email = tbEmail.Text, ConnectionStatusValueId = definedValue.Id, }; personService.Add( person, CurrentPersonId ); personService.Save( person, CurrentPersonId ); } return person; }
private Person CreatePerson() { Rock.Model.PersonService personService = new PersonService(); Person person = new Person(); person.FirstName = tbFirstName.Text; person.LastName = tbLastName.Text; person.Email = tbEmail.Text; switch(ddlGender.SelectedValue) { case "M": person.Gender = Gender.Male; break; case "F": person.Gender = Gender.Female; break; default: person.Gender = Gender.Unknown; break; } var birthday = bdaypBirthDay.SelectedDate; if ( birthday.HasValue ) { person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if ( birthday.Value.Year != DateTime.MinValue.Year ) { person.BirthYear = birthday.Value.Year; } } personService.Add(person, CurrentPersonId); personService.Save(person, CurrentPersonId); return person; }
private Person CreatePerson() { Rock.Model.PersonService personService = new PersonService(); Person person = new Person(); person.GivenName = tbFirstName.Text; person.LastName = tbLastName.Text; person.Email = tbEmail.Text; switch(ddlGender.SelectedValue) { case "M": person.Gender = Gender.Male; break; case "F": person.Gender = Gender.Female; break; default: person.Gender = Gender.Unknown; break; } if (ddlBirthMonth.SelectedValue != "0") person.BirthMonth = Int32.Parse(ddlBirthMonth.SelectedValue); if (ddlBirthDay.SelectedValue != "0") person.BirthDay = Int32.Parse(ddlBirthDay.SelectedValue); if (ddlBirthYear.SelectedValue != "0") person.BirthYear = Int32.Parse(ddlBirthYear.SelectedValue); personService.Add(person, CurrentPersonId); personService.Save(person, CurrentPersonId); return person; }
/// <summary> /// Authenticates the specified request. /// </summary> /// <param name="request">The request.</param> /// <param name="username">The username.</param> /// <param name="returnUrl">The return URL.</param> /// <returns></returns> public override Boolean Authenticate( HttpRequest request, out string username, out string returnUrl ) { var fbClient = new FacebookClient(); FacebookOAuthResult oAuthResult; if ( fbClient.TryParseOAuthCallbackUrl( request.Url, out oAuthResult ) && oAuthResult.IsSuccess ) { try { var redirectUri = new Uri( GetRedirectUrl( request ) ); dynamic parameters = new ExpandoObject(); parameters.client_id = GetAttributeValue( "AppID" ); parameters.client_secret = GetAttributeValue( "AppSecret" ); parameters.redirect_uri = redirectUri.AbsoluteUri; parameters.code = oAuthResult.Code; dynamic result = fbClient.Post( "oauth/access_token", parameters ); string accessToken = result.access_token; fbClient = new FacebookClient( accessToken ); dynamic me = fbClient.Get( "me" ); string facebookId = "FACEBOOK_" + me.id.ToString(); // query for matching id in the user table var userLoginService = new UserLoginService(); var user = userLoginService.GetByUserName( facebookId ); // if not user was found see if we can find a match in the person table if ( user == null ) { try { // determine if we can find a match and if so add an user login record // get properties from Facebook dynamic object string lastName = me.last_name.ToString(); string firstName = me.first_name.ToString(); string email = me.email.ToString(); var personService = new PersonService(); var person = personService.Queryable().FirstOrDefault( u => u.LastName == lastName && u.FirstName == firstName && u.Email == email ); if ( person != null ) { // since we have the data enter the birthday from Facebook to the db if we don't have it yet DateTime birthdate = Convert.ToDateTime( me.birthday.ToString() ); if ( person.BirthDay == null ) { person.BirthDate = birthdate; personService.Save( person, person.Id ); } } else { var dvService = new DefinedValueService(); person = new Person(); person.IsSystem = false; person.RecordTypeValueId = dvService.GetIdByGuid( new Guid( SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON ) ); person.RecordStatusValueId = dvService.GetIdByGuid( new Guid( SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE ) ); person.FirstName = me.first_name.ToString(); person.LastName = me.last_name.ToString(); person.Email = me.email.ToString(); if ( me.gender.ToString() == "male" ) person.Gender = Gender.Male; else if ( me.gender.ToString() == "female" ) person.Gender = Gender.Female; else person.Gender = Gender.Unknown; person.BirthDate = Convert.ToDateTime( me.birthday.ToString() ); person.DoNotEmail = false; personService.Add( person, null ); personService.Save( person, null ); } user = userLoginService.Create( person, AuthenticationServiceType.External, this.TypeId, facebookId, "fb", true, person.Id ); } catch ( Exception ex ) { string msg = ex.Message; // TODO: probably should report something... } // TODO: Show label indicating inability to find user corresponding to facebook id } username = user.UserName; returnUrl = oAuthResult.State; return true; } catch ( FacebookOAuthException oae ) { string msg = oae.Message; // TODO: Add error handeling // Error validating verification code. (usually from wrong return url very picky with formatting) // Error validating client secret. // Error validating application. } } username = null; returnUrl = null; return false; }
/// <summary> /// Adds a new person. /// </summary> /// <param name="firstName">The first name.</param> /// <param name="lastName">The last name.</param> /// <param name="DOB">The DOB.</param> /// <param name="gender">The gender</param> /// <param name="attribute">The attribute.</param> protected Person CreatePerson( string firstName, string lastName, DateTime? dob, int? gender, string ability, string abilityGroup ) { Person person = new Person(); person.FirstName = firstName; person.LastName = lastName; person.BirthDate = dob; if ( gender != null ) { person.Gender = (Gender)gender; } if ( !string.IsNullOrWhiteSpace( ability ) && abilityGroup == "Grade" ) { person.Grade = (int)ability.ConvertToEnum<GradeLevel>(); } var rockContext = new RockContext(); PersonService ps = new PersonService( rockContext ); ps.Add( person ); rockContext.SaveChanges(); if ( !string.IsNullOrWhiteSpace( ability ) && abilityGroup == "Ability" ) { rockContext = new RockContext(); Person p = new PersonService( rockContext ).Get( person.Id ); if ( p != null ) { p.LoadAttributes( rockContext ); p.SetAttributeValue( "AbilityLevel", ability ); p.SaveAttributeValues( ); } } return person; }
#pragma warning restore #endregion #region Methods /// <summary> /// Transforms the data from the dataset. /// </summary> public override int TransformData( string importUser = null ) { // Report progress to the main thread so it can update the UI ReportProgress( 0, "Starting import..." ); // Connects to the source database (already loaded in memory by the UI) var scanner = new DataScanner( database ); // List of tables the user would like to import var tableList = TableNodes.Where( n => n.Checked != false ).Select( n => n.Name ).ToList(); // Supplies a lazy-loaded database queryable var tableData = scanner.ScanTable( "TableName" ).AsQueryable(); // Hold a count of how many records have been imported int completed = 0; // Pick a method to save data to Rock: #1 (simple) or #2 (fast) // Option #1. Standard way to put data in Rock foreach ( var dataRow in tableData ) { // Get a value from the row. This has to be a nullable type. string columnValue = dataRow["ColumnName"] as string; // Create a Rock model and assign data to it Person person = new Person(); person.LastName = columnValue; RockTransactionScope.WrapTransaction( () => { // Instantiate the object model service var personService = new PersonService(); // If it's a new model, add it to the database first personService.Add( person, ImportPersonAlias ); // Save the data to the database personService.Save( person, ImportPersonAlias ); } ); completed++; } // end option #1 // Option #2. More efficient way to import large data sets var newPersonList = new List<Person>(); foreach ( var dataRow in tableData ) { // Get a value from the row. This has to be a nullable type. string columnValue = dataRow["ColumnName"] as string; // Create a Rock model and assign data to it Person person = new Person(); newPersonList.Add( new Person() ); completed++; // Save 100 people at a time if ( completed % 100 < 1 ) { RockTransactionScope.WrapTransaction( () => { var personService = new PersonService(); personService.RockContext.People.AddRange( newPersonList ); personService.RockContext.SaveChanges(); } ); } } // Outside foreach, save any that haven't been saved yet if ( newPersonList.Any() ) { RockTransactionScope.WrapTransaction( () => { var personService = new PersonService(); personService.RockContext.People.AddRange( newPersonList ); personService.RockContext.SaveChanges(); } ); } // end option #2 // Report the final imported count ReportProgress( 100, string.Format( "Completed import: {0:N0} records imported.", completed ) ); return completed; }
/// <summary> /// Adds a new person. /// </summary> /// <param name="firstName">The first name.</param> /// <param name="lastName">The last name.</param> /// <param name="DOB">The DOB.</param> /// <param name="gender">The gender</param> /// <param name="attribute">The attribute.</param> protected Person CreatePerson( string firstName, string lastName, DateTime? dob, int? gender, string ability, string abilityGroup ) { Person person = new Person().Clone( false ); person.FirstName = firstName; person.LastName = lastName; person.BirthDate = dob; if ( gender != null ) { person.Gender = (Gender)gender; } PersonService ps = new PersonService(); Rock.Data.RockTransactionScope.WrapTransaction( () => { ps.Add( person, CurrentPersonId ); ps.Save( person, CurrentPersonId ); } ); if ( !string.IsNullOrWhiteSpace( ability ) ) { if ( abilityGroup == "Grade" ) { person.Grade = (int)ability.ConvertToEnum<GradeLevel>(); ps.Save( person, CurrentPersonId ); } else if ( abilityGroup == "Ability" ) { Person p = new PersonService().Get( person.Id ); if ( p != null ) { p.LoadAttributes(); p.SetAttributeValue( "AbilityLevel", ability ); Rock.Attribute.Helper.SaveAttributeValues( p, CurrentPersonId ); } } } return person; }