/// <summary> /// Sets the approval values. /// </summary> /// <param name="approved">if set to <c>true</c> [approved].</param> /// <param name="person">The person.</param> private void SetApprovalValues(bool approved, PersonAlias personAlias) { string cssClass = string.Empty; if (approved) { cssClass = "label label-success"; } else { cssClass = "label label-danger"; } lblApprovalStatus.Text = string.Format("<span class='{0}'>{1}</span>", cssClass, approved ? "Approved" : "Not-Approved"); hfApprovalStatus.Value = approved.ToTrueFalse(); if (personAlias != null && personAlias.Person != null) { lblApprovalStatusPerson.Visible = true; lblApprovalStatusPerson.Text = "by " + personAlias.Person.FullName; hfApprovalStatusPersonId.Value = personAlias.Person.Id.ToString(); } else { lblApprovalStatusPerson.Visible = false; } }
private void SetPersonDateValue(Literal literal, PersonAlias personAlias, DateTime?datetime, string labelText) { if (personAlias != null) { SetPersonDateValue(literal, personAlias.Person, datetime, labelText); } }
/// <summary> /// Logs the error to database (or filesystem if database isn't available) /// </summary> /// <param name="ex">The ex.</param> /// <param name="context">The context.</param> private static void LogError(Exception ex, HttpContext context) { int? pageId; int? siteId; PersonAlias personAlias = null; if (context == null) { pageId = null; siteId = null; } else { var pid = context.Items["Rock:PageId"]; pageId = pid != null?int.Parse(pid.ToString()) : ( int? )null; var sid = context.Items["Rock:SiteId"]; siteId = sid != null?int.Parse(sid.ToString()) : ( int? )null; try { var user = UserLoginService.GetCurrentUser(); if (user != null && user.Person != null) { personAlias = user.Person.PrimaryAlias; } } catch { // Intentionally left blank } } ExceptionLogService.LogException(ex, context, pageId, siteId, personAlias); }
public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var personAliasGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "Person").AsGuid()).AsGuidOrNull(); if (personAliasGuid.HasValue) { PersonAliasService personAliasService = new PersonAliasService(new RockContext()); PersonAlias personAlias = personAliasService.Get(personAliasGuid.Value); var client = new RestClient(GlobalAttributesCache.Value("MinistrySafeAPIURL")); var request = new RestRequest("/users/{ExternalId}", Method.GET); request.AddHeader("Authorization", "Token token=" + GlobalAttributesCache.Value("MinistrySafeAPIToken")); request.AddUrlSegment("ExternalId", personAlias.Id.ToString()); var tmp = client.Execute <MinistrySafeUser>(request); var user = tmp.Data; SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "Score").AsGuid(), user.score.ToString()); if (user.complete_date != null) { SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "CompletionDate").AsGuid(), user.complete_date.ToString()); } return(true); } return(false); }
public bool Save(PersonAlias personAlias, out List <Audit> audits, out List <string> errorMessages) { audits = new List <Audit>(); errorMessages = new List <string>(); return(true); }
/// <summary> /// Gets the by alias unique identifier. /// </summary> /// <param name="aliasPersonGuid">The alias person unique identifier.</param> /// <returns></returns> public virtual PersonAlias GetByAliasGuid( Guid aliasPersonGuid ) { var personAlias = Queryable( "Person" ).Where( a => a.AliasPersonGuid == aliasPersonGuid ).FirstOrDefault(); if ( personAlias != null ) { return personAlias; } else { // If the personId is valid, there should be a personAlias with the AliasPersonID equal // to that personId. If there isn't for some reason, create it now. var person = new PersonService( (RockContext)this.Context ).Get( aliasPersonGuid ); if ( person != null ) { personAlias = new PersonAlias(); personAlias.Guid = Guid.NewGuid(); personAlias.AliasPersonId = person.Id; personAlias.AliasPersonGuid = person.Guid; personAlias.PersonId = person.Id; // Use a different context so calling method's changes are not yet saved var rockContext = new RockContext(); new PersonAliasService( rockContext ).Add( personAlias ); rockContext.SaveChanges(); return Get( personAlias.Id ); } } return null; }
/// <summary> /// Gets the specified <see cref="Rock.Model.EntityType"/> by the object type. If a match is not found, it can optionally create a new <see cref="Rock.Model.EntityType"/> for the object. /// </summary> /// <param name="type">The <see cref="System.Type"/> to search for.</param> /// <param name="createIfNotFound">A <see cref="System.Boolean"/> value that indicates if a new <see cref="Rock.Model.EntityType"/> should be created if a match is not found. This value /// will be <c>true</c> if a new <see cref="Rock.Model.EntityType"/> should be created if there is not a match; otherwise <c>false</c>/</param> /// <param name="personAlias">A <see cref="Rock.Model.PersonAlias"/> representing the alias of the <see cref="Rock.Model.Person"/> who is searching for and possibly creating a new EntityType. This value can be /// null if the logged in person is not known (i.e. an anonymous user).</param> /// <returns>A <see cref="Rock.Model.EntityType"/> matching the provided type. If a match is not found and createIfNotFound is false this value will be null.</returns> public EntityType Get( Type type, bool createIfNotFound, PersonAlias personAlias ) { var entityType = Get( type.FullName ); if ( entityType != null ) { return entityType; } if ( createIfNotFound ) { // Create a new context so type can be saved independing of current context using ( var rockContext = new RockContext() ) { var EntityTypeService = new EntityTypeService( rockContext ); entityType = new EntityType(); entityType.Name = type.FullName; entityType.FriendlyName = type.Name.SplitCase(); entityType.AssemblyName = type.AssemblyQualifiedName; EntityTypeService.Add( entityType ); rockContext.SaveChanges(); } // Read type using current context return this.Get( entityType.Id ); } return null; }
/// <summary> /// Checks the database for existing import data. /// returns false if an error occurred /// </summary> private bool LoadExistingData(string importUser) { var lookupContext = new RockContext(); var personService = new PersonService(lookupContext); var importPerson = personService.GetByFullName(importUser, includeDeceased: false, allowFirstNameOnly: true).FirstOrDefault(); if (importPerson == null) { importPerson = personService.Queryable().FirstOrDefault(); if (importPerson == null) { LogException("CheckExistingImport", "The named import user was not found, and none could be created."); return(false); } } ImportPersonAlias = new PersonAliasService(lookupContext).Get(importPerson.Id); PersonEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id; FamilyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; ReportProgress(0, "Checking your database for previously imported people..."); // Don't track groups in this context, just use it as a static reference ImportedPeople = lookupContext.Groups.AsNoTracking().Where(g => g.GroupTypeId == FamilyGroupTypeId && g.ForeignId != null).ToList(); CampusList = new CampusService(lookupContext).Queryable().ToList(); return(true); }
/// <summary> /// Creates audit logs and/or triggers workflows for items that were changed /// </summary> /// <param name="updatedItems">The updated items.</param> /// <param name="personAlias">The person alias.</param> /// <param name="enableAuditing">if set to <c>true</c> [enable auditing].</param> protected virtual void RockPostSave(List <ContextItem> updatedItems, PersonAlias personAlias, bool enableAuditing = false) { if (enableAuditing) { try { var audits = updatedItems.Select(i => i.Audit).ToList(); if (audits.Any(a => a.Details.Any())) { var transaction = new Rock.Transactions.AuditTransaction(); transaction.Audits = audits; Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction); } } catch (SystemException ex) { ExceptionLogService.LogException(ex, null); } } foreach (var item in updatedItems) { if (item.State == EntityState.Detached || item.State == EntityState.Deleted) { TriggerWorkflows(item, WorkflowTriggerType.PostDelete, personAlias); } else { TriggerWorkflows(item, WorkflowTriggerType.ImmediatePostSave, personAlias); TriggerWorkflows(item, WorkflowTriggerType.PostSave, personAlias); } } }
public PersonAliasViewModel(PersonAlias pa) { this.Id = pa.Id; this.PersonId = pa.Person.Id; this.LastName = pa.LastName; this.FirstName = pa.FirstName; this.Archive = pa.Archive; this.Notes = pa.Notes; }
/// <summary> /// Does a direct bulk UPDATE. /// Example: rockContext.BulkUpdate( personQuery, p => new Person { LastName = "Decker" } ); /// NOTE: This bypasses the Rock and a bunch of the EF Framework and automatically commits the changes to the database /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable">The queryable for the records to update</param> /// <param name="updateFactory">Linq expression to specify the updated property values</param> /// <returns>the number of records updated</returns> public virtual int BulkUpdate <T>(IQueryable <T> queryable, Expression <Func <T, T> > updateFactory) where T : class { var currentDateTime = RockDateTime.Now; PersonAlias currentPersonAlias = this.GetCurrentPersonAlias(); var rockExpressionVisitor = new RockBulkUpdateExpressionVisitor(currentDateTime, currentPersonAlias); rockExpressionVisitor.Visit(updateFactory); int recordsUpdated = queryable.Update(updateFactory); return(recordsUpdated); }
/// <summary> /// Logs new <see cref="Rock.Model.ExceptionLog" /> entities. This method serves as an interface to asynchronously log exceptions. /// </summary> /// <param name="ex">A <see cref="System.Exception" /> object to log.</param> /// <param name="context">The <see cref="System.Web.HttpContext" /></param> /// <param name="pageId">A <see cref="System.Int32" /> containing the Id of the <see cref="Rock.Model.Page" /> that the exception occurred on. /// This parameter is nullable..</param> /// <param name="siteId">A <see cref="System.Int32" /> containing the Id of the <see cref="Rock.Model.Site" /> that the exception occurred on.</param> /// <param name="personAlias">The person alias.</param> public static void LogException( Exception ex, HttpContext context, int? pageId = null, int? siteId = null, PersonAlias personAlias = null ) { // Populate the initial ExceptionLog with data from HttpContext. Must capture initial // HttpContext details before spinning off new thread, because the current context will // not be the same within the context of the new thread. var exceptionLog = PopulateExceptionLog( ex, context, pageId, siteId, personAlias ); // Spin off a new thread to handle the real logging work so the UI is not blocked whilst // recursively writing to the database. Task.Run( () => LogExceptions( ex, exceptionLog, true ) ); }
public void Verify_Add_Should_AddTheEntityToTheContext() { // Arrange Mock<IDbSet<PersonAlias>> mockSetPersonAliases; var mockContext = PersonAliasesMockingSetup.DoMockingSetupForContext(false, out mockSetPersonAliases); var repository = new PersonAliasesRepository(mockContext.Object); var personAliases = new PersonAlias { Active = true, CustomKey = "SALVATORE-RAA", }; // Act repository.Add(personAliases); // Assert mockSetPersonAliases.Verify(x => x.Add(personAliases), Times.Once); }
/// <summary> /// Saves all changes made in this context to the underlying database. The /// default pre and post processing can also optionally be disabled. This /// would disable audit records being created, workflows being triggered, and /// any PreSaveChanges() methods being called for changed entities. /// </summary> /// <param name="disablePrePostProcessing">if set to <c>true</c> disables /// the Pre and Post processing from being run. This should only be disabled /// when updating a large number of records at a time (e.g. importing records).</param> /// <returns></returns> public int SaveChanges(bool disablePrePostProcessing) { // Pre and Post processing has been disabled, just call the base // SaveChanges() method and return if (disablePrePostProcessing) { return(base.SaveChanges()); } int result = 0; SaveErrorMessages = new List <string>(); // Try to get the current person alias and id PersonAlias personAlias = GetCurrentPersonAlias(); bool enableAuditing = GlobalAttributesCache.Value("EnableAuditing").AsBoolean(); // Evaluate the current context for items that have changes var updatedItems = RockPreSave(this, personAlias, enableAuditing); // If update was not cancelled by triggered workflow if (updatedItems != null) { try { // Save the context changes result = base.SaveChanges(); } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { var validationErrors = new List <string>(); foreach (var error in ex.EntityValidationErrors) { foreach (var prop in error.ValidationErrors) { validationErrors.Add(string.Format("{0} ({1}): {2}", error.Entry.Entity.GetType().Name, prop.PropertyName, prop.ErrorMessage)); } } throw new SystemException("Entity Validation Error: " + validationErrors.AsDelimited(";"), ex); } // If any items changed process audit and triggers if (updatedItems.Any()) { RockPostSave(updatedItems, personAlias, enableAuditing); } } return(result); }
public JsonNetResult Delete(int id) { PersonAlias alias = this.personTasks.GetPersonAlias(id); if (alias != null) { this.personTasks.DeletePersonAlias(alias); Response.StatusCode = (int)HttpStatusCode.OK; return(JsonNet("Person alias successfully removed.")); } Response.StatusCode = (int)HttpStatusCode.NotFound; return(JsonNet("Person alias not found.")); }
public void DeletePersonAlias(PersonAlias alias) { Person person = alias.Person; if (person != null) { person.RemovePersonAlias(alias); // queue update to Person index BackgroundJob.Enqueue <IPersonTasks>(x => x.LuceneUpdatePersonQueueable(person.Id)); } this.personAliasRepo.Delete(alias); }
/// <summary> /// Does a direct bulk UPDATE. /// Example: rockContext.BulkUpdate( personQuery, p => new Person { LastName = "Decker" } ); /// NOTE: This bypasses the Rock and a bunch of the EF Framework and automatically commits the changes to the database /// </summary> /// <typeparam name="T"></typeparam> /// <param name="queryable">The queryable for the records to update</param> /// <param name="updateFactory">Linq expression to specify the updated property values</param> /// <returns>the number of records updated</returns> public virtual int BulkUpdate <T>(IQueryable <T> queryable, Expression <Func <T, T> > updateFactory) where T : class { var currentDateTime = RockDateTime.Now; PersonAlias currentPersonAlias = this.GetCurrentPersonAlias(); var rockExpressionVisitor = new RockBulkUpdateExpressionVisitor(currentDateTime, currentPersonAlias); var updatedExpression = rockExpressionVisitor.Visit(updateFactory) as Expression <Func <T, T> > ?? updateFactory; int recordsUpdated = queryable.Update(updatedExpression, batchUpdateBuilder => { batchUpdateBuilder.Executing = (e) => { e.CommandTimeout = this.Database.CommandTimeout ?? 30; }; }); return(recordsUpdated); }
public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages) { var mergeFields = GetMergeFields(action); errorMessages = new List <string>(); // Get the startdate/enddate DateTime?startDate = GetAttributeValue(action, "StartDate", true).ResolveMergeFields(mergeFields).AsDateTime(); DateTime?endDate = GetAttributeValue(action, "EndDate", true).ResolveMergeFields(mergeFields).AsDateTime(); // Now set the person PersonAliasService personAliasService = new PersonAliasService(rockContext); PersonAlias targetPersonAlias = personAliasService.Get(GetAttributeValue(action, "Person", true).AsGuid()); // get excluded currency types setting List <Guid> excludedCurrencyTypes = new List <Guid>(); if (GetAttributeValue(action, "ExcludedCurrencyTypes").IsNotNullOrWhiteSpace()) { excludedCurrencyTypes = GetAttributeValue(action, "ExcludedCurrencyTypes").Split(',').Select(Guid.Parse).ToList(); } List <Guid> accountGuids = null; if (!string.IsNullOrWhiteSpace(GetAttributeValue(action, "Accounts"))) { accountGuids = GetAttributeValue(action, "Accounts").Split(',').Select(Guid.Parse).ToList(); } // Add all the merge fields from the Statement Utility Statement.AddMergeFields(mergeFields, targetPersonAlias.Person, new DateRange(startDate, endDate), excludedCurrencyTypes, accountGuids); var template = GetAttributeValue(action, "LavaTemplate"); string output = template.ResolveMergeFields(mergeFields); // Now store the target attribute var targetAttribute = AttributeCache.Get(GetActionAttributeValue(action, "StatementHTML").AsGuid(), rockContext); if (targetAttribute.EntityTypeId == new Rock.Model.Workflow().TypeId) { action.Activity.Workflow.SetAttributeValue(targetAttribute.Key, output); } else if (targetAttribute.EntityTypeId == new WorkflowActivity().TypeId) { action.Activity.SetAttributeValue(targetAttribute.Key, output); } return(true); }
private bool HasPublicOrPrivatePrayerRequest(PersonAlias personAlias, DateTime cutoffDateTime) { using (var rockContext = new RockContext()) { return(new PrayerRequestService(rockContext) .Queryable().AsNoTracking() .Any(r => r.RequestedByPersonAlias != null && r.RequestedByPersonAlias.PersonId == personAlias.PersonId && r.ApprovedOnDateTime.HasValue && r.ApprovedOnDateTime.Value >= cutoffDateTime && r.IsApproved == true)); } }
/// <summary> /// Launches the workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="connectionWorkflow">The connection workflow.</param> /// <param name="name">The name.</param> private void LaunchWorkflow(RockContext rockContext, Attendance attendance, PersonAlias pagePersonAlias, WorkflowType pageWorkflowType) { if (pageWorkflowType != null) { var workflow = Rock.Model.Workflow.Activate(pageWorkflowType, pageWorkflowType.WorkTerm, rockContext); if (workflow != null) { workflow.SetAttributeValue("Person", attendance.PersonAlias.Guid); workflow.SetAttributeValue("PagePerson", pagePersonAlias.Guid); var workflowService = new Rock.Model.WorkflowService(rockContext); List <string> workflowErrors; if (workflowService.Process(workflow, attendance, out workflowErrors)) { if (workflow.Id != 0) { if (workflow.HasActiveEntryForm(CurrentPerson)) { var qryParam = new Dictionary <string, string>(); qryParam.Add("WorkflowTypeId", pageWorkflowType.Id.ToString()); qryParam.Add("WorkflowId", workflow.Id.ToString()); NavigateToLinkedPage("WorkflowEntryPage", qryParam); } else { mdWorkflowLaunched.Show(string.Format("A '{0}' workflow has been started.", pageWorkflowType.Name), ModalAlertType.Information); } } else { mdWorkflowLaunched.Show(string.Format("A '{0}' workflow was processed (but not persisted).", pageWorkflowType.Name), ModalAlertType.Information); } } else { mdWorkflowLaunched.Show("Workflow Processing Error(s):<ul><li>" + workflowErrors.AsDelimited("</li><li>") + "</li></ul>", ModalAlertType.Information); } return; } } Dictionary <string, string> qParams = new Dictionary <string, string>(); qParams.Add("AttendanceId", attendance.Id.ToString()); qParams.Add("PagePersonId", pagePersonAlias.Person.Id.ToString()); NavigateToLinkedPage("WorkflowEntryPage", qParams); }
private Person GetPerson(PersonAliasService personAliasService, IEnumerable <AttributeValue> AttributeValues) { AttributeValue personAliasAV = AttributeValues.AsQueryable().Where(av => av.AttributeKey == "PersonToVisit" || av.AttributeKey == "HomeboundPerson").FirstOrDefault(); if (personAliasAV != null) { PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid()); if (pa != null) { return(pa.Person); } } return(new Person()); }
public ActionResult Edit(int id) { PersonAlias alias = this.personTasks.GetPersonAlias(id); if (alias != null) { PersonAliasViewModel vm = new PersonAliasViewModel(alias); return(View(vm)); } else { return(new HttpNotFoundResult()); } }
public void Verify_MapToEntity_WithExistingEntity_AssignsPersonAliasProperties() { // Arrange var mapper = new PersonAliasMapper(); var model = PersonAliasesMockingSetup.DoMockingSetupForPersonAliasModel(); // Act IPersonAlias existingEntity = new PersonAlias { Id = 1 }; mapper.MapToEntity(model.Object, ref existingEntity); // Assert // <None> // Related Objects Assert.Equal(model.Object.PersonId, existingEntity.PersonId); // Associated Objects // <None> }
public void Verify_Add_Should_AddTheEntityToTheContext() { // Arrange Mock <IDbSet <PersonAlias> > mockSetPersonAliases; var mockContext = PersonAliasesMockingSetup.DoMockingSetupForContext(false, out mockSetPersonAliases); var repository = new PersonAliasesRepository(mockContext.Object); var personAliases = new PersonAlias { Active = true, CustomKey = "SALVATORE-RAA", }; // Act repository.Add(personAliases); // Assert mockSetPersonAliases.Verify(x => x.Add(personAliases), Times.Once); }
public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var personAliasGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "Person").AsGuid()).AsGuidOrNull(); if (personAliasGuid.HasValue) { PersonAliasService personAliasService = new PersonAliasService(new RockContext()); PersonAlias personAlias = personAliasService.Get(personAliasGuid.Value); var client = new RestClient(GlobalAttributesCache.Value("MinistrySafeAPIURL")); var post = new RestRequest("/users", Method.POST); post.AddHeader("Authorization", "Token token=" + GlobalAttributesCache.Value("MinistrySafeAPIToken")); post.AddJsonBody(new { user = new MinistrySafeUser() { external_id = personAlias.Id.ToString(), first_name = personAlias.Person.NickName, last_name = personAlias.Person.LastName, email = personAlias.Person.Email }, tags = string.Join(",", GetActionAttributeValue(action, "MinistrySafeTags").Trim('|').Split('|')) } ); var execution = client.Execute <bool>(post); if (execution.Data == true) { var request = new RestRequest("/users/{ExternalId}", Method.GET); request.AddHeader("Authorization", "Token token=" + GlobalAttributesCache.Value("MinistrySafeAPIToken")); request.AddUrlSegment("ExternalId", personAlias.Id.ToString()); var tmp = client.Execute <MinistrySafeUser>(request); var user = tmp.Data; if (user.direct_login_url != null) { SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "MinistrySafeURL").AsGuid(), user.direct_login_url); } return(true); } } return(false); }
/// <summary> /// Gets the audit HTML. /// </summary> /// <param name="personAlias">The person alias.</param> /// <param name="dateTime">The date time.</param> /// <param name="rootUrl">The root URL.</param> /// <returns></returns> private string GetAuditHtml(PersonAlias personAlias, DateTime?dateTime, string rootUrl) { var sb = new StringBuilder(); if (personAlias != null && personAlias.Person != null) { sb.AppendFormat("<a href={0}Person/{1}>{2}</a> ", rootUrl, personAlias.PersonId, personAlias.Person.FullName); } if (dateTime.HasValue) { sb.AppendFormat("<small class='js-date-rollover' data-toggle='tooltip' data-placement='top' title='{0}'>({1})</small>", dateTime.Value.ToString(), dateTime.Value.ToRelativeDateString()); } return(sb.ToString()); }
public PersonAlias SavePersonAlias(PersonAlias alias) { Person person = alias.Person; if (person != null) { person.AddPersonAlias(alias); if (!person.HasValidProfileStatus()) { person.ProfileStatus = this.GetProfileStatus(ProfileStatus.ROUGH_OUTLINE); } this.SavePerson(person); // also updates lucene } return(this.personAliasRepo.SaveOrUpdate(alias)); }
private bool ModifyFrontPorchUser(int personAliasId) { // Fetch the person alias PersonAliasService personAliasService = new PersonAliasService(new RockContext()); PersonAlias personAlias = personAliasService.Get(personAliasId); FrontPorchUser user = new FrontPorchUser() { name = personAlias.Person.FullName, email = personAlias.Person.Email, userId = personAlias.Id }; // Always set the SecureNetworkSSID; user.secureNetworkSSID = GetAttributeValue("NetworkSSID"); var url = string.Format("https://{0}/api/user/modify", fpHost); HttpWebRequest request = ( HttpWebRequest )WebRequest.Create(url); request.Headers.Add(fpAuthenticationHeader); request.Method = "POST"; request.ContentType = "application/json"; try { JavaScriptSerializer js = new JavaScriptSerializer(); byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(js.Serialize(user)); request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); // Close the Stream objec HttpWebResponse response = ( HttpWebResponse )request.GetResponse(); Stream resStream = response.GetResponseStream(); if (response.StatusCode == HttpStatusCode.OK) { return(true); } } catch (Exception e) { LogException(e); } return(false); }
public JsonNetResult Edit(PersonAliasViewModel vm) { if (ModelState.IsValid) { PersonAlias alias = this.personTasks.GetPersonAlias(vm.Id); if (alias != null) { Mapper.Map <PersonAliasViewModel, PersonAlias>(vm, alias); alias = this.personTasks.SavePersonAlias(alias); return(JsonNet(string.Empty)); } Response.StatusCode = (int)HttpStatusCode.NotFound; return(JsonNet("Person alias not found.")); } else { return(JsonNet(this.GetErrorsForJson())); } }
public static void AddAliasList(Person person, ICollection<AliasPersonRel> list) { foreach (var rel in list) { var c = rel; var @alias = new PersonAlias() { Id = c.AliasId, Name = c.Alias.AliasName, PrimaryStatus = (PrimaryStatus)c.PrimaryStatusId, DateCreated = c.DateCreated, DateUpdated = c.DateModified }; person.PersonAliases.Add(@alias); person.LogEntries.Add(new PersonLogEntry() { Note = $"Added Person {person.FullName} alias {@alias.Name}" }); } }
private void Actions_CommunicateClick(object sender, EventArgs e) { var rockPage = Page as RockPage; BindGrid(); var redirectUrl = rockPage.Response.Output.ToString(); if (redirectUrl != null) { Regex rgx = new Regex(".*/(\\d*)"); string result = rgx.Replace(redirectUrl, "$1"); var recipients = GetDuplicatePersonData(); if (recipients.Any()) { // Create communication var communicationRockContext = new RockContext(); var communicationService = new CommunicationService(communicationRockContext); var communicationRecipientService = new CommunicationRecipientService(communicationRockContext); var personAliasService = new PersonAliasService(communicationRockContext); var communication = communicationService.Queryable().Where(c => c.SenderPersonAliasId == rockPage.CurrentPersonAliasId).OrderByDescending(c => c.Id).FirstOrDefault(); communication.IsBulkCommunication = false; foreach (var recipient in recipients) { PersonAlias a = personAliasService.Queryable().Where(p => p.PersonId == p.AliasPersonId && p.PersonId == recipient.Key).FirstOrDefault(); var communicationRecipient = new CommunicationRecipient { CommunicationId = communication.Id, PersonAliasId = a.Id, AdditionalMergeValues = recipient.Value }; communicationRecipientService.Add(communicationRecipient); communicationRockContext.SaveChanges(); } } } }
public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var mergeFields = GetMergeFields(action); // Get the connection request ConnectionRequest request = null; var connectionRequestGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionRequestAttribute").AsGuid()).AsGuid(); request = new ConnectionRequestService(rockContext).Get(connectionRequestGuid); if (request == null) { errorMessages.Add("Invalid Connection Request Attribute or Value!"); return(false); } // Get the connector PersonAlias personAlias = null; Guid? personAttributeGuid = GetAttributeValue(action, "PersonAttribute").AsGuidOrNull(); if (personAttributeGuid.HasValue) { Guid?personAliasGuid = action.GetWorklowAttributeValue(personAttributeGuid.Value).AsGuidOrNull(); if (personAliasGuid.HasValue) { personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value); if (personAlias == null) { errorMessages.Add("Invalid Person"); return(false); } } } request.ConnectorPersonAlias = personAlias; rockContext.SaveChanges(); return(true); }
private void submitPrayer(PersonAlias personAlias, string prayerRequest, RockContext rockContext) { var prayerService = new PrayerRequestService(rockContext); // Parse out if (prayerRequest.StartsWith("3")) { prayerRequest = prayerRequest.Substring(1, prayerRequest.Length - 1); } prayerService.Add(new PrayerRequest { EnteredDateTime = RockDateTime.Now, CreatedDateTime = RockDateTime.Now, ExpirationDate = RockDateTime.Now.AddYears(1), Text = prayerRequest, RequestedByPersonAlias = personAlias, IsActive = true, AllowComments = true, FirstName = personAlias.Person.FirstName, LastName = personAlias.Person.LastName }); rockContext.SaveChanges(); }
/// <summary> /// Checks the database for existing import data. /// returns false if an error occurred /// </summary> private bool LoadExistingData(string importUser) { //try //{ var lookupContext = new RockContext(); var personService = new PersonService(lookupContext); var importPerson = personService.GetByFullName(importUser, includeDeceased: false, allowFirstNameOnly: true).FirstOrDefault(); if (importPerson == null) { importPerson = personService.Queryable().FirstOrDefault(); if (importPerson == null) { LogException("CheckExistingImport", "The named import user was not found, and none could be created."); return(false); } } ImportPersonAlias = new PersonAliasService(lookupContext).Get(importPerson.Id); PersonEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id; FamilyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; ReportProgress(0, "Checking for existing people..."); ImportedPeople = new GroupService(lookupContext).GetByGroupTypeId(FamilyGroupTypeId).Where(n => n.ForeignId != null).ToList(); CampusList = new CampusService(lookupContext).Queryable().ToList(); return(true); //} //catch ( Exception ex ) //{ // LogException( "CheckExistingImport", ex.ToString() ); // return false; //} }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); // Get the current person alias if possible PersonAlias personAlias = null; if (HttpContext.Current != null && HttpContext.Current.Items.Contains("CurrentPerson")) { var currentPerson = HttpContext.Current.Items["CurrentPerson"] as Person; if (currentPerson != null && currentPerson.PrimaryAlias != null) { personAlias = currentPerson.PrimaryAlias; // Get the attribute to set Guid guid = GetAttributeValue(action, "PersonAttribute").AsGuid(); if (!guid.IsEmpty()) { var personAttribute = AttributeCache.Read(guid, rockContext); if (personAttribute != null) { // If this is a person type attribute if (personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id) { SetWorkflowAttributeValue(action, guid, personAlias.Guid.ToString()); } else if (personAttribute.FieldTypeId == FieldTypeCache.Read(SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id) { SetWorkflowAttributeValue(action, guid, currentPerson.FullName); } } } } } return(true); }
/// <summary> /// Transforms the data from the dataset. /// </summary> /// <returns></returns> public override int TransformData( string importUser = null ) { ReportProgress( 0, "Starting import..." ); var personService = new PersonService(); var importPerson = personService.GetByFullName( importUser, includeDeceased: false, allowFirstNameOnly: true ).FirstOrDefault(); ImportPersonAlias = new PersonAliasService().Get( importPerson.Id ); var tableList = TableNodes.Where( n => n.Checked != false ).ToList(); ReportProgress( 0, "Checking for existing attributes..." ); LoadExistingRockData(); ReportProgress( 0, "Checking for table dependencies..." ); bool isValidImport = ImportedPeople.Any() || tableList.Any( n => n.Name.Equals( "Individual_Household" ) ); var tableDependencies = new List<string>(); tableDependencies.Add( "Batch" ); // needed to attribute contributions properly tableDependencies.Add( "Company" ); // needed to attribute any company items tableDependencies.Add( "Individual_Household" ); // needed for just about everything if ( isValidImport ) { // Order tables so non-dependents are imported first if ( tableList.Any( n => tableDependencies.Contains( n.Name ) ) ) { tableList = tableList.OrderByDescending( n => tableDependencies.IndexOf( n.Name ) ).ToList(); } var scanner = new DataScanner( database ); foreach ( var table in tableList ) { if ( !tableDependencies.Contains( table.Name ) ) { switch ( table.Name ) { case "Account": MapBankAccount( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Communication": MapCommunication( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Contribution": MapContribution( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Household_Address": MapFamilyAddress( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Pledge": MapPledge( scanner.ScanTable( table.Name ).AsQueryable() ); break; default: break; } } else { if ( table.Name == "Individual_Household" ) { MapPerson( scanner.ScanTable( table.Name ).AsQueryable() ); } else if ( table.Name == "Batch" ) { MapBatch( scanner.ScanTable( table.Name ).AsQueryable() ); } else if ( table.Name == "Company" ) { MapCompany( scanner.ScanTable( table.Name ).AsQueryable() ); } } } ReportProgress( 100, "Import completed. " ); } else { ReportProgress( 0, "No imported people exist. Please include the Individual_Household table during the import." ); } return 0; // return total number of rows imported? }
/// <summary> /// Updates the Created/Modified data for any model being created or modified /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="personAlias">The person alias.</param> /// <returns></returns> protected virtual List<ContextItem> RockPreSave( DbContext dbContext, PersonAlias personAlias ) { int? personAliasId = null; if ( personAlias != null ) { personAliasId = personAlias.Id; } var updatedItems = new List<ContextItem>(); foreach ( var entry in dbContext.ChangeTracker.Entries() .Where( c => c.Entity is IEntity && ( c.State == EntityState.Added || c.State == EntityState.Modified || c.State == EntityState.Deleted ) ) ) { // Cast entry as IEntity var entity = entry.Entity as IEntity; // Get the context item to track audits var contextItem = new ContextItem( entity, entry.State ); // If entity was added or modifed, update the Created/Modified fields if ( entry.State == EntityState.Added || entry.State == EntityState.Modified ) { if ( !TriggerWorkflows( entity, WorkflowTriggerType.PreSave, personAlias ) ) { return null; } if ( entry.Entity is IModel ) { var model = entry.Entity as IModel; model.PreSaveChanges( this, entry.State ); // Update Guid/Created/Modified person and times if ( entry.State == EntityState.Added ) { if ( !model.CreatedDateTime.HasValue ) { model.CreatedDateTime = RockDateTime.Now; } if ( !model.CreatedByPersonAliasId.HasValue ) { model.CreatedByPersonAliasId = personAliasId; } if ( model.Guid == Guid.Empty ) { model.Guid = Guid.NewGuid(); } model.ModifiedDateTime = RockDateTime.Now; model.ModifiedByPersonAliasId = personAliasId; } else if ( entry.State == EntityState.Modified ) { model.ModifiedDateTime = RockDateTime.Now; model.ModifiedByPersonAliasId = personAliasId; } } } else if ( entry.State == EntityState.Deleted ) { if ( !TriggerWorkflows( entity, WorkflowTriggerType.PreDelete, personAlias ) ) { return null; } } try { GetAuditDetails( dbContext, contextItem, personAliasId ); } catch (SystemException ex) { ExceptionLogService.LogException( ex, null ); } updatedItems.Add( contextItem ); } return updatedItems; }
//Just mapping Connect Groups and not People Lists (Wonder if People lists could be Tags?) /// <summary> /// Maps the Connect Groups. /// </summary> /// <param name="tableData">The table data.</param> /// <returns></returns> private void MapGroups( IQueryable<Row> tableData ) { var lookupContext = new RockContext(); int completedMembers = 0; int completedGroups = 0; int completedLifeStages = 0; int completedTags = 0; int completedIndividualTags = 0; int totalRows = tableData.Count(); int percentage = ( totalRows - 1 ) / 100 + 1; ReportProgress( 0, string.Format( "Verifying group import ({0:N0} found. Total may vary based on Group Type Name).", totalRows ) ); foreach ( var row in tableData ) { var rockContext = new RockContext(); var lifeStageContext = new RockContext(); var connectGroupContext = new RockContext(); var connectGroupMemberContext = new RockContext(); string groupTypeName = row["Group_Type_Name"] as string; if ( groupTypeName.Trim() == "Connect Groups" ) //Moves Connect Groups into Rock Groups { var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault(); var connectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault(); var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault(); string groupName = row["Group_Name"] as string; int? groupId = row["Group_ID"] as int?; int? individualId = row["Individual_ID"] as int?; int? personId = GetPersonAliasId( individualId ); DateTime? createdDateTime = row["Created_Date"] as DateTime?; //Check to see if Head of Connect Group Tree exists //If it doesn't exist if ( connectGroupsId == 0 ) { //Create one. var connectGroupTree = new Group(); connectGroupTree.IsSystem = false; connectGroupTree.GroupTypeId = groupTypeIdSection; connectGroupTree.CampusId = 1; connectGroupTree.Name = "Connect Groups"; connectGroupTree.Description = "Crossroads Connect Group Ministry"; connectGroupTree.IsActive = true; //connectGroupTree.Order = 0; connectGroupTree.CreatedByPersonAliasId = 1; connectGroupTree.CreatedDateTime = DateTime.Now; //save group rockContext.WrapTransaction( () => { rockContext.Configuration.AutoDetectChangesEnabled = false; rockContext.Groups.Add( connectGroupTree ); rockContext.SaveChanges( DisableAudit ); } ); } //check to see if life stage exists //getting the life stage name string lifeStage = groupName; int index = lifeStage.IndexOf( "-" ); if ( index > 0 ) lifeStage = lifeStage.Substring( 0, index ).Trim(); //checks to see if it exists int existingLifeStage = new GroupService( lookupContext ).Queryable().Where( g => g.Name == lifeStage ).Select( a => a.Id ).FirstOrDefault(); if ( existingLifeStage == 0 ) { //Create one. var connectGroupsLifeStage = new Group(); connectGroupsLifeStage.IsSystem = false; connectGroupsLifeStage.ParentGroupId = connectGroupsId; connectGroupsLifeStage.GroupTypeId = groupTypeIdSection; connectGroupsLifeStage.CampusId = 1; connectGroupsLifeStage.Name = lifeStage; connectGroupsLifeStage.Description = ""; connectGroupsLifeStage.IsActive = true; //connectGroupsLifeStage.Order = 0; connectGroupsLifeStage.CreatedByPersonAliasId = 1; connectGroupsLifeStage.CreatedDateTime = DateTime.Now; //save Life Stage lifeStageContext.WrapTransaction( () => { lifeStageContext.Configuration.AutoDetectChangesEnabled = false; lifeStageContext.Groups.Add( connectGroupsLifeStage ); lifeStageContext.SaveChanges( DisableAudit ); } ); completedLifeStages++; } int existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault(); existingLifeStage = new GroupService( lookupContext ).Queryable().Where( g => g.Name == lifeStage ).Select( a => a.Id ).FirstOrDefault(); //check to see if Connect Group exists. if ( existingConnectGroup == 0 ) { //Create one. var connectGroups = new Group(); connectGroups.IsSystem = false; connectGroups.GroupTypeId = groupTypeIdSmallGroup; connectGroups.ParentGroupId = existingLifeStage; connectGroups.CampusId = 1; connectGroups.Name = groupName; connectGroups.Description = ""; connectGroups.IsActive = true; //connectGroups.Order = 0; connectGroups.CreatedByPersonAliasId = 1; connectGroups.CreatedDateTime = createdDateTime; connectGroups.ForeignId = groupId.ToString(); //Will use this for GroupsAttendance //Save Group connectGroupContext.WrapTransaction( () => { connectGroupContext.Configuration.AutoDetectChangesEnabled = false; connectGroupContext.Groups.Add( connectGroups ); connectGroupContext.SaveChanges( DisableAudit ); } ); completedGroups++; } existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault(); //Adds Group Member(s) //makes sure Connect Group Exists if ( existingConnectGroup != 0 ) { int memberGroupTypeRoleId = new GroupTypeRoleService( lookupContext ).Queryable().Where( g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member" ).Select( a => a.Id ).FirstOrDefault(); int groupMemberExists = new GroupMemberService( lookupContext ).Queryable().Where( g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId ).Select( a => a.Id ).FirstOrDefault(); if ( groupMemberExists == 0 ) { //adds member var connectGroupMember = new GroupMember(); connectGroupMember.IsSystem = false; connectGroupMember.GroupId = existingConnectGroup; connectGroupMember.PersonId = (int)personId; connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member // ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) ); //Save Member connectGroupMemberContext.WrapTransaction( () => { connectGroupMemberContext.Configuration.AutoDetectChangesEnabled = false; connectGroupMemberContext.GroupMembers.Add( connectGroupMember ); connectGroupMemberContext.SaveChanges( DisableAudit ); } ); completedMembers++; } } if ( completedMembers % percentage < 1 ) { int percentComplete = completedMembers / percentage; //ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) ); } else if ( completedMembers % ReportingNumber < 1 ) { ReportPartialProgress(); } } if ( groupTypeName.Trim() == "Care Ministries" ) //Moves Care Ministries into Rock Groups { var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault(); var careMinistriesId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Care Ministries" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault(); var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault(); string groupName = row["Group_Name"] as string; int? groupId = row["Group_ID"] as int?; int? individualId = row["Individual_ID"] as int?; int? personId = GetPersonAliasId( individualId ); DateTime? createdDateTime = row["Created_Date"] as DateTime?; //Check to see if Head of Care Ministries Tree exists //If it doesn't exist if ( careMinistriesId == 0 ) { //Create one. var connectGroupTree = new Group(); connectGroupTree.IsSystem = false; connectGroupTree.GroupTypeId = groupTypeIdSection; connectGroupTree.CampusId = 1; connectGroupTree.Name = "Care Ministries"; connectGroupTree.Description = "Crossroads Care Ministries"; connectGroupTree.IsActive = true; //connectGroupTree.Order = 0; connectGroupTree.CreatedByPersonAliasId = 1; connectGroupTree.CreatedDateTime = DateTime.Now; //save group var careMinistryContext = new RockContext(); careMinistryContext.WrapTransaction( () => { careMinistryContext.Configuration.AutoDetectChangesEnabled = false; careMinistryContext.Groups.Add( connectGroupTree ); careMinistryContext.SaveChanges( DisableAudit ); } ); } int existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault(); int existingCareMinistries = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Care Ministries" ).Select( a => a.Id ).FirstOrDefault(); //check to see if Connect Group exists. if ( existingConnectGroup == 0 ) { //Create one. var careGroup = new Group(); careGroup.IsSystem = false; careGroup.GroupTypeId = groupTypeIdSmallGroup; careGroup.ParentGroupId = existingCareMinistries; careGroup.CampusId = 1; careGroup.Name = groupName; careGroup.Description = ""; careGroup.IsActive = true; //connectGroups.Order = 0; careGroup.CreatedByPersonAliasId = 1; careGroup.CreatedDateTime = createdDateTime; careGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance //Save Group var careMinistryGroupContext = new RockContext(); careMinistryGroupContext.WrapTransaction( () => { careMinistryGroupContext.Configuration.AutoDetectChangesEnabled = false; careMinistryGroupContext.Groups.Add( careGroup ); careMinistryGroupContext.SaveChanges( DisableAudit ); } ); completedGroups++; } existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault(); //Adds Group Member(s) //makes sure Connect Group Exists if ( existingConnectGroup != 0 ) { int memberGroupTypeRoleId = new GroupTypeRoleService( lookupContext ).Queryable().Where( g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member" ).Select( a => a.Id ).FirstOrDefault(); int groupMemberExists = new GroupMemberService( lookupContext ).Queryable().Where( g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId ).Select( a => a.Id ).FirstOrDefault(); if ( groupMemberExists == 0 ) { //adds member var connectGroupMember = new GroupMember(); connectGroupMember.IsSystem = false; connectGroupMember.GroupId = existingConnectGroup; connectGroupMember.PersonId = (int)personId; connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) ); //Save Member var careGroupMemberContext = new RockContext(); careGroupMemberContext.WrapTransaction( () => { careGroupMemberContext.Configuration.AutoDetectChangesEnabled = false; careGroupMemberContext.GroupMembers.Add( connectGroupMember ); careGroupMemberContext.SaveChanges( DisableAudit ); } ); completedMembers++; } } if ( completedMembers % percentage < 1 ) { int percentComplete = completedMembers / percentage; // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) ); } else if ( completedMembers % ReportingNumber < 1 ) { ReportPartialProgress(); } } if ( groupTypeName.Trim() == "Intro Connect Groups" ) //Moves Intro Connect Groups into Rock Groups { var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault(); var introConnectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Intro Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault(); var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault(); string groupName = row["Group_Name"] as string; int? groupId = row["Group_ID"] as int?; int? individualId = row["Individual_ID"] as int?; int? personId = GetPersonAliasId( individualId ); DateTime? createdDateTime = row["Created_Date"] as DateTime?; //Check to see if Head of Care Ministries Tree exists //If it doesn't exist if ( introConnectGroupsId == 0 ) { //Create one. var connectGroupTree = new Group(); connectGroupTree.IsSystem = false; connectGroupTree.GroupTypeId = groupTypeIdSection; connectGroupTree.CampusId = 1; connectGroupTree.Name = "Intro Connect Groups"; connectGroupTree.Description = "Crossroads Intro Connect Groups"; connectGroupTree.IsActive = true; //connectGroupTree.Order = 0; connectGroupTree.CreatedByPersonAliasId = 1; connectGroupTree.CreatedDateTime = DateTime.Now; //save group var introConnectGroupTreeContext = new RockContext(); introConnectGroupTreeContext.WrapTransaction( () => { introConnectGroupTreeContext.Configuration.AutoDetectChangesEnabled = false; introConnectGroupTreeContext.Groups.Add( connectGroupTree ); introConnectGroupTreeContext.SaveChanges( DisableAudit ); } ); } int existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault(); int existingIntroConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Intro Connect Groups" ).Select( a => a.Id ).FirstOrDefault(); //check to see if Connect Group exists. if ( existingConnectGroup == 0 ) { //Create one. var introConnectGroup = new Group(); introConnectGroup.IsSystem = false; introConnectGroup.GroupTypeId = groupTypeIdSmallGroup; introConnectGroup.ParentGroupId = existingIntroConnectGroup; introConnectGroup.CampusId = 1; introConnectGroup.Name = groupName; introConnectGroup.Description = ""; introConnectGroup.IsActive = true; //connectGroups.Order = 0; introConnectGroup.CreatedByPersonAliasId = 1; introConnectGroup.CreatedDateTime = createdDateTime; introConnectGroup.ForeignId = groupId.ToString(); //will use this later for GroupsAttendance //Save Group var introConnectGroupConext = new RockContext(); introConnectGroupConext.WrapTransaction( () => { introConnectGroupConext.Configuration.AutoDetectChangesEnabled = false; introConnectGroupConext.Groups.Add( introConnectGroup ); introConnectGroupConext.SaveChanges( DisableAudit ); } ); completedGroups++; } existingConnectGroup = new GroupService( lookupContext ).Queryable().Where( g => g.Name == groupName ).Select( a => a.Id ).FirstOrDefault(); //Adds Group Member(s) //makes sure Connect Group Exists if ( existingConnectGroup != 0 ) { int memberGroupTypeRoleId = new GroupTypeRoleService( lookupContext ).Queryable().Where( g => g.GroupTypeId == groupTypeIdSmallGroup && g.Name == "Member" ).Select( a => a.Id ).FirstOrDefault(); int groupMemberExists = new GroupMemberService( lookupContext ).Queryable().Where( g => g.GroupId == existingConnectGroup && g.PersonId == personId && g.GroupRoleId == memberGroupTypeRoleId ).Select( a => a.Id ).FirstOrDefault(); if ( groupMemberExists == 0 ) { //adds member var connectGroupMember = new GroupMember(); connectGroupMember.IsSystem = false; connectGroupMember.GroupId = existingConnectGroup; connectGroupMember.PersonId = (int)personId; connectGroupMember.GroupRoleId = memberGroupTypeRoleId; //will add them as a member //ReportProgress( 0, string.Format( "GroupId: {0}, GroupName: {3}, PersonID: {1}, GroupRoleId: {2}", connectGroupMember.GroupId, connectGroupMember.PersonId, connectGroupMember.GroupRoleId, groupName ) ); //Save Member var introConnectGroupMemberConext = new RockContext(); introConnectGroupMemberConext.WrapTransaction( () => { introConnectGroupMemberConext.Configuration.AutoDetectChangesEnabled = false; introConnectGroupMemberConext.GroupMembers.Add( connectGroupMember ); introConnectGroupMemberConext.SaveChanges( DisableAudit ); } ); completedMembers++; } } if ( completedMembers % percentage < 1 ) { int percentComplete = completedMembers / percentage; // ReportProgress( percentComplete, string.Format( "Life Stages Imported: {0}, Groups Imported: {1}, Members Imported: {2} ({3}% complete). ", completedLifeStages, completedGroups, completedMembers, percentComplete ) ); } else if ( completedMembers % ReportingNumber < 1 ) { ReportPartialProgress(); } } if ( groupTypeName.Trim() == "People List" ) //Places People Lists in tags { var tagService = new TagService( lookupContext ); var entityTypeService = new EntityTypeService( lookupContext ); var taggedItemService = new TaggedItemService( lookupContext ); var personService = new PersonService( lookupContext ); //var groupTypeIdSection = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Event/Serving/Small Group Section" ).Select( a => a.Id ).FirstOrDefault(); //var connectGroupsId = new GroupService( lookupContext ).Queryable().Where( g => g.Name == "Connect Groups" && g.GroupTypeId == groupTypeIdSection ).Select( a => a.Id ).FirstOrDefault(); //var groupTypeIdSmallGroup = new GroupTypeService( lookupContext ).Queryable().Where( gt => gt.Name == "Small Group" ).Select( a => a.Id ).FirstOrDefault(); string peopleListName = row["Group_Name"] as string; int? groupId = row["Group_ID"] as int?; int? individualId = row["Individual_ID"] as int?; int? personId = GetPersonAliasId( individualId ); DateTime? createdDateTime = row["Created_Date"] as DateTime?; if ( personId != null ) { //check if tag exists if ( tagService.Queryable().Where( t => t.Name == peopleListName ).FirstOrDefault() == null ) { //create if it doesn't var newTag = new Tag(); newTag.IsSystem = false; newTag.Name = peopleListName; newTag.EntityTypeQualifierColumn = string.Empty; newTag.EntityTypeQualifierValue = string.Empty; newTag.EntityTypeId = entityTypeService.Queryable().Where( e => e.Name == "Rock.Model.Person" ).FirstOrDefault().Id; //Save tag var tagContext = new RockContext(); tagContext.WrapTransaction( () => { tagContext.Configuration.AutoDetectChangesEnabled = false; tagContext.Tags.Add( newTag ); tagContext.SaveChanges( DisableAudit ); } ); completedTags++; } var personAlias = new PersonAlias(); personAlias = null; if ( tagService.Queryable().Where( t => t.Name == peopleListName ).FirstOrDefault() != null ) //Makes sure tag exists { //selects the ID of the current people list / tag int tagId = tagService.Queryable().Where( t => t.Name == peopleListName ).FirstOrDefault().Id; //gets the person instance in order to use person's GUID later. var personTagged = personService.Queryable().Where( p => p.Id == personId ).FirstOrDefault(); if ( personTagged == null ) { var personAliasService = new PersonAliasService(lookupContext); personAlias = personAliasService.Queryable().Where( p => p.PersonId == (int)personId ).FirstOrDefault(); //ReportProgress( 0, string.Format( "Not able to tag person Id: {0} Tag Name: {1} F1 groupId: {2} Tag Id: {3}. ", personId, peopleListName, groupId, tagId ) ); } //check if person already has this tag if ( personTagged != null && taggedItemService.Queryable().Where( t => t.EntityGuid == personTagged.Guid && t.TagId == tagId ).FirstOrDefault() == null ) { //add tag if one doesn't exist for person. var taggedItem = new TaggedItem(); taggedItem.IsSystem = false; taggedItem.TagId = tagId; taggedItem.EntityGuid = personTagged.Guid; taggedItem.CreatedDateTime = createdDateTime; //save tag var tagContext = new RockContext(); tagContext.WrapTransaction( () => { tagContext.Configuration.AutoDetectChangesEnabled = false; tagContext.TaggedItems.Add( taggedItem ); tagContext.SaveChanges( DisableAudit ); } ); completedIndividualTags++; } if ( personAlias != null && taggedItemService.Queryable().Where( t => t.EntityGuid == personAlias.AliasPersonGuid && t.TagId == tagId ).FirstOrDefault() == null ) { //add tag if one doesn't exist for person. var taggedItem = new TaggedItem(); taggedItem.IsSystem = false; taggedItem.TagId = tagId; taggedItem.EntityGuid = personAlias.AliasPersonGuid; taggedItem.CreatedDateTime = createdDateTime; //save tag var tagContext = new RockContext(); tagContext.WrapTransaction( () => { tagContext.Configuration.AutoDetectChangesEnabled = false; tagContext.TaggedItems.Add( taggedItem ); tagContext.SaveChanges( DisableAudit ); } ); completedIndividualTags++; } } //report Progress if ( completedIndividualTags != 0 ) { if ( completedIndividualTags % percentage < 1 ) { int percentComplete = completedIndividualTags / percentage; // ReportProgress( percentComplete, string.Format( "People Lists / Tags Imported: {0:N0}, Tagged Individuals: {1:N0} ({2:N0}% complete). ", completedTags, completedIndividualTags, percentComplete ) ); } else if ( completedMembers % ReportingNumber < 1 ) { ReportPartialProgress(); } } } } } }
/// <summary> /// Sets the approval values. /// </summary> /// <param name="approved">if set to <c>true</c> [approved].</param> /// <param name="person">The person.</param> private void SetApprovalValues( bool approved, PersonAlias personAlias ) { string cssClass = string.Empty; if ( approved ) { cssClass = "label label-success"; } else { cssClass = "label label-danger"; } lblApprovalStatus.Text = string.Format( "<span class='{0}'>{1}</span>", cssClass, approved ? "Approved" : "Not-Approved" ); hfApprovalStatus.Value = approved.ToTrueFalse(); if ( personAlias != null && personAlias.Person != null ) { lblApprovalStatusPerson.Visible = true; lblApprovalStatusPerson.Text = "by " + personAlias.Person.FullName; hfApprovalStatusPersonId.Value = personAlias.Person.Id.ToString(); } else { lblApprovalStatusPerson.Visible = false; } }
private bool TriggerWorkflows( IEntity entity, WorkflowTriggerType triggerType, PersonAlias personAlias ) { Dictionary<string, PropertyInfo> properties = null; var rockContext = new RockContext(); var workflowTypeService = new WorkflowTypeService( rockContext ); var workflowService = new WorkflowService( rockContext ); foreach ( var trigger in TriggerCache.Triggers( entity.TypeName, triggerType ).Where( t => t.IsActive == true ) ) { bool match = true; if ( !string.IsNullOrWhiteSpace( trigger.EntityTypeQualifierColumn ) ) { if ( properties == null ) { properties = new Dictionary<string, PropertyInfo>(); foreach ( PropertyInfo propertyInfo in entity.GetType().GetProperties() ) { properties.Add( propertyInfo.Name.ToLower(), propertyInfo ); } } match = ( properties.ContainsKey( trigger.EntityTypeQualifierColumn.ToLower() ) && properties[trigger.EntityTypeQualifierColumn.ToLower()].GetValue( entity, null ).ToString() == trigger.EntityTypeQualifierValue ); } if ( match ) { if ( triggerType == WorkflowTriggerType.PreSave || triggerType == WorkflowTriggerType.PreDelete ) { var workflowType = workflowTypeService.Get( trigger.WorkflowTypeId ); if ( workflowType != null ) { var workflow = Rock.Model.Workflow.Activate( workflowType, trigger.WorkflowName ); List<string> workflowErrors; if ( !workflow.Process( rockContext, entity, out workflowErrors ) ) { SaveErrorMessages.AddRange( workflowErrors ); return false; } else { if ( workflow.IsPersisted || workflowType.IsPersisted ) { workflowService.Add( workflow ); rockContext.SaveChanges(); } } } } else { var transaction = new Rock.Transactions.WorkflowTriggerTransaction(); transaction.Trigger = trigger; transaction.Entity = entity.Clone(); transaction.PersonAlias = personAlias; Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); } } } return true; }
public int? SaveNewPersonAlias( int personId) { PersonAliasController aliasController = new PersonAliasController( Service ); string expression = string.Format( "PersonId eq {0} and AliasPersonId eq {1}", personId, personId ); PersonAlias alias = aliasController.GetByFilter( expression ).FirstOrDefault(); PersonController personController = new PersonController( Service ); Person person = personController.GetById( personId ); if ( alias == null ) { alias = new PersonAlias(); alias.PersonId = personId; alias.AliasPersonId = personId; alias.AliasPersonGuid = person.Guid; aliasController.Add( alias ); return aliasController.GetByGuid( alias.Guid ).Id; } else { return alias.Id; } }
/// <summary> /// Updates the Created/Modified data for any model being created or modified /// </summary> /// <param name="dbContext">The database context.</param> /// <param name="personAlias">The person alias.</param> /// <param name="enableAuditing">if set to <c>true</c> [enable auditing].</param> /// <returns></returns> protected virtual List<ContextItem> RockPreSave( DbContext dbContext, PersonAlias personAlias, bool enableAuditing = false ) { int? personAliasId = null; if ( personAlias != null ) { personAliasId = personAlias.Id; } var preSavedEntities = new HashSet<Guid>(); // First loop through all models calling the PreSaveChanges foreach ( var entry in dbContext.ChangeTracker.Entries() .Where( c => c.Entity is IEntity && ( c.State == EntityState.Added || c.State == EntityState.Modified || c.State == EntityState.Deleted ) ) ) { if ( entry.Entity is IModel ) { var model = entry.Entity as IModel; model.PreSaveChanges( this, entry ); if ( !preSavedEntities.Contains( model.Guid ) ) { preSavedEntities.Add( model.Guid ); } } } // Then loop again, as new models may have been added by PreSaveChanges events var updatedItems = new List<ContextItem>(); foreach ( var entry in dbContext.ChangeTracker.Entries() .Where( c => c.Entity is IEntity && ( c.State == EntityState.Added || c.State == EntityState.Modified || c.State == EntityState.Deleted ) ) ) { // Cast entry as IEntity var entity = entry.Entity as IEntity; // Get the context item to track audits var contextItem = new ContextItem( entity, entry ); // If entity was added or modified, update the Created/Modified fields if ( entry.State == EntityState.Added || entry.State == EntityState.Modified ) { // instead of passing "true" the trigger model and UI would support a // on-value-changed checkbox (or perhaps it should be the default/only behavior) // and its value would be passed in to the onValueChange if ( !TriggerWorkflows( contextItem, WorkflowTriggerType.PreSave, personAlias ) ) { return null; } if ( entry.Entity is IModel ) { var model = entry.Entity as IModel; if ( !preSavedEntities.Contains( model.Guid ) ) { model.PreSaveChanges( this, entry ); } // Update Guid/Created/Modified person and times if ( entry.State == EntityState.Added ) { if ( !model.CreatedDateTime.HasValue ) { model.CreatedDateTime = RockDateTime.Now; } if ( !model.CreatedByPersonAliasId.HasValue ) { model.CreatedByPersonAliasId = personAliasId; } if ( model.Guid == Guid.Empty ) { model.Guid = Guid.NewGuid(); } model.ModifiedDateTime = RockDateTime.Now; model.ModifiedByPersonAliasId = personAliasId; } else if ( entry.State == EntityState.Modified ) { model.ModifiedDateTime = RockDateTime.Now; model.ModifiedByPersonAliasId = personAliasId; } } } else if ( entry.State == EntityState.Deleted ) { if ( !TriggerWorkflows( contextItem, WorkflowTriggerType.PreDelete, personAlias ) ) { return null; } } if ( enableAuditing ) { try { GetAuditDetails( dbContext, contextItem, personAliasId ); } catch ( SystemException ex ) { ExceptionLogService.LogException( ex, null ); } } updatedItems.Add( contextItem ); } return updatedItems; }
/// <summary> /// Saves the tag values that user entered for the entity ( /// </summary> /// <param name="personAlias">The person alias.</param> public void SaveTagValues(PersonAlias personAlias) { int? currentPersonId = null; if (personAlias != null) { currentPersonId = personAlias.PersonId; } if ( EntityGuid != Guid.Empty ) { var rockContext = new RockContext(); var tagService = new TagService( rockContext ); var taggedItemService = new TaggedItemService( rockContext ); // Get the existing tags for this entity type var existingTags = tagService.Get( EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId ).ToList(); // Get the existing tagged items for this entity var existingTaggedItems = taggedItemService.Get( EntityTypeId, EntityQualifierColumn, EntityQualifierValue, currentPersonId, EntityGuid ); // Get tag values after user edit var currentTags = new List<Tag>(); foreach ( var value in this.Text.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ) ) { string tagName = value; if ( tagName.Contains( '^' ) ) { tagName = tagName.Split( new char[] { '^' }, StringSplitOptions.RemoveEmptyEntries )[0]; } // If this is a new tag, create it Tag tag = existingTags.FirstOrDefault( t => t.Name.Equals( tagName, StringComparison.OrdinalIgnoreCase ) ); if ( tag == null && currentPersonId != null ) { tag = new Tag(); tag.EntityTypeId = EntityTypeId; tag.EntityTypeQualifierColumn = EntityQualifierColumn; tag.EntityTypeQualifierValue = EntityQualifierValue; tag.OwnerPersonAliasId = personAlias != null ? personAlias.Id : (int?)null; tag.Name = tagName; } if ( tag != null ) { currentTags.Add( tag ); } } rockContext.SaveChanges(); // Delete any tagged items that user removed var names = currentTags.Select( t => t.Name ).ToList(); foreach ( var taggedItem in existingTaggedItems) { if ( !names.Contains( taggedItem.Tag.Name, StringComparer.OrdinalIgnoreCase ) ) { taggedItemService.Delete( taggedItem ); } } rockContext.SaveChanges(); // Add any tagged items that user added names = existingTaggedItems.Select( t => t.Tag.Name ).ToList(); foreach ( var tag in currentTags) { if ( !names.Contains( tag.Name, StringComparer.OrdinalIgnoreCase ) ) { var taggedItem = new TaggedItem(); taggedItem.TagId = tag.Id; taggedItem.EntityGuid = EntityGuid; taggedItemService.Add( taggedItem ); } } rockContext.SaveChanges(); } }
/// <summary> /// Launches the workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="connectionWorkflow">The connection workflow.</param> /// <param name="name">The name.</param> private void LaunchWorkflow( RockContext rockContext, Attendance attendance, PersonAlias pagePersonAlias, WorkflowType pageWorkflowType ) { if ( pageWorkflowType != null ) { var workflow = Rock.Model.Workflow.Activate( pageWorkflowType, pageWorkflowType.WorkTerm, rockContext ); if ( workflow != null ) { workflow.SetAttributeValue( "Person", attendance.PersonAlias.Guid ); workflow.SetAttributeValue( "PagePerson", pagePersonAlias.Guid ); var workflowService = new Rock.Model.WorkflowService( rockContext ); List<string> workflowErrors; if ( workflowService.Process( workflow, attendance, out workflowErrors ) ) { if ( workflow.Id != 0 ) { if ( workflow.HasActiveEntryForm( CurrentPerson ) ) { var qryParam = new Dictionary<string, string>(); qryParam.Add( "WorkflowTypeId", pageWorkflowType.Id.ToString() ); qryParam.Add( "WorkflowId", workflow.Id.ToString() ); NavigateToLinkedPage( "WorkflowEntryPage", qryParam ); } else { mdWorkflowLaunched.Show( string.Format( "A '{0}' workflow has been started.", pageWorkflowType.Name ), ModalAlertType.Information ); } } else { mdWorkflowLaunched.Show( string.Format( "A '{0}' workflow was processed (but not persisted).", pageWorkflowType.Name ), ModalAlertType.Information ); } } else { mdWorkflowLaunched.Show( "Workflow Processing Error(s):<ul><li>" + workflowErrors.AsDelimited( "</li><li>" ) + "</li></ul>", ModalAlertType.Information ); } return; } } Dictionary<string, string> qParams = new Dictionary<string, string>(); qParams.Add( "AttendanceId", attendance.Id.ToString() ); qParams.Add( "PagePersonId", pagePersonAlias.Person.Id.ToString() ); NavigateToLinkedPage( "WorkflowEntryPage", qParams ); }
/// <summary> /// Populates the <see cref="Rock.Model.ExceptionLog" /> entity with the exception data. /// </summary> /// <param name="ex">The <see cref="System.Exception" /> to log.</param> /// <param name="context">The <see cref="System.Web.HttpContext" />.</param> /// <param name="pageId">An <see cref="System.Int32" /> containing the Id of the <see cref="Rock.Model.Page" /> where the exception occurred. /// This value is nullable.</param> /// <param name="siteId">An <see cref="System.Int32" /> containing the Id the <see cref="Rock.Model.Site" /> where the exception occurred. /// This value is nullable.</param> /// <param name="personAlias">The person alias.</param> /// <returns></returns> private static ExceptionLog PopulateExceptionLog( Exception ex, HttpContext context, int? pageId, int? siteId, PersonAlias personAlias ) { int? personAliasId = null; if (personAlias != null) { personAliasId = personAlias.Id; } string exceptionMessage = ex.Message; if ( ex is System.Data.SqlClient.SqlException ) { var sqlEx = ex as System.Data.SqlClient.SqlException; var sqlErrorList = sqlEx.Errors.OfType<System.Data.SqlClient.SqlError>().ToList().Select(a => string.Format("{0}: Line {1}", a.Procedure, a.LineNumber)); if ( sqlErrorList.Any() ) { exceptionMessage += string.Format( "[{0}]", sqlErrorList.ToList().AsDelimited(", ") ); } } var exceptionLog = new ExceptionLog { SiteId = siteId, PageId = pageId, HasInnerException = ex.InnerException != null, ExceptionType = ex.GetType().ToString(), Description = exceptionMessage, Source = ex.Source, StackTrace = ex.StackTrace, Guid = Guid.NewGuid(), CreatedByPersonAliasId = personAliasId, ModifiedByPersonAliasId = personAliasId, CreatedDateTime = RockDateTime.Now, ModifiedDateTime = RockDateTime.Now, ModifiedAuditValuesAlreadyUpdated = true }; if ( exceptionLog.StackTrace == null ) { try { // if the Exception didn't include a StackTrace, manually grab it var stackTrace = new System.Diagnostics.StackTrace( 2 ); exceptionLog.StackTrace = stackTrace.ToString(); } catch { // ignore } } try { ex.Data.Add( "ExceptionLogGuid", exceptionLog.Guid ); } catch { // ignore } try { // If current HttpContext is null, return early. if ( context == null ) { return exceptionLog; } // If current HttpContext is available, populate its information as well. var request = context.Request; StringBuilder cookies = new StringBuilder(); var cookieList = request.Cookies; if ( cookieList.Count > 0 ) { cookies.Append( "<table class=\"cookies exception-table\">" ); foreach ( string cookie in cookieList ) { var httpCookie = cookieList[cookie]; if ( httpCookie != null ) cookies.Append( "<tr><td><b>" + cookie + "</b></td><td>" + httpCookie.Value.EncodeHtml() + "</td></tr>" ); } cookies.Append( "</table>" ); } StringBuilder formItems = new StringBuilder(); var formList = request.Form; if ( formList.Count > 0 ) { formItems.Append( "<table class=\"form-items exception-table\">" ); foreach ( string formItem in formList ) { formItems.Append( "<tr><td><b>" + formItem + "</b></td><td>" + formList[formItem].EncodeHtml() + "</td></tr>" ); } formItems.Append( "</table>" ); } StringBuilder serverVars = new StringBuilder(); var serverVarList = request.ServerVariables; if ( serverVarList.Count > 0 ) { serverVars.Append( "<table class=\"server-variables exception-table\">" ); foreach ( string serverVar in serverVarList ) serverVars.Append( "<tr><td><b>" + serverVar + "</b></td><td>" + serverVarList[serverVar].EncodeHtml() + "</td></tr>" ); serverVars.Append( "</table>" ); } exceptionLog.Cookies = cookies.ToString(); exceptionLog.StatusCode = context.Response.StatusCode.ToString(); exceptionLog.PageUrl = request.Url.ToString(); exceptionLog.ServerVariables = serverVars.ToString(); exceptionLog.QueryString = request.Url.Query; exceptionLog.Form = formItems.ToString(); } catch { // Intentionally do nothing } return exceptionLog; }
/// <summary> /// Checks the database for existing import data. /// returns false if an error occurred /// </summary> private bool LoadExistingData( string importUser ) { //try //{ var lookupContext = new RockContext(); var personService = new PersonService( lookupContext ); var importPerson = personService.GetByFullName( importUser, includeDeceased: false, allowFirstNameOnly: true ).FirstOrDefault(); if ( importPerson == null ) { importPerson = personService.Queryable().FirstOrDefault(); if ( importPerson == null ) { LogException( "CheckExistingImport", "The named import user was not found, and none could be created." ); return false; } } ImportPersonAlias = new PersonAliasService( lookupContext ).Get( importPerson.Id ); PersonEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id; FamilyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; ReportProgress( 0, "Checking for existing people..." ); ImportedPeople = new GroupService( lookupContext ).GetByGroupTypeId( FamilyGroupTypeId ).Where( n => n.ForeignId != null ).ToList(); CampusList = new CampusService( lookupContext ).Queryable().ToList(); return true; //} //catch ( Exception ex ) //{ // LogException( "CheckExistingImport", ex.ToString() ); // return false; //} }
/// <summary> /// Reads new values entered by the user for the field (as PersonAlias.Guid) /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public override string GetEditValue( System.Web.UI.Control control, Dictionary<string, ConfigurationValue> configurationValues ) { PersonPicker ppPerson = control as PersonPicker; string result = null; if ( ppPerson != null ) { Guid personGuid = Guid.Empty; int? personId = ppPerson.PersonId; if ( personId.HasValue ) { var rockContext = new RockContext(); var personAliasService = new PersonAliasService( rockContext ); var personAlias = personAliasService.Queryable() .Where( a => a.AliasPersonId == personId ) .FirstOrDefault(); if ( personAlias != null ) { result = personAlias.Guid.ToString(); } else { // If the personId is valid, there should be a personAlias with the AliasPersonID equal // to that personId. If there isn't for some reason, create it now... var person = new PersonService( rockContext ).Get( personId.Value ); if ( person != null ) { personAlias = new PersonAlias(); personAlias.Guid = Guid.NewGuid(); personAlias.AliasPersonId = person.Id; personAlias.AliasPersonGuid = person.Guid; personAlias.PersonId = person.Id; result = personAlias.Guid.ToString(); personAliasService.Add( personAlias ); rockContext.SaveChanges(); } } } } return result; }
private void SetPersonDateValue( Literal literal, PersonAlias personAlias, DateTime? datetime, string labelText ) { if ( personAlias != null ) { SetPersonDateValue( literal, personAlias.Person, datetime, labelText ); } }
/// <summary> /// Triggers all the workflows of the given triggerType for the given entity item. /// </summary> /// <param name="item">The item.</param> /// <param name="triggerType">Type of the trigger.</param> /// <param name="personAlias">The person alias.</param> /// <returns></returns> private bool TriggerWorkflows( ContextItem item, WorkflowTriggerType triggerType, PersonAlias personAlias ) { IEntity entity = item.Entity; Dictionary<string, PropertyInfo> properties = null; using ( var rockContext = new RockContext() ) { var workflowTypeService = new WorkflowTypeService( rockContext ); var workflowService = new WorkflowService( rockContext ); // Look at each trigger for this entity and for the given trigger type // and see if it's a match. foreach ( var trigger in TriggerCache.Triggers( entity.TypeName, triggerType ).Where( t => t.IsActive == true ) ) { bool match = true; // If a qualifier column was given, then we need to check the previous or current qualifier value // otherwise it's just an automatic match. if ( !string.IsNullOrWhiteSpace( trigger.EntityTypeQualifierColumn ) ) { // Get and cache the properties https://lotsacode.wordpress.com/2010/04/13/reflection-type-getproperties-and-performance/ // (Note: its possible that none of the triggers need them, so future TODO could be to // bypass all this in that case. if ( properties == null ) { properties = new Dictionary<string, PropertyInfo>(); foreach ( PropertyInfo propertyInfo in entity.GetType().GetProperties() ) { properties.Add( propertyInfo.Name.ToLower(), propertyInfo ); } } match = IsQualifierMatch( item, properties, trigger ); } // If we found a matching trigger, then fire it; otherwise do nothing. if ( match ) { // If it's one of the pre or immediate triggers, fire it immediately; otherwise queue it. if ( triggerType == WorkflowTriggerType.PreSave || triggerType == WorkflowTriggerType.PreDelete || triggerType == WorkflowTriggerType.ImmediatePostSave ) { var workflowType = workflowTypeService.Get( trigger.WorkflowTypeId ); if ( workflowType != null ) { var workflow = Rock.Model.Workflow.Activate( workflowType, trigger.WorkflowName ); List<string> workflowErrors; if ( !workflowService.Process( workflow, entity, out workflowErrors ) ) { SaveErrorMessages.AddRange( workflowErrors ); return false; } } } else { var transaction = new Rock.Transactions.WorkflowTriggerTransaction(); transaction.Trigger = trigger; transaction.Entity = entity.Clone(); transaction.PersonAlias = personAlias; Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); } } } } return true; }
/// <summary> /// Transforms the data from the dataset. /// </summary> /// <returns></returns> public override int TransformData( string importUser = null ) { ReportProgress( 0, "Starting import..." ); var rockContext = new RockContext(); var personService = new PersonService( rockContext ); var importPerson = personService.GetByFullName( importUser, allowFirstNameOnly: true ).FirstOrDefault(); if ( importPerson == null ) { importPerson = personService.Queryable().FirstOrDefault(); } ImportPersonAlias = new PersonAliasService( rockContext ).Get( importPerson.Id ); var tableList = TableNodes.Where( n => n.Checked != false ).ToList(); ReportProgress( 0, "Checking for existing attributes..." ); LoadExistingRockData(); ReportProgress( 0, "Checking for table dependencies..." ); bool isValidImport = ImportedPeople.Any() || tableList.Any( n => n.Name.Equals( "Individual_Household" ) ); var tableDependencies = new List<string>(); tableDependencies.Add( "Batch" ); // needed to attribute contributions properly tableDependencies.Add( "Users" ); // needed for notes, user logins tableDependencies.Add( "Company" ); // needed to attribute any business items tableDependencies.Add( "Individual_Household" ); // needed for just about everything tableDependencies.Add("ActivityMinistry"); // needed for RLC and Attendance tableDependencies.Add("RLC"); // needed for Attendance if ( isValidImport ) { // Order tables so non-dependents are imported first if ( tableList.Any( n => tableDependencies.Contains( n.Name ) ) ) { tableList = tableList.OrderByDescending( n => tableDependencies.IndexOf( n.Name ) ).ToList(); } var scanner = new DataScanner( Database ); foreach ( var table in tableList ) { if ( !tableDependencies.Contains( table.Name ) ) { switch ( table.Name ) { case "Account": MapBankAccount( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Communication": MapCommunication( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Contribution": MapContribution( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Household_Address": MapFamilyAddress( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Notes": MapNotes( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Pledge": MapPledge( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Attribute": MapAttributes( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Groups": MapGroups( scanner.ScanTable( table.Name ).AsQueryable() ); break; //case "ActivityMinistry": // MapActivityMinistry( scanner.ScanTable( table.Name ).AsQueryable() ); // break; //case "RLC": // MapRLC( scanner.ScanTable( table.Name ).AsQueryable() ); // break; case "Attendance": MapAttendance( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "IndividualContactNotes": MapIndividualContactNotes( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "GiftednessProgram": MapGiftednessProgram( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "IndividualGiftedness": MapIndividualGiftedness( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "Authorizations": MapAuthorizations( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "ActivityAssignment": MapActivityAssignment( scanner.ScanTable( table.Name ).AsQueryable() ); break; case "GroupsAttendance": MapGroupsAttendance( scanner.ScanTable( table.Name ).AsQueryable() ); break; default: break; } } else { if ( table.Name == "Batch" ) { MapBatch( scanner.ScanTable( table.Name ).AsQueryable() ); } else if ( table.Name == "Company" ) { MapCompany( scanner.ScanTable( table.Name ).AsQueryable() ); } else if ( table.Name == "Individual_Household" ) { MapPerson( scanner.ScanTable( table.Name ).AsQueryable() ); } else if ( table.Name == "Users" ) { MapUsers( scanner.ScanTable( table.Name ).AsQueryable() ); } else if ( table.Name == "ActivityMinistry" ) { MapActivityMinistry( scanner.ScanTable( table.Name ).AsQueryable() ); } else if ( table.Name == "RLC" ) { MapRLC( scanner.ScanTable( table.Name ).AsQueryable() ); } } } ReportProgress( 100, "Import completed. " ); } else { ReportProgress( 0, "No imported people exist. Please include the Individual_Household table during the import." ); } return 0; // return total number of rows imported? }
/// <summary> /// Gets the inverse relationship. /// Returns the <see cref="Rock.Model.GroupMember" /> who has an inverse relationship to the provided <see cref="Rock.Model.GroupMember" />. /// </summary> /// <param name="groupMember">A <see cref="Rock.Model.GroupMember" /> representing the person to find the inverse relationship for.</param> /// <param name="createGroup">A <see cref="System.Boolean"/> flag indicating if a new <see cref="Rock.Model.Group"/> can be created /// for the person with the inverse relationship. </param> /// <param name="personAlias">The alias of the <see cref="Rock.Model.Person"/> who has the inverse relationship.</param> /// <returns> /// A <see cref="Rock.Model.GroupMember"/> representing the <see cref="Rock.Model.Person"/> with the inverse relationship. /// </returns> /// <remarks> /// In Rock, examples of inverse relationships include: Parent/Child, Can Check In/Check in By, Sibling/Sibling, Grandparent/Grandchild, etc. /// </remarks> public GroupMember GetInverseRelationship( GroupMember groupMember, bool createGroup, PersonAlias personAlias ) { var groupRole = groupMember.GroupRole; if ( groupRole == null ) { groupRole = Queryable() .Where( m => m.Id == groupMember.Id ) .Select( m => m.GroupRole ) .FirstOrDefault(); } if ( groupRole != null ) { if ( groupRole.Attributes == null ) { groupRole.LoadAttributes(); } if ( groupRole.Attributes.ContainsKey( "InverseRelationship" ) ) { Guid ownerRoleGuid = new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER ); var memberInfo = Queryable() .Where( m => m.GroupId == groupMember.GroupId && m.GroupRole.Guid.Equals( ownerRoleGuid ) ) .Select( m => new { PersonId = m.PersonId, RoleId = m.GroupRoleId } ) .FirstOrDefault(); int? ownerPersonId = null; int? ownerRoleId = null; if ( memberInfo != null ) { ownerPersonId = memberInfo.PersonId; ownerRoleId = memberInfo.RoleId; } if ( ownerPersonId.HasValue && ownerRoleId.HasValue ) { // Find related person's group var inverseGroup = Queryable() .Where( m => m.PersonId == groupMember.PersonId && m.Group.GroupTypeId == groupRole.GroupTypeId && m.GroupRole.Guid.Equals( ownerRoleGuid ) ) .Select( m => m.Group ) .FirstOrDefault(); if ( inverseGroup == null && createGroup ) { var ownerGroupMember = new GroupMember(); ownerGroupMember.PersonId = groupMember.PersonId; ownerGroupMember.GroupRoleId = ownerRoleId.Value; inverseGroup = new Group(); inverseGroup.Name = groupRole.GroupType.Name; inverseGroup.GroupTypeId = groupRole.GroupTypeId.Value; inverseGroup.Members.Add( ownerGroupMember ); } if ( inverseGroup != null ) { Guid inverseRoleGuid = Guid.Empty; if ( Guid.TryParse( groupRole.GetAttributeValue( "InverseRelationship" ), out inverseRoleGuid ) ) { var inverseGroupMember = Queryable() .Where( m => m.PersonId == ownerPersonId && m.GroupId == inverseGroup.Id && m.GroupRole.Guid.Equals( inverseRoleGuid ) ) .FirstOrDefault(); if ( inverseGroupMember == null ) { var inverseRole = new GroupTypeRoleService( (RockContext)Context ).Get( inverseRoleGuid ); if ( inverseRole != null ) { inverseGroupMember = new GroupMember(); inverseGroupMember.PersonId = ownerPersonId.Value; inverseGroupMember.Group = inverseGroup; inverseGroupMember.GroupRoleId = inverseRole.Id; Add( inverseGroupMember ); } } return inverseGroupMember; } } } } } return null; }
/// <summary> /// Checks the database for existing import data. /// returns false if an error occurred /// </summary> private bool LoadExistingData( string importUser ) { var lookupContext = new RockContext(); var personService = new PersonService( lookupContext ); var importPerson = personService.GetByFullName( importUser, includeDeceased: false, allowFirstNameOnly: true ).FirstOrDefault(); if ( importPerson == null ) { importPerson = personService.Queryable().FirstOrDefault(); if ( importPerson == null ) { LogException( "CheckExistingImport", "The named import user was not found, and none could be created." ); return false; } } ImportPersonAlias = new PersonAliasService( lookupContext ).Get( importPerson.Id ); PersonEntityTypeId = EntityTypeCache.Read( "Rock.Model.Person" ).Id; FamilyGroupTypeId = GroupTypeCache.GetFamilyGroupType().Id; ReportProgress( 0, "Checking for existing people..." ); // Don't track groups in this context, just use it as a static reference ImportedPeople = lookupContext.Groups.AsNoTracking().Where( g => g.GroupTypeId == FamilyGroupTypeId && g.ForeignId != null ).ToList(); CampusList = new CampusService( lookupContext ).Queryable().ToList(); return true; }
/// <summary> /// Populates the <see cref="Rock.Model.ExceptionLog" /> entity with the exception data. /// </summary> /// <param name="ex">The <see cref="System.Exception" /> to log.</param> /// <param name="context">The <see cref="System.Web.HttpContext" />.</param> /// <param name="pageId">An <see cref="System.Int32" /> containing the Id of the <see cref="Rock.Model.Page" /> where the exception occurred. /// This value is nullable.</param> /// <param name="siteId">An <see cref="System.Int32" /> containing the Id the <see cref="Rock.Model.Site" /> where the exception occurred. /// This value is nullable.</param> /// <param name="personAlias">The person alias.</param> /// <returns></returns> private static ExceptionLog PopulateExceptionLog( Exception ex, HttpContext context, int? pageId, int? siteId, PersonAlias personAlias ) { int? personAliasId = null; if (personAlias != null) { personAliasId = personAlias.Id; } var exceptionLog = new ExceptionLog { SiteId = siteId, PageId = pageId, HasInnerException = ex.InnerException != null, ExceptionType = ex.GetType().ToString(), Description = ex.Message, Source = ex.Source, StackTrace = ex.StackTrace, Guid = Guid.NewGuid(), CreatedByPersonAliasId = personAliasId, ModifiedByPersonAliasId = personAliasId, CreatedDateTime = RockDateTime.Now, ModifiedDateTime = RockDateTime.Now }; try { // If current HttpContext is null, return early. if ( context == null ) { return exceptionLog; } // If current HttpContext is available, populate its information as well. var request = context.Request; StringBuilder cookies = new StringBuilder(); var cookieList = request.Cookies; if ( cookieList.Count > 0 ) { cookies.Append( "<table class=\"cookies exception-table\">" ); foreach ( string cookie in cookieList ) { var httpCookie = cookieList[cookie]; if ( httpCookie != null ) cookies.Append( "<tr><td><b>" + cookie + "</b></td><td>" + httpCookie.Value + "</td></tr>" ); } cookies.Append( "</table>" ); } StringBuilder formItems = new StringBuilder(); var formList = request.Form; if ( formList.Count > 0 ) { formItems.Append( "<table class=\"form-items exception-table\">" ); foreach ( string formItem in formList ) formItems.Append( "<tr><td><b>" + formItem + "</b></td><td>" + formList[formItem] + "</td></tr>" ); formItems.Append( "</table>" ); } StringBuilder serverVars = new StringBuilder(); var serverVarList = request.ServerVariables; if ( serverVarList.Count > 0 ) { serverVars.Append( "<table class=\"server-variables exception-table\">" ); foreach ( string serverVar in serverVarList ) serverVars.Append( "<tr><td><b>" + serverVar + "</b></td><td>" + serverVarList[serverVar] + "</td></tr>" ); serverVars.Append( "</table>" ); } exceptionLog.Cookies = cookies.ToString(); exceptionLog.StatusCode = context.Response.StatusCode.ToString(); exceptionLog.PageUrl = request.Url.ToString(); exceptionLog.ServerVariables = serverVars.ToString(); exceptionLog.QueryString = request.Url.Query; exceptionLog.Form = formItems.ToString(); } catch { // Intentionally do nothing } return exceptionLog; }
public GroupMember GetInverseRelationship( GroupMember groupMember, bool createGroup, PersonAlias personAlias ) { return GetInverseRelationship( groupMember, createGroup ); }
/// <summary> /// Creates audit logs and/or triggers workflows for items that were changed /// </summary> /// <param name="updatedItems">The updated items.</param> /// <param name="personAlias">The person alias.</param> /// <param name="enableAuditing">if set to <c>true</c> [enable auditing].</param> protected virtual void RockPostSave( List<ContextItem> updatedItems, PersonAlias personAlias, bool enableAuditing = false ) { if ( enableAuditing ) { try { var audits = updatedItems.Select( i => i.Audit ).ToList(); if ( audits.Any( a => a.Details.Any() ) ) { var transaction = new Rock.Transactions.AuditTransaction(); transaction.Audits = audits; Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); } } catch ( SystemException ex ) { ExceptionLogService.LogException( ex, null ); } } foreach ( var item in updatedItems ) { if ( item.State == EntityState.Detached || item.State == EntityState.Deleted ) { TriggerWorkflows( item, WorkflowTriggerType.PostDelete, personAlias ); } else { TriggerWorkflows( item, WorkflowTriggerType.ImmediatePostSave, personAlias ); TriggerWorkflows( item, WorkflowTriggerType.PostSave, personAlias ); } } }