public void PersonService_GetAsync_ReturnsPersons() { //Arrange var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>(); var mockDbContextScope = new Mock<IDbContextReadOnlyScope>(); var mockEfDbContext = new Mock<EFDbContext>(); mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object); mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object); var mockAppUserManager = new Mock<IAppUserManager>(); var mockDbUserService = new Mock<DBUserService>(new object[] {mockDbContextScopeFac.Object, mockAppUserManager.Object, true }); var dbEntry1 = new Person { Id = "dummyEntryId1", FirstName = "First1", LastName = "Last1", IsActive_bl = false, Initials = "FLA1" }; var dbEntry2 = new Person { Id = "dummyEntryId2", FirstName = "First2", LastName = "Last2", IsActive_bl = true, Initials = "FLA2" }; var dbEntries = (new List<Person> { dbEntry1, dbEntry2 }).AsQueryable(); var mockDbSet = new Mock<DbSet<Person>>(); mockDbSet.As<IDbAsyncEnumerable<Person>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<Person>(dbEntries.GetEnumerator())); mockDbSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<Person>(dbEntries.Provider)); mockDbSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(dbEntries.Expression); mockDbSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(dbEntries.ElementType); mockDbSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(dbEntries.GetEnumerator()); mockEfDbContext.Setup(x => x.Persons).Returns(mockDbSet.Object); var personService = new PersonService(mockDbContextScopeFac.Object, "DummyUserId"); //Act var resultPersons = personService.GetAllAsync().Result; //Assert Assert.IsTrue(resultPersons.Count == 1); Assert.IsTrue(resultPersons[0].LastName.Contains("Last2")); }
public void ValidContractAdded() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); validatorFactory.Setup(x => x.IsValid(It.IsAny<object>(), It.IsAny<IList<IRule>>())).Returns(false); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var identifier = new MdmId { SystemName = "Test", Identifier = "A" }; var message = new CreateMappingRequest { EntityId = 12, Mapping = identifier }; var system = new MDM.SourceSystem { Name = "Test" }; var mapping = new PersonMapping { System = system, MappingValue = "A" }; validatorFactory.Setup(x => x.IsValid(It.IsAny<CreateMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true); mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.MdmId, PersonMapping>(identifier)).Returns(mapping); var person = new MDM.Person(); repository.Setup(x => x.FindOne<MDM.Person>(12)).Returns(person); // Act var candidate = (PersonMapping)service.CreateMapping(message); // Assert Assert.AreSame(mapping, candidate); repository.Verify(x => x.Save(person)); repository.Verify(x => x.Flush()); }
public void UnsuccessfulMatchReturnsNotFound() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var list = new List<PersonMapping>(); repository.Setup(x => x.Queryable<PersonMapping>()).Returns(list.AsQueryable()); var message = new GetRequest { EntityId = 0, }; // Act var contract = service.Request(message); // Assert Assert.IsNotNull(contract, "Contract null"); Assert.IsFalse(contract.IsValid, "Contract valid"); Assert.AreEqual(ErrorType.NotFound, contract.Error.Type, "ErrorType difers"); }
static void Main(string[] args) { Console.Write("Login: "******"Password: "******"Try to connect using login:{0} password:{1}", login, pass)); var authenticationService = new AuthenticationService(); var token = new UsernameToken("test_user", "12345678", PasswordOption.SendPlainText); authenticationService.RequestSoapContext.Security.Tokens.Add(token); var credentials = new Credentials(); credentials.Login = login; credentials.Password = pass; credentials.LanId = new decimal(1); credentials.AppCode = "I"; var sessionHash = authenticationService.authenticate(credentials); Console.WriteLine("Sessioh hash: {0}", sessionHash); var personService = new PersonService(); var user = personService.getCurrentUser(sessionHash); var projects = personService.getUserProjectsList(sessionHash, (decimal)user.Id); decimal projectId = 0; foreach (var project in projects) { Console.WriteLine("Project id: {0}, project name: {1}", project.Key, project.Value); if (project.Value.Equals("ABC-TST")) { projectId = (decimal)project.Key; personService.changeProject(sessionHash, projectId); } } if (projectId != 0) { var requirementService = new RequirementService(); var requirement = new Requirement { ItemName = "Test req", ParentItemId = projectId }; requirement = requirementService.addRequirement(sessionHash, requirement); if (requirement.Id != 0) { Console.WriteLine("Requirement was added with id: {0}", requirement.Id); } } else { Console.WriteLine("Project wasn't changed"); } Console.ReadLine(); authenticationService.invalidateSession(sessionHash); }
public void NullRequestErrors() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); // Act service.CrossMap(null); }
public void NullContractInvalid() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); validatorFactory.Setup(x => x.IsValid(It.IsAny<object>(), It.IsAny<IList<IRule>>())).Returns(false); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); // Act service.Create(null); }
public void Should_Get_Person() { //Arrange var expectedPerson = new Person { Id = 2, Name = "Rafael", Email = "*****@*****.**" }; var personService = new PersonService(new PersonRepositoryStub()); //Act var people = personService.GetPerson(expectedPerson.Id); //Assert Assert.AreEqual(expectedPerson.Id, people.Id); }
public void Should_Return_List_Of_Selected_Persons() { //Arrange var expectedPersonIdList = new List<int> { 1, 2 }; var personService = new PersonService(new PersonRepositoryStub()); //Act var personIdList = personService.GetPeople(expectedPersonIdList).Select(p => p.Id).ToList(); //Assert CollectionAssert.AreEqual(expectedPersonIdList, personIdList); }
public void InvalidContractNotSaved() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var contract = new EnergyTrading.MDM.Contracts.Sample.Person(); validatorFactory.Setup(x => x.IsValid(It.IsAny<object>(), It.IsAny<IList<IRule>>())).Returns(false); // Act service.Create(contract); }
public void EarlierVersionRaisesVersionConflict() { var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); validatorFactory.Setup(x => x.IsValid(It.IsAny<EnergyTrading.MDM.Contracts.Sample.Person>(), It.IsAny<IList<IRule>>())).Returns(true); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var cd = new EnergyTrading.MDM.Contracts.Sample.PersonDetails { Forename = "John", Surname = "Smith", Email = "*****@*****.**" }; var nexus = new EnergyTrading.Mdm.Contracts.SystemData { StartDate = new DateTime(2012, 1, 1) }; var contract = new EnergyTrading.MDM.Contracts.Sample.Person { Details = cd, MdmSystemData = nexus }; var details = new PersonDetails { Id = 2, FirstName = "Bill", LastName = "Jones", Email = "*****@*****.**" }; var entity = new Person(); entity.AddDetails(details); repository.Setup(x => x.FindOne<Person>(1)).Returns(entity); // Act service.Update(1, 1, contract); }
public void ValidContractIsSaved() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var person = new MDM.Person(); var contract = new EnergyTrading.MDM.Contracts.Sample.Person(); validatorFactory.Setup(x => x.IsValid(It.IsAny<EnergyTrading.MDM.Contracts.Sample.Person>(), It.IsAny<IList<IRule>>())).Returns(true); mappingEngine.Setup(x => x.Map<EnergyTrading.MDM.Contracts.Sample.Person, MDM.Person>(contract)).Returns(person); // Act var expected = service.Create(contract); // Assert Assert.AreSame(expected, person, "Person differs"); repository.Verify(x => x.Add(person)); repository.Verify(x => x.Flush()); }
public void ValidDetailsSaved() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var identifier = new MdmId { SystemName = "Test", Identifier = "A" }; var message = new AmendMappingRequest { MappingId = 12, Mapping = identifier, Version = 34 }; var start = new DateTime(2000, 12, 31); var finish = DateUtility.Round(SystemTime.UtcNow().AddDays(5)); var s1 = new MDM.SourceSystem { Name = "Test" }; var m1 = new PersonMapping { Id = 12, System = s1, MappingValue = "1", Version = 34UL.GetVersionByteArray(), Validity = new DateRange(start, DateUtility.MaxDate) }; var m2 = new PersonMapping { Id = 12, System = s1, MappingValue = "1", Validity = new DateRange(start, finish) }; // NB We deliberately bypasses the business logic var person = new MDM.Person(); m1.Person = person; person.Mappings.Add(m1); validatorFactory.Setup(x => x.IsValid(It.IsAny<AmendMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true); repository.Setup(x => x.FindOne<PersonMapping>(12)).Returns(m1); mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.MdmId, PersonMapping>(identifier)).Returns(m2); // Act service.UpdateMapping(message); // Assert // NB Don't verify result of Update - already covered by PersonMappingFixture repository.Verify(x => x.Save(person)); repository.Verify(x => x.Flush()); }
public void EntityNotFound() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var cd = new EnergyTrading.MDM.Contracts.Sample.PersonDetails { Forename = "John", Surname = "Smith", Email = "*****@*****.**" }; var nexus = new EnergyTrading.Mdm.Contracts.SystemData { StartDate = new DateTime(2012, 1, 1) }; var contract = new EnergyTrading.MDM.Contracts.Sample.Person { Details = cd, MdmSystemData = nexus }; validatorFactory.Setup(x => x.IsValid(It.IsAny<EnergyTrading.MDM.Contracts.Sample.Person>(), It.IsAny<IList<IRule>>())).Returns(true); // Act var response = service.Update(1, 1, contract); // Assert Assert.IsNotNull(response, "Response is null"); Assert.IsFalse(response.IsValid, "Response is valid"); Assert.AreEqual(ErrorType.NotFound, response.Error.Type, "ErrorType differs"); }
public void EntityNotFound() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var message = new CreateMappingRequest { EntityId = 12, Mapping = new MdmId { SystemName = "Test", Identifier = "A" } }; validatorFactory.Setup(x => x.IsValid(It.IsAny<CreateMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true); // Act var candidate = service.CreateMapping(message); // Assert Assert.IsNull(candidate); }
public static void Main(string[] args) { SourceService sourceService = new SourceService("http://*****:*****@WebFault."); } catch (SoapException e) { //fall through } relationshipService.Touch(); AssertionService assertionService = new AssertionService("http://localhost:8080/full/AssertionServiceService"); Assertion[] assertions = assertionService.ReadAssertions(); Assertion gender = assertions[0]; Assert.AreEqual("gender",gender.Id); Assert.IsTrue(gender is Gender); Assertion name = assertions[1]; Assert.AreEqual("name",name.Id); Assert.IsTrue(name is Name); }
/// <summary> /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e) { if (RegistrantState != null) { RockContext rockContext = new RockContext(); var personService = new PersonService(rockContext); var registrantService = new RegistrationRegistrantService(rockContext); var registrantFeeService = new RegistrationRegistrantFeeService(rockContext); var registrationTemplateFeeService = new RegistrationTemplateFeeService(rockContext); RegistrationRegistrant registrant = null; if (RegistrantState.Id > 0) { registrant = registrantService.Get(RegistrantState.Id); } var previousRegistrantPersonIds = registrantService.Queryable().Where(a => a.RegistrationId == RegistrantState.RegistrationId) .Where(r => r.PersonAlias != null) .Select(r => r.PersonAlias.PersonId) .ToList(); bool newRegistrant = false; var registrantChanges = new List <string>(); if (registrant == null) { newRegistrant = true; registrant = new RegistrationRegistrant(); registrant.RegistrationId = RegistrantState.RegistrationId; registrantService.Add(registrant); registrantChanges.Add("Created Registrant"); } if (!registrant.PersonAliasId.Equals(ppPerson.PersonAliasId)) { string prevPerson = (registrant.PersonAlias != null && registrant.PersonAlias.Person != null) ? registrant.PersonAlias.Person.FullName : string.Empty; string newPerson = ppPerson.PersonName; newRegistrant = true; History.EvaluateChange(registrantChanges, "Person", prevPerson, newPerson); } int?personId = ppPerson.PersonId.Value; registrant.PersonAliasId = ppPerson.PersonAliasId.Value; // Get the name of registrant for history string registrantName = "Unknown"; if (ppPerson.PersonId.HasValue) { var person = personService.Get(ppPerson.PersonId.Value); if (person != null) { registrantName = person.FullName; } } // set their status (wait list / registrant) registrant.OnWaitList = !tglWaitList.Checked; History.EvaluateChange(registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal()); registrant.Cost = cbCost.Text.AsDecimal(); History.EvaluateChange(registrantChanges, "Discount Applies", registrant.DiscountApplies, cbDiscountApplies.Checked); registrant.DiscountApplies = cbDiscountApplies.Checked; if (!Page.IsValid) { return; } // Remove/delete any registrant fees that are no longer in UI with quantity foreach (var dbFee in registrant.Fees.ToList()) { if (!RegistrantState.FeeValues.Keys.Contains(dbFee.RegistrationTemplateFeeId) || RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] == null || !RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] .Any(f => f.Option == dbFee.Option && f.Quantity > 0)) { registrantChanges.Add(string.Format("Removed '{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}", dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option)); registrant.Fees.Remove(dbFee); registrantFeeService.Delete(dbFee); } } // Add/Update any of the fees from UI foreach (var uiFee in RegistrantState.FeeValues.Where(f => f.Value != null)) { foreach (var uiFeeOption in uiFee.Value) { var dbFee = registrant.Fees .Where(f => f.RegistrationTemplateFeeId == uiFee.Key && f.Option == uiFeeOption.Option) .FirstOrDefault(); if (dbFee == null) { dbFee = new RegistrationRegistrantFee(); dbFee.RegistrationTemplateFeeId = uiFee.Key; dbFee.Option = uiFeeOption.Option; registrant.Fees.Add(dbFee); } var templateFee = dbFee.RegistrationTemplateFee; if (templateFee == null) { templateFee = registrationTemplateFeeService.Get(uiFee.Key); } string feeName = templateFee != null ? templateFee.Name : "Fee"; if (!string.IsNullOrWhiteSpace(uiFeeOption.Option)) { feeName = string.Format("{0} ({1})", feeName, uiFeeOption.Option); } if (dbFee.Id <= 0) { registrantChanges.Add(feeName + " Fee Added"); } History.EvaluateChange(registrantChanges, feeName + " Quantity", dbFee.Quantity, uiFeeOption.Quantity); dbFee.Quantity = uiFeeOption.Quantity; History.EvaluateChange(registrantChanges, feeName + " Cost", dbFee.Cost, uiFeeOption.Cost); dbFee.Cost = uiFeeOption.Cost; } } if (TemplateState.RequiredSignatureDocumentTemplate != null) { var person = new PersonService(rockContext).Get(personId.Value); var documentService = new SignatureDocumentService(rockContext); var binaryFileService = new BinaryFileService(rockContext); SignatureDocument document = null; int?signatureDocumentId = hfSignedDocumentId.Value.AsIntegerOrNull(); int?binaryFileId = fuSignedDocument.BinaryFileId; if (signatureDocumentId.HasValue) { document = documentService.Get(signatureDocumentId.Value); } if (document == null && binaryFileId.HasValue) { var instance = new RegistrationInstanceService(rockContext).Get(RegistrationInstanceId); document = new SignatureDocument(); document.SignatureDocumentTemplateId = TemplateState.RequiredSignatureDocumentTemplate.Id; document.AppliesToPersonAliasId = registrant.PersonAliasId.Value; document.AssignedToPersonAliasId = registrant.PersonAliasId.Value; document.Name = string.Format("{0}_{1}", (instance != null ? instance.Name : TemplateState.Name), (person != null ? person.FullName.RemoveSpecialCharacters() : string.Empty)); document.Status = SignatureDocumentStatus.Signed; document.LastStatusDate = RockDateTime.Now; documentService.Add(document); } if (document != null) { int?origBinaryFileId = document.BinaryFileId; document.BinaryFileId = binaryFileId; if (origBinaryFileId.HasValue && origBinaryFileId.Value != document.BinaryFileId) { // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up var oldBinaryFile = binaryFileService.Get(origBinaryFileId.Value); if (oldBinaryFile != null && !oldBinaryFile.IsTemporary) { oldBinaryFile.IsTemporary = true; } } // ensure the IsTemporary is set to false on binaryFile associated with this document if (document.BinaryFileId.HasValue) { var binaryFile = binaryFileService.Get(document.BinaryFileId.Value); if (binaryFile != null && binaryFile.IsTemporary) { binaryFile.IsTemporary = false; } } } } if (!registrant.IsValid) { // Controls will render the error messages return; } // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges() rockContext.WrapTransaction(() => { rockContext.SaveChanges(); registrant.LoadAttributes(); foreach (var field in TemplateState.Forms .SelectMany(f => f.Fields .Where(t => t.FieldSource == RegistrationFieldSource.RegistrationAttribute && t.AttributeId.HasValue))) { var attribute = AttributeCache.Read(field.AttributeId.Value); if (attribute != null) { string originalValue = registrant.GetAttributeValue(attribute.Key); var fieldValue = RegistrantState.FieldValues .Where(f => f.Key == field.Id) .Select(f => f.Value.FieldValue) .FirstOrDefault(); string newValue = fieldValue != null ? fieldValue.ToString() : string.Empty; if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim()) { string formattedOriginalValue = string.Empty; if (!string.IsNullOrWhiteSpace(originalValue)) { formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false); } string formattedNewValue = string.Empty; if (!string.IsNullOrWhiteSpace(newValue)) { formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false); } History.EvaluateChange(registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue); } if (fieldValue != null) { registrant.SetAttributeValue(attribute.Key, fieldValue.ToString()); } } } registrant.SaveAttributeValues(rockContext); }); if (newRegistrant && TemplateState.GroupTypeId.HasValue && ppPerson.PersonId.HasValue) { using (var newRockContext = new RockContext()) { var reloadedRegistrant = new RegistrationRegistrantService(newRockContext).Get(registrant.Id); if (reloadedRegistrant != null && reloadedRegistrant.Registration != null && reloadedRegistrant.Registration.Group != null && reloadedRegistrant.Registration.Group.GroupTypeId == TemplateState.GroupTypeId.Value) { int?groupRoleId = TemplateState.GroupMemberRoleId.HasValue ? TemplateState.GroupMemberRoleId.Value : reloadedRegistrant.Registration.Group.GroupType.DefaultGroupRoleId; if (groupRoleId.HasValue) { var groupMemberService = new GroupMemberService(newRockContext); var groupMember = groupMemberService .Queryable().AsNoTracking() .Where(m => m.GroupId == reloadedRegistrant.Registration.Group.Id && m.PersonId == reloadedRegistrant.PersonId && m.GroupRoleId == groupRoleId.Value) .FirstOrDefault(); if (groupMember == null) { groupMember = new GroupMember(); groupMemberService.Add(groupMember); groupMember.GroupId = reloadedRegistrant.Registration.Group.Id; groupMember.PersonId = ppPerson.PersonId.Value; groupMember.GroupRoleId = groupRoleId.Value; groupMember.GroupMemberStatus = TemplateState.GroupMemberStatus; newRockContext.SaveChanges(); registrantChanges.Add(string.Format("Registrant added to {0} group", reloadedRegistrant.Registration.Group.Name)); } else { registrantChanges.Add(string.Format("Registrant group member reference updated to existing person in {0} group", reloadedRegistrant.Registration.Group.Name)); } // Record this to the Person's and Registrants Notes and History... reloadedRegistrant.Registration.SavePersonNotesAndHistory(reloadedRegistrant.Registration.PersonAlias.Person, this.CurrentPersonAliasId, previousRegistrantPersonIds); reloadedRegistrant.GroupMemberId = groupMember.Id; newRockContext.SaveChanges(); } } } } HistoryService.SaveChanges( rockContext, typeof(Registration), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registrant.RegistrationId, registrantChanges, "Registrant: " + registrantName, null, null); } NavigateToRegistration(); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="context">The context.</param> /// <param name="entityIdProperty">The entity identifier property.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection) { var settings = new GroupParticipationSelectSettings(selection); // // Define Candidate Groups. // // Get the Group Data View that defines the set of candidates from which matching Groups can be selected. var dataView = DataComponentSettingsHelper.GetDataViewForFilterComponent(settings.DataViewGuid, context); // Evaluate the Data View that defines the candidate Groups. var groupService = new GroupService(context); var groupQuery = groupService.Queryable(); if (dataView != null) { groupQuery = DataComponentSettingsHelper.FilterByDataView(groupQuery, dataView, groupService); } else { // Apply a default Group filter to only show Groups that would be visible in a Group List. groupQuery = groupQuery.Where(x => x.GroupType.ShowInGroupList); } var groupKeys = groupQuery.Select(x => x.Id); // // Construct the Query to return the list of Group Members matching the filter conditions. // var groupMemberQuery = new GroupMemberService(context).Queryable(); // Filter By Group. groupMemberQuery = groupMemberQuery.Where(x => groupKeys.Contains(x.GroupId)); // Filter By Group Role Type. switch (settings.RoleType) { case RoleTypeSpecifier.Member: groupMemberQuery = groupMemberQuery.Where(x => !x.GroupRole.IsLeader); break; case RoleTypeSpecifier.Leader: groupMemberQuery = groupMemberQuery.Where(x => x.GroupRole.IsLeader); break; } // Filter by Group Member Status. if (settings.MemberStatus.HasValue) { groupMemberQuery = groupMemberQuery.Where(x => x.GroupMemberStatus == settings.MemberStatus.Value); } // // Create a Select Expression to return the requested values. // // Set the Output Format of the field. Expression selectExpression; if (settings.ListFormat == ListFormatSpecifier.YesNo) { // Define a Query to return True/False text indicating if the Person participates in any of the filtered Groups. // Note that the text must be returned as an Enumerable to satisfy the expected output of this field. var personGroupsQuery = new PersonService(context).Queryable() .Select(p => new List <string> { groupMemberQuery.Any(s => s.PersonId == p.Id) ? "Yes" : "No" }); selectExpression = SelectExpressionExtractor.Extract(personGroupsQuery, entityIdProperty, "p"); } else { // Define a Query to return the collection of filtered Groups for each Person. Expression <Func <Rock.Model.GroupMember, string> > outputExpression; if (settings.ListFormat == ListFormatSpecifier.GroupOnly) { outputExpression = ((m => m.Group.Name)); } else { outputExpression = ((m => m.Group.Name + " [" + m.GroupRole.Name + "]")); } // Define a Query to return the collection of filtered Groups for each Person. var personGroupsQuery = new PersonService(context).Queryable() .Select(p => groupMemberQuery.Where(s => s.PersonId == p.Id) .OrderBy(x => x.Group.Name) .ThenBy(x => x.GroupRole.Name) .Select(outputExpression).AsEnumerable()); selectExpression = SelectExpressionExtractor.Extract(personGroupsQuery, entityIdProperty, "p"); } return(selectExpression); }
/// <summary> /// Shows the detail. /// </summary> /// <param name="businessId">The business identifier.</param> public void ShowDetail(int businessId) { var rockContext = new RockContext(); // Load the Campus drop down ddlCampus.Items.Clear(); ddlCampus.Items.Add(new ListItem(string.Empty, string.Empty)); foreach (var campus in CampusCache.All()) { ListItem li = new ListItem(campus.Name, campus.Id.ToString()); ddlCampus.Items.Add(li); } Person business = null; // A business is a person if (!businessId.Equals(0)) { business = new PersonService(rockContext).Get(businessId); pdAuditDetails.SetEntity(business, ResolveRockUrl("~")); } if (business == null) { business = new Person { Id = 0, Guid = Guid.NewGuid() }; // hide the panel drawer that show created and last modified dates pdAuditDetails.Visible = false; } bool editAllowed = business.IsAuthorized(Authorization.EDIT, CurrentPerson); hfBusinessId.Value = business.Id.ToString(); bool readOnly = false; nbEditModeMessage.Text = string.Empty; if (!editAllowed || !IsUserAuthorized(Authorization.EDIT)) { readOnly = true; nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Person.FriendlyTypeName); } if (readOnly) { ShowSummary(businessId); } else { if (business.Id > 0) { ShowSummary(business.Id); } else { ShowEditDetails(business); } } BindContactListGrid(business); }
/// <summary> /// This will pull the api key generated in rock. The name of it needs to be AppRestKey. /// It can be changed whenever from the website, this function will pull it based on the name in case the key becomes compromised /// if it can't find it, it will return empty string and the request will return unauthorized /// </summary> /// <returns></returns> public static string APIKey() { var rc = new RockContext(); var u = new PersonService(rc).GetByFullName("AppRestKey", false); var key = ""; if (u.Count() > 0) { var restUser = u.First(); var userLoginService = new UserLoginService(rc); var userLogin = userLoginService.Queryable().Where(a => a.PersonId == restUser.Id).FirstOrDefault(); if (userLogin != null) { key = userLogin.ApiKey; } } return key; }
/// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> public void ProcessRequest(HttpContext context) { int?communicationId = context.Request.QueryString["c"].AsIntegerOrNull(); if (communicationId.HasValue) { var rockContext = new RockContext(); var communication = new CommunicationService(rockContext).Get(communicationId.Value); if (communication != null) { var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null); mergeFields.Add("Communication", communication); Person person = null; string encodedKey = context.Request.QueryString["p"]; if (!string.IsNullOrWhiteSpace(encodedKey)) { person = new PersonService(rockContext).GetByImpersonationToken(encodedKey, true, null); } if (person == null) { var principal = context.User; if (principal != null && principal.Identity != null) { var userLoginService = new Rock.Model.UserLoginService(new RockContext()); var userLogin = userLoginService.GetByUserName(principal.Identity.Name); if (userLogin != null) { var currentPerson = userLogin.Person; // if a person wasn't specified in the URL, then only show it if the current person has EDIT auth to the communication if (communication.IsAuthorized(Authorization.EDIT, currentPerson)) { person = currentPerson; } } } } if (person != null) { mergeFields.Add("Person", person); var recipient = new CommunicationRecipientService(rockContext).Queryable() .Where(r => r.CommunicationId == communication.Id && r.PersonAlias != null && r.PersonAlias.PersonId == person.Id) .FirstOrDefault(); if (recipient != null) { // Add any additional merge fields created through a report foreach (var mergeField in recipient.AdditionalMergeValues) { if (!mergeFields.ContainsKey(mergeField.Key)) { mergeFields.Add(mergeField.Key, mergeField.Value); } } } context.Response.ContentType = "text/html"; context.Response.Write(GetHtmlPreview(communication, mergeFields)); if (recipient != null) { // write an 'opened' interaction var interactionService = new InteractionService(rockContext); InteractionComponent interactionComponent = new InteractionComponentService(rockContext) .GetComponentByEntityId(Rock.SystemGuid.InteractionChannel.COMMUNICATION.AsGuid(), communication.Id, communication.Subject); rockContext.SaveChanges(); var ipAddress = Rock.Web.UI.RockPage.GetClientIpAddress(); var userAgent = context.Request.UserAgent ?? ""; UAParser.ClientInfo client = UAParser.Parser.GetDefault().Parse(userAgent); var clientOs = client.OS.ToString(); var clientBrowser = client.UserAgent.ToString(); var clientType = InteractionDeviceType.GetClientType(userAgent); interactionService.AddInteraction(interactionComponent.Id, recipient.Id, "Opened", "", recipient.PersonAliasId, RockDateTime.Now, clientBrowser, clientOs, clientType, userAgent, ipAddress, null); rockContext.SaveChanges(); } return; } } } context.Response.ContentType = "text/plain"; context.Response.Write("Sorry, the communication you requested does not exist, or you are not authorized to view it."); return; }
void gPeople_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var person = e.Row.DataItem as PersonSearchResult; if (person != null) { if (_inactiveStatus != null && person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == _inactiveStatus.Id) { e.Row.AddCssClass("inactive"); } if (person.IsDeceased) { e.Row.AddCssClass("deceased"); } string delimitedCampuses = string.Empty; if (person.CampusIds.Any()) { var campuses = new List <string>(); foreach (var campusId in person.CampusIds) { var campus = CampusCache.Get(campusId); if (campus != null) { campuses.Add(campus.Name); } } if (campuses.Any()) { delimitedCampuses = campuses.AsDelimited(", "); var lCampus = e.Row.FindControl("lCampus") as Literal; if (lCampus != null) { lCampus.Text = delimitedCampuses; } } } var lPerson = e.Row.FindControl("lPerson") as Literal; if (!person.IsBusiness) { StringBuilder sbPersonDetails = new StringBuilder(); sbPersonDetails.Append(string.Format("<div class=\"photo-round photo-round-sm pull-left\" data-original=\"{0}&w=100\" style=\"background-image: url('{1}');\"></div>", person.PhotoUrl, ResolveUrl("~/Assets/Images/person-no-photo-unknown.svg"))); sbPersonDetails.Append("<div class=\"pull-left margin-l-sm\">"); sbPersonDetails.Append(string.Format("<strong>{0}</strong> ", person.FullNameReversed)); sbPersonDetails.Append(string.Format("{0} ", Person.GetSignalMarkup(person.TopSignalColor, person.TopSignalIconCssClass))); sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\"><br>{0}</br></small>", delimitedCampuses)); sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\">{0}</small>", DefinedValueCache.GetName(person.ConnectionStatusValueId))); sbPersonDetails.Append(string.Format(" <small class=\"hidden-md hidden-lg\">{0}</small>", person.AgeFormatted)); foreach (Guid phGuid in _phoneTypeGuids) { var dv = DefinedValueCache.Get(phGuid); if (dv != null) { var pn = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == dv.Id); if (pn != null) { sbPersonDetails.Append(string.Format("<br/><small>{0}: {1}</small>", dv.Value.Left(1).ToUpper(), pn.Number)); } } } if (!string.IsNullOrWhiteSpace(person.Email)) { sbPersonDetails.Append(string.Format("<br/><small>{0}</small>", person.Email)); } // add home addresses foreach (var location in person.HomeAddresses) { if (string.IsNullOrWhiteSpace(location.Street1) && string.IsNullOrWhiteSpace(location.Street2) && string.IsNullOrWhiteSpace(location.City)) { continue; } string format = string.Empty; var countryValue = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid()) .DefinedValues .Where(v => v.Value.Equals(location.Country, StringComparison.OrdinalIgnoreCase)) .FirstOrDefault(); if (countryValue != null) { format = countryValue.GetAttributeValue("AddressFormat"); } if (!string.IsNullOrWhiteSpace(format)) { var dict = location.ToDictionary(); dict["Country"] = countryValue.Description; sbPersonDetails.Append(string.Format("<small><br>{0}</small>", format.ResolveMergeFields(dict).ConvertCrLfToHtmlBr().Replace("<br/><br/>", "<br/>"))); } else { sbPersonDetails.Append(string.Format(string.Format("<small><br>{0}<br>{1} {2}, {3} {4}</small>", location.Street1, location.Street2, location.City, location.State, location.PostalCode))); } } sbPersonDetails.Append("</div>"); lPerson.Text = sbPersonDetails.ToString(); if (_showSpouse) { using (var rockContext = new RockContext()) { var personRec = new PersonService(rockContext).Get(person.Id); if (personRec != null) { var lSpouse = e.Row.FindControl("lSpouse") as Literal; var spouse = personRec.GetSpouse(rockContext); if (lSpouse != null && spouse != null) { lSpouse.Text = spouse.FullName; } } } } if (_envelopeNumbers != null && _envelopeNumbers.ContainsKey(person.Id)) { var lEnvelopeNumber = e.Row.FindControl("lEnvelopeNumber") as Literal; if (lEnvelopeNumber != null) { lEnvelopeNumber.Text = _envelopeNumbers[person.Id]; } } } else { lPerson.Text = string.Format("{0}", person.LastName); } } } }
/// <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>(); var inactiveStatusValueId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE).Id; var guidPersonAttribute = GetAttributeValue(action, AttributeKey.Person).AsGuid(); Person person = GetPersonFromWorkflowAttribute(rockContext, action, guidPersonAttribute); if (person == null) { var message = string.Format("Person could not be found for selected value ('{0}')!", person.ToString()); errorMessages.Add(message); action.AddLogEntry(message, true); return(false); } // If the configured inactiveReasonGuid is not in the inactiveReasonDefinedValues, then // that guid is probably from an attribute and therefore we need to get the inactiveReasonGuid // from the workflow's attribute value instead. Guid inactiveReasonGuid = GetAttributeValue(action, AttributeKey.InactiveReason).AsGuid(); var inactiveReasonDefinedValues = DefinedTypeCache.Get(SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON.AsGuid()).DefinedValues; if (!inactiveReasonDefinedValues.Any(a => a.Guid == inactiveReasonGuid)) { var workflowAttributeValue = action.GetWorkflowAttributeValue(inactiveReasonGuid); if (workflowAttributeValue.IsNotNullOrWhiteSpace()) { inactiveReasonGuid = workflowAttributeValue.AsGuid(); } } // Now can we do our final check to ensure the guid is a valid inactive reason. if (!inactiveReasonDefinedValues.Any(a => a.Guid == inactiveReasonGuid)) { var message = string.Format("Inactive Reason could not be found for selected value ('{0}')!", inactiveReasonGuid.ToString()); errorMessages.Add(message); action.AddLogEntry(message, true); return(false); } var inactiveReasonValueId = inactiveReasonDefinedValues.First(a => a.Guid == inactiveReasonGuid).Id; string inactiveNote = GetAttributeValue(action, AttributeKey.InactiveNote); Guid guid = inactiveNote.AsGuid(); if (!guid.IsEmpty()) { inactiveNote = action.GetWorkflowAttributeValue(guid); } var personService = new PersonService(rockContext); var multiFamilyLogic = GetAttributeValue(action, AttributeKey.MultiFamilyLogic).AsInteger(); if (multiFamilyLogic == (int)LogicOption.InactivateIndividualsPrimaryFamily) { if (person.PrimaryFamily != null) { var familyMembers = person.PrimaryFamily.Members.Select(a => a.Person); foreach (var familyMember in familyMembers.Where(a => a.RecordStatusValueId != inactiveStatusValueId)) { personService.InactivatePerson(familyMember, DefinedValueCache.Get(inactiveReasonValueId), inactiveNote); } } } else if (multiFamilyLogic == ( int )LogicOption.InactivateIndividualsAllFamilies) { var familyMembers = person.GetFamilyMembers(true, rockContext).Select(a => a.Person).Distinct(); foreach (var familyMember in familyMembers.Where(a => a.RecordStatusValueId != inactiveStatusValueId)) { personService.InactivatePerson(familyMember, DefinedValueCache.Get(inactiveReasonValueId), inactiveNote); } } else { personService.InactivatePerson(person, DefinedValueCache.Get(inactiveReasonValueId), inactiveNote); } rockContext.SaveChanges(); action.AddLogEntry("Inactivate Family ran successfully."); return(true); }
/// <summary> /// Handles the Click event of the btnSend 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 btnSend_Click(object sender, EventArgs e) { var url = LinkedPageUrl("ConfirmationPage"); if (string.IsNullOrWhiteSpace(url)) { url = ResolveRockUrl("~/ConfirmAccount"); } var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson); mergeFields.Add("ConfirmAccountUrl", RootPath + url.TrimStart(new char[] { '/' })); var results = new List <IDictionary <string, object> >(); var rockContext = new RockContext(); var personService = new PersonService(rockContext); var userLoginService = new UserLoginService(rockContext); bool hasAccountWithPasswordResetAbility = false; List <string> accountTypes = new List <string>(); foreach (Person person in personService.GetByEmail(tbEmail.Text) .Where(p => p.Users.Any())) { var users = new List <UserLogin>(); foreach (UserLogin user in userLoginService.GetByPersonId(person.Id)) { if (user.EntityType != null) { var component = AuthenticationContainer.GetComponent(user.EntityType.Name); if (!component.RequiresRemoteAuthentication) { users.Add(user); hasAccountWithPasswordResetAbility = true; } accountTypes.Add(user.EntityType.FriendlyName); } } var resultsDictionary = new Dictionary <string, object>(); resultsDictionary.Add("Person", person); resultsDictionary.Add("Users", users); results.Add(resultsDictionary); } if (results.Count > 0 && hasAccountWithPasswordResetAbility) { mergeFields.Add("Results", results.ToArray()); var recipients = new List <RecipientData>(); recipients.Add(new RecipientData(tbEmail.Text, mergeFields)); Email.Send(GetAttributeValue("EmailTemplate").AsGuid(), recipients, ResolveRockUrlIncludeRoot("~/"), ResolveRockUrlIncludeRoot("~~/"), false); pnlEntry.Visible = false; pnlSuccess.Visible = true; } else if (results.Count > 0) { // the person has user accounts but none of them are allowed to have their passwords reset (Facebook/Google/etc) lWarning.Text = string.Format(@"<p>We were able to find the following accounts for this email, but none of them are able to be reset from this website.</p> <p>Accounts:<br /> {0}</p> <p>To create a new account with a username and password please see our <a href='{1}'>New Account</a> page.</p>" , string.Join(",", accountTypes) , ResolveRockUrl("~/NewAccount")); pnlWarning.Visible = true; } else { pnlWarning.Visible = true; } }
public PersonApiController(PersonService service) { _svc = service; }
public ActionResult DeleteConfirmed(ReasonViewModel vm) { if (ModelState.IsValid) { Person person = new PersonService(_unitOfWork).Find(vm.id); BusinessEntity businessentiry = _BusinessEntityService.Find(vm.id); Employee Employee = _EmployeeService.Find(vm.id); ActivityLog al = new ActivityLog() { ActivityType = (int)ActivityTypeContants.Deleted, CreatedBy = User.Identity.Name, CreatedDate = DateTime.Now, DocId = vm.id, UserRemark = vm.Reason, Narration = "Employee is deleted with Name:" + person.Name, DocTypeId = new DocumentTypeService(_unitOfWork).FindByName(TransactionDocCategoryConstants.SaleOrder).DocumentTypeId, UploadDate = DateTime.Now, }; new ActivityLogService(_unitOfWork).Create(al); //Then find Ledger Account associated with the above Person. LedgerAccount ledgeraccount = _AccountService.GetLedgerAccountFromPersonId(vm.id); _AccountService.Delete(ledgeraccount.LedgerAccountId); //Then find all the Person Address associated with the above Person. PersonAddress personaddress = _PersonAddressService.GetShipAddressByPersonId(vm.id); _PersonAddressService.Delete(personaddress.PersonAddressID); IEnumerable <PersonContact> personcontact = new PersonContactService(_unitOfWork).GetPersonContactIdListByPersonId(vm.id); //Mark ObjectState.Delete to all the Person Contact For Above Person. foreach (PersonContact item in personcontact) { new PersonContactService(_unitOfWork).Delete(item.PersonContactID); } IEnumerable <PersonBankAccount> personbankaccount = new PersonBankAccountService(_unitOfWork).GetPersonBankAccountIdListByPersonId(vm.id); //Mark ObjectState.Delete to all the Person Contact For Above Person. foreach (PersonBankAccount item in personbankaccount) { new PersonBankAccountService(_unitOfWork).Delete(item.PersonBankAccountID); } IEnumerable <PersonProcess> personProcess = new PersonProcessService(_unitOfWork).GetPersonProcessIdListByPersonId(vm.id); //Mark ObjectState.Delete to all the Person Process For Above Person. foreach (PersonProcess item in personProcess) { new PersonProcessService(_unitOfWork).Delete(item.PersonProcessId); } IEnumerable <PersonRegistration> personregistration = new PersonRegistrationService(_unitOfWork).GetPersonRegistrationIdListByPersonId(vm.id); //Mark ObjectState.Delete to all the Person Registration For Above Person. foreach (PersonRegistration item in personregistration) { new PersonRegistrationService(_unitOfWork).Delete(item.PersonRegistrationID); } // Now delete the Parent Employee _EmployeeService.Delete(Employee); _BusinessEntityService.Delete(businessentiry); new PersonService(_unitOfWork).Delete(person); try { _unitOfWork.Save(); } catch (Exception ex) { string message = _exception.HandleException(ex); ModelState.AddModelError("", message); return(PartialView("_Reason", vm)); } return(Json(new { success = true })); } return(PartialView("_Reason", vm)); }
/// <summary> /// Shows the summary. /// </summary> /// <param name="business">The business.</param> private void ShowSummary(int businessId) { SetEditMode(false); hfBusinessId.SetValue(businessId); lTitle.Text = "View Business".FormatAsHtmlTitle(); var business = new PersonService(new RockContext()).Get(businessId); if (business != null) { SetHeadingStatusInfo(business); var detailsLeft = new DescriptionList(); detailsLeft.Add("Business Name", business.LastName); if (business.GivingGroup != null) { detailsLeft.Add("Campus", business.GivingGroup.Campus); } if (business.RecordStatusReasonValue != null) { detailsLeft.Add("Record Status Reason", business.RecordStatusReasonValue); } lDetailsLeft.Text = detailsLeft.Html; var detailsRight = new DescriptionList(); // Get address var workLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK.AsGuid()); if (workLocationType != null) { if (business.GivingGroup != null) // Giving Group is a shortcut to Family Group for business { var location = business.GivingGroup.GroupLocations .Where(gl => gl.GroupLocationTypeValueId == workLocationType.Id) .Select(gl => gl.Location) .FirstOrDefault(); if (location != null) { detailsRight.Add("Address", location.GetFullStreetAddress().ConvertCrLfToHtmlBr()); } } } var workPhoneType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK.AsGuid()); if (workPhoneType != null) { var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == workPhoneType.Id); if (phoneNumber != null) { detailsRight.Add("Phone Number", phoneNumber.ToString()); } } var communicationLinkedPageValue = this.GetAttributeValue("CommunicationPage"); Rock.Web.PageReference communicationPageReference; if (communicationLinkedPageValue.IsNotNullOrWhiteSpace()) { communicationPageReference = new Rock.Web.PageReference(communicationLinkedPageValue); } else { communicationPageReference = null; } detailsRight.Add("Email Address", business.GetEmailTag(ResolveRockUrl("/"), communicationPageReference)); lDetailsRight.Text = detailsRight.Html; } }
public MediaElementInteraction PostWatchInteraction(MediaElementInteraction mediaInteraction) { var rockContext = Service.Context as RockContext; var personService = new PersonService(rockContext); var personAliasService = new PersonAliasService(rockContext); var interactionService = new InteractionService(rockContext); int?personAliasId; if (!IsWatchMapValid(mediaInteraction.WatchMap)) { var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"The WatchMap contains invalid characters."); throw new HttpResponseException(errorResponse); } // Get the person alias to associate with the interaction in // order of provided Person.Guid, then PersonAlias.Guid, then // the logged in Person. if (mediaInteraction.PersonGuid.HasValue) { personAliasId = personAliasService.GetPrimaryAliasId(mediaInteraction.PersonGuid.Value); } else if (mediaInteraction.PersonAliasGuid.HasValue) { personAliasId = personAliasService.GetId(mediaInteraction.PersonAliasGuid.Value); } else { personAliasId = GetPersonAliasId(rockContext); } var mediaElement = new MediaElementService(rockContext).GetNoTracking(mediaInteraction.MediaElementGuid); // Ensure we have our required MediaElement. if (mediaElement == null) { var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"The MediaElement could not be found."); throw new HttpResponseException(errorResponse); } // Get (or create) the component. var interactionChannelId = InteractionChannelCache.Get(SystemGuid.InteractionChannel.MEDIA_EVENTS).Id; var interactionComponentId = InteractionComponentCache.GetComponentIdByChannelIdAndEntityId(interactionChannelId, mediaElement.Id, mediaElement.Name); Interaction interaction = null; if (mediaInteraction.InteractionGuid.HasValue) { // Look for an existing Interaction by it's Guid and the // component it is supposed to show up under. But also // check that the RelatedEntityTypeId/RelatedEntityId values // are either null or match what was passed by the user. // Finally also make sure the Interaction Person Alias is // either the one for this user OR if there is a Person // record attached to that alias that the alias Id we have is // also attached to that Person record OR the interaction is // not tied to a person. interaction = interactionService.Queryable() .Where(a => a.Guid == mediaInteraction.InteractionGuid.Value && a.InteractionComponentId == interactionComponentId) .Where(a => !a.RelatedEntityTypeId.HasValue || !mediaInteraction.RelatedEntityTypeId.HasValue || a.RelatedEntityTypeId == mediaInteraction.RelatedEntityTypeId) .Where(a => !a.RelatedEntityId.HasValue || !mediaInteraction.RelatedEntityId.HasValue || a.RelatedEntityId == mediaInteraction.RelatedEntityId) .Where(a => !a.PersonAliasId.HasValue || a.PersonAliasId == personAliasId || a.PersonAlias.Person.Aliases.Any(b => b.Id == personAliasId)) .SingleOrDefault(); } if (interaction != null) { var watchedPercentage = CalculateWatchedPercentage(mediaInteraction.WatchMap); // Update the interaction data with the new watch map. var data = interaction.InteractionData.FromJsonOrNull <MediaWatchedInteractionData>() ?? new MediaWatchedInteractionData(); data.WatchMap = mediaInteraction.WatchMap; data.WatchedPercentage = watchedPercentage; interaction.InteractionData = data.ToJson(); interaction.InteractionLength = watchedPercentage; interaction.InteractionEndDateTime = RockDateTime.Now; interaction.PersonAliasId = interaction.PersonAliasId ?? personAliasId; if (mediaInteraction.RelatedEntityTypeId.HasValue) { interaction.RelatedEntityTypeId = mediaInteraction.RelatedEntityTypeId; } if (mediaInteraction.RelatedEntityId.HasValue) { interaction.RelatedEntityId = mediaInteraction.RelatedEntityId; } } else { // Generate the interaction data from the watch map. var data = new MediaWatchedInteractionData { WatchMap = mediaInteraction.WatchMap, WatchedPercentage = CalculateWatchedPercentage(mediaInteraction.WatchMap) }; interaction = interactionService.CreateInteraction(interactionComponentId, null, "Watch", string.Empty, data.ToJson(), personAliasId, RockDateTime.Now, null, null, null, null, null, null); interaction.InteractionEndDateTime = RockDateTime.Now; interaction.RelatedEntityTypeId = mediaInteraction.RelatedEntityTypeId; interaction.RelatedEntityId = mediaInteraction.RelatedEntityId; interactionService.Add(interaction); } rockContext.SaveChanges(); mediaInteraction.InteractionGuid = interaction.Guid; return(mediaInteraction); }
public MediaElementInteraction GetWatchInteraction([FromUri] Guid?mediaElementGuid = null, [FromUri] Guid?personGuid = null, Guid?personAliasGuid = null) { var rockContext = Service.Context as RockContext; var personService = new PersonService(rockContext); var personAliasService = new PersonAliasService(rockContext); var interactionService = new InteractionService(rockContext); int?personAliasId; // Get the person alias to associate with the interaction in // order of provided Person.Guid, then PersonAlias.Guid, then // the logged in Person. if (personGuid.HasValue) { personAliasId = personAliasService.GetPrimaryAliasId(personGuid.Value); } else if (personAliasGuid.HasValue) { personAliasId = personAliasService.GetId(personAliasGuid.Value); } else { personAliasId = GetPersonAliasId(rockContext); } // Verify we have a person alias, otherwise bail out. if (!personAliasId.HasValue) { var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"The personAliasId could not be determined."); throw new HttpResponseException(errorResponse); } MediaElement mediaElement = null; // In the future we might make MediaElementGuid optional so // perform the check this way rather than making it required // in the parameter list. if (mediaElementGuid.HasValue) { mediaElement = new MediaElementService(rockContext).GetNoTracking(mediaElementGuid.Value); } // Ensure we have our required MediaElement. if (mediaElement == null) { var errorResponse = Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"The MediaElement could not be found."); throw new HttpResponseException(errorResponse); } // Get (or create) the component. var interactionChannelId = InteractionChannelCache.Get(SystemGuid.InteractionChannel.MEDIA_EVENTS).Id; var interactionComponentId = InteractionComponentCache.GetComponentIdByChannelIdAndEntityId(interactionChannelId, mediaElement.Id, mediaElement.Name); Interaction interaction = interactionService.Queryable() .AsNoTracking() .Include(a => a.PersonAlias) .Where(a => a.InteractionComponentId == interactionComponentId) .Where(a => a.PersonAliasId == personAliasId || a.PersonAlias.Person.Aliases.Any(b => b.Id == personAliasId)) .OrderByDescending(a => a.InteractionEndDateTime) .ThenByDescending(a => a.InteractionDateTime) .FirstOrDefault(); if (interaction == null) { var errorResponse = Request.CreateErrorResponse(HttpStatusCode.NotFound, $"The Interaction could not be found."); throw new HttpResponseException(errorResponse); } var data = interaction.InteractionData.FromJsonOrNull <MediaWatchedInteractionData>(); return(new MediaElementInteraction { InteractionGuid = interaction.Guid, MediaElementGuid = mediaElement.Guid, PersonGuid = interaction.PersonAlias.Person?.Guid, PersonAliasGuid = interaction.PersonAlias.Guid, RelatedEntityTypeId = interaction.RelatedEntityTypeId, RelatedEntityId = interaction.RelatedEntityId, WatchMap = data?.WatchMap ?? string.Empty }); }
public Task sell([Remainder] string text) => PersonService.SellItem(text, Context);
public Task UseItem([Remainder] string text) => PersonService.UseItem(text, Context);
public Task LookItem([Remainder] string text) => PersonService.LookItem(text, Context);
static void Main(string[] args) { bool useAutoGeneration = false; bool useTests = false; bool useInitializers = true; if(useAutoGeneration) { using (var unitOfWork = new UnitOfWork(new BankModuleFactory(useInitializers))) { var LoanApplicationService = new LoanApplicationService(unitOfWork); var LoanAgreementService = new LoanAgreementService(unitOfWork); Console.WriteLine("Автогенерация для заявок:"); foreach (var loanApplication in LoanApplicationService.Get()) { if (loanApplication.Goal == "Смена гардероба" || loanApplication.Goal == "Пластическая операция" || loanApplication.Additional == "Car loan test" || loanApplication.Additional == "Grad loan test 1" || loanApplication.Additional == "Grad loan test 2") { Console.WriteLine(string.Format("{0} {1} {2}", loanApplication.Client.FirstName, loanApplication.Goal, loanApplication.Term)); loanApplication.Status.Stage = ApplicationConsiderationStages.ApplicationConfirmationQueue; LoanApplicationService.ApproveApplication(loanApplication); loanApplication.Status.Stage = ApplicationConsiderationStages.Providing; LoanAgreementService.CompleteAgreement(loanApplication.LoanAgreements.First()); unitOfWork.Commit(); } } Console.WriteLine("\nРезультаты:\n"); foreach (var loanApplication in LoanApplicationService.Get()) { if (loanApplication.Goal == "Смена гардероба" || loanApplication.Goal == "Пластическая операция" || loanApplication.Additional == "Car loan test" || loanApplication.Additional == "Grad loan test 1" || loanApplication.Additional == "Grad loan test 2") { Console.WriteLine(string.Format("{0} {1} {2}", loanApplication.Client.FirstName, loanApplication.Goal, loanApplication.Term)); Console.WriteLine("Создан кредитный договор:"); var loanAgreement = loanApplication.LoanAgreements.First(); Console.WriteLine(string.Format("Номер:{0} Кредитный аккаунт:{1} Аккаунт для оплаты:{2}", loanAgreement.Id, loanAgreement.LoanAccount.IBAN, loanAgreement.RepaymentAccount.IBAN)); foreach(var bailAgreement in loanApplication.BailAgreements) { Console.WriteLine("Создан договор залога:"); Console.WriteLine(string.Format("Номер:{0} Объект:{1} Владелец:{2}", bailAgreement.Id, bailAgreement.BailObject, bailAgreement.BailObjectHolder)); } foreach (var suretyAgreement in loanApplication.SuretyAgreements) { Console.WriteLine("Создан договор поручительства:"); Console.WriteLine(string.Format("Номер:{0} Поручитель:{1} Должник:{2}", suretyAgreement.Id, suretyAgreement.Guarantor.FirstName + " " + suretyAgreement.Guarantor.LastName, suretyAgreement.Client.FirstName)); } Console.WriteLine(); } } } System.Console.ReadKey(true); return; } if(useTests) { Console.WriteLine(new LoanTest().RunTest()); Console.WriteLine(new UserTest().RunTest()); System.Console.ReadKey(true); return; } List<LoanApplication> archiveApplications; using (var unitOfWork = new UnitOfWork(new BankModuleFactory(useInitializers))) { var AccountService = new AccountService(unitOfWork); Console.WriteLine("Accounts:"); foreach(var account in AccountService.Get()) { System.Console.WriteLine(string.Format("{0} {1} {2} {3} Transfers From: {4} Transfers To:{5}", account.IBAN, account.AccountType, account.MoneyAmount, account.Currency, account.BankTransfersFrom.Count, account.BankTransfersTo.Count)); } var BankTransferService = new BankTransferService(unitOfWork); Console.WriteLine("Transfers:"); foreach (var transfer in BankTransferService.Get(includeProperties: "AccountFrom,AccountTo")) Console.WriteLine(string.Format("From: {0} To: {1} {2} {3} {4}", transfer.AccountFrom.IBAN, transfer.AccountTo.IBAN, transfer.Amount, transfer.Currency, transfer.TransferDate.ToShortDateString())); var LoanAgreementService = new LoanAgreementService(unitOfWork); Console.WriteLine("Loan Agreements:"); foreach (var loanAgreement in LoanAgreementService.Get(includeProperties: "PayoutStatus")) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5} {6}", loanAgreement.Client.FirstName, loanAgreement.LoanType, loanAgreement.LoanProviding, loanAgreement.LoanRepayment, loanAgreement.Term, loanAgreement.Amount, loanAgreement.Currency)); var PayoutService = new PayoutService(unitOfWork); Console.WriteLine("Payouts:"); foreach (var payout in PayoutService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5}", payout.PayoutWay, payout.LoanAmount, payout.ProcessingFee, payout.InterestAmount, payout.TotalAmount, payout.Currency)); var FineService = new FineService(unitOfWork); Console.WriteLine("Fines:"); foreach (var fine in FineService.Get(includeProperties: "LoanAgreement")) Console.WriteLine(string.Format("{0} {1} {2} {3}", fine.LoanAgreement.Id, fine.DeadLineDate.ToShortDateString(), fine.FineRateOfInterest, fine.IsClosed)); var WithdrawalService = new WithdrawalService(unitOfWork); Console.WriteLine("Withdrawals:"); foreach (var withdrawal in WithdrawalService.Get(includeProperties: "ClientAccount,LoanAgreement")) Console.WriteLine(string.Format("{0} {1} {2} {3} {4}", withdrawal.ClientAccount.Id, withdrawal.MoneyAmount, withdrawal.Currency, withdrawal.WithdrawalWay, withdrawal.Date.ToShortDateString())); var PersonService = new PersonService(unitOfWork); Console.WriteLine("Persons:"); foreach (var person in PersonService.Get()) Console.WriteLine(string.Format("{0} {1} {2} Documents: {3} Records: {4}", person.FirstName, person.IdentificationNumber, person.MonthlyIncome, person.Documents.Count, person.CreditHistoryRecords.Count)); var HistoryService = new CreditHistoryRecordService(unitOfWork); Console.WriteLine("Records:"); foreach (var record in HistoryService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4}", record.Person.FirstName, record.BankConstants.BIC, record.Amount, record.Currency, record.Interest)); var LoanService = new LoanService(unitOfWork); Console.WriteLine("Loan programs:"); foreach (var program in LoanService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5}", program.Name, program.LoanProviding, program.LoanGuarantee, program.LoanRepayment, program.LoanType, program.MaxAmount)); var LoanApplicationService = new LoanApplicationService(unitOfWork); Console.WriteLine("Loan applications:"); foreach (var loanApplication in LoanApplicationService.Get()) { Console.WriteLine(string.Format("{0} {1} {2} {3} Time: {4}", loanApplication.Client.FirstName, loanApplication.Loan.Name, loanApplication.Amount, loanApplication.Term, loanApplication.Status.ChangedDate.TimeOfDay.ToString())); } unitOfWork.Commit(); var SuretyAgreementService = new SuretyAgreementService(unitOfWork); Console.WriteLine("Surety agreements:"); foreach (var suretyAgreement in SuretyAgreementService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5}", suretyAgreement.Client.FirstName, suretyAgreement.Guarantor.FirstName, suretyAgreement.Amount, suretyAgreement.Currency, suretyAgreement.LoanTerm, suretyAgreement.SuretyTerm)); var BailAgreementService = new BailAgreementService(unitOfWork); Console.WriteLine("Bail agreements:"); foreach (var bailAgreement in BailAgreementService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5}", bailAgreement.Client.FirstName, bailAgreement.BailObject, bailAgreement.Amount, bailAgreement.Currency, bailAgreement.LoanTerm, bailAgreement.BailTerm)); var BailObjectService = new BailObjectsService(unitOfWork); Console.WriteLine("Bail objects:"); foreach (var bailObject in BailObjectService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3}", bailObject.Object, bailObject.ClientIdentificationNumber, bailObject.BailObjectEstimate, bailObject.Currency)); var SystemService = new SystemResolutionService(unitOfWork); Console.WriteLine("System resolutions:"); foreach (var resolution in SystemService.Get()) Console.WriteLine(string.Format("Application: {0} {1} {2}", resolution.LoanApplication.Id, resolution.MaxLoanAmount, resolution.ScoringPoint)); var SecurityService = new SecurityResolutionService(unitOfWork); Console.WriteLine("Security resolutions:"); foreach (var resolution in SecurityService.Get()) Console.WriteLine(string.Format("Application: {0} {1} {2}{3}", resolution.LoanApplication.Id, resolution.Income, Environment.NewLine, resolution.IncomeEstimate)); var ExpertService = new ExpertResolutionService(unitOfWork); Console.WriteLine("Expert resolutions:"); foreach (var resolution in ExpertService.Get()) Console.WriteLine(string.Format("Application: {0} {1} {2}", resolution.LoanApplication.Id, resolution.Social, resolution.SocialEstimate)); var CommitteeService = new CommitteeResolutionService(unitOfWork); Console.WriteLine("Committee resolutions:"); foreach (var resolution in CommitteeService.Get()) Console.WriteLine(string.Format("Link: {0} {1}", resolution.ProtocolDocument.Link, resolution.Resolution)); archiveApplications = LoanApplicationService.Get (app => app.Id < 5, app => app.OrderBy(p => p.Id), app => app.Client, app => app.LoanAgreements, app => app.LoanAgreements.Select(l => l.BankConstants), app => app.LoanAgreements.Select(l => l.Payouts), app => app.LoanAgreements.Select(l => l.ClientWithdrawals), app => app.BailAgreements.Select(b => b.AgreementDocument), app => app.BailAgreements.Select(b => b.EstimationDocument), app => app.BailAgreements.Select(b => b.InsuranceDocument), app => app.SuretyAgreements.Select(s => s.AgreementDocument), app => app.SuretyAgreements.Select(s => s.Client), app => app.SuretyAgreements.Select(s => s.Guarantor), app => app.SuretyAgreements.Select(s => s.BankConstants) ).ToList(); } using (var archiveUnit = new UnitOfWork(new ArchiveModuleFactory(useInitializers))) { var ApplicationService = new ArchiveLoanApplicationService(archiveUnit); foreach(var arch in archiveApplications) ApplicationService.ArchiveApplication(arch); archiveUnit.Commit(); } using (var archiveUnit = new UnitOfWork(new ArchiveModuleFactory(false))) { var ApplicationService = new ArchiveLoanApplicationService(archiveUnit); Console.WriteLine("\nArchived applications:"); foreach (var loanApplication in ApplicationService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} Time: {4}", loanApplication.ClientIdentificationNumber, loanApplication.LoanAgreements.Count, loanApplication.Amount, loanApplication.Term, loanApplication.ArchivedDate.TimeOfDay.ToString())); } Console.WriteLine("\nAuthentification: "); using (var unitOfWork = new UnitOfWork(new AuthorizationModuleFactory(useInitializers))) { var userService = new UserService(unitOfWork); foreach (var user in userService.Get(includeProperties: "Roles")) { System.Console.WriteLine(string.Format("{0} {1} {2} {3}", user.FirstName, user.MiddleName, user.LastName, user.Roles.First().Name)); var newUser = userService.GetLoggedUser(user.Login, "ivan_peresvetov_pass"); if(newUser != null) Console.WriteLine("Found ivan!"); } } System.Console.ReadKey(true); }
/// <summary> /// Get Method for logging the user in. /// </summary> /// <returns></returns> public HttpResponseMessage Post(RegisterPost register) { //verify the token passed from the app is valid. Just an extra security measure tp make sure they're hitting from the app. var isAuthed = MobileAppAPIHelper.ValidateAppToken(Request); //if this check fails, return Unauthorized if (!isAuthed) return Request.CreateResponse(HttpStatusCode.Unauthorized); try { var rockContext = new RockContext(); var personService = new PersonService(rockContext); if (new UserLoginService(rockContext).GetByUserName(register.Username.Trim()) != null) { //check the username return Request.CreateResponse(HttpStatusCode.BadRequest, "The selected username is already taken."); } if (!UserLoginService.IsPasswordValid(register.Password.Trim())) { //check the password. return Request.CreateResponse(HttpStatusCode.BadRequest, "Password is invalid."); } Person person = null; Person spouse = null; Group family = null; GroupLocation homeLocation = null; var changes = new List<string>(); var spouseChanges = new List<string>(); var familyChanges = new List<string>(); // Try to find person by name/email if (person == null) { var matches = personService.GetByMatch(register.FirstName.Trim(), register.LastName.Trim(), register.Email.Trim()); if (matches.Count() == 1) { person = matches.First(); } } // Check to see if this is a new person if (person == null) { // If so, create the person and family record for the new person person = new Person(); person.FirstName = register.FirstName.Trim(); person.LastName = register.LastName.Trim(); person.Email = register.Email.Trim(); person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; // person.ConnectionStatusValueId = DefinedValueCache.Read(GetAttributeValue("ConnectionStatus").AsGuid()).Id; // person.RecordStatusValueId = DefinedValueCache.Read(GetAttributeValue("RecordStatus").AsGuid()); person.Gender = Gender.Unknown; family = PersonService.SaveNewPerson(person, rockContext, null, false); } if (person != null) { var user = UserLoginService.Create( rockContext, person, Rock.Model.AuthenticationServiceType.Internal, EntityTypeCache.Read(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id, register.Username.Trim(), register.Password.Trim(), true); //var mergeObjects = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage); //mergeObjects.Add("ConfirmAccountUrl", RootPath + "ConfirmAccount"); //var personDictionary = person.ToLiquid() as Dictionary<string, object>; //mergeObjects.Add("Person", personDictionary); //mergeObjects.Add("User", user); //var recipients = new List<Rock.Communication.RecipientData>(); //recipients.Add(new Rock.Communication.RecipientData(person.Email, // mergeObjects)); //Rock.Communication.Email.Send(GetAttributeValue("ConfirmAccountTemplate").AsGuid(), // recipients, ResolveRockUrl("~/"), ResolveRockUrl("~~/"), false); } return Request.CreateResponse(HttpStatusCode.OK, "SUccess"); } catch (Exception ex) { //todo: log the error somewhere. return Request.CreateResponse(HttpStatusCode.InternalServerError); } }
/// <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 personService = new PersonService(rockContext); 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); tbBusinessName.Text = tbBusinessName.Text.FixCase(); } // Business Name business.LastName = tbBusinessName.Text; // Phone Number var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id; var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId); 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; } else { if (phoneNumber != null) { business.PhoneNumbers.Remove(phoneNumber); new PhoneNumberService(rockContext).Delete(phoneNumber); } } // Record Type - this is always "business". it will never change. business.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id; // Record Status business.RecordStatusValueId = dvpRecordStatus.SelectedValueAsInt();; // Record Status Reason int?newRecordStatusReasonId = null; if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id) { newRecordStatusReasonId = dvpReason.SelectedValueAsInt(); } business.RecordStatusReasonValueId = newRecordStatusReasonId; // Email business.IsEmailActive = true; business.Email = tbEmail.Text.Trim(); business.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>(); if (!business.IsValid) { // Controls will render the error messages return; } rockContext.WrapTransaction(() => { rockContext.SaveChanges(); // 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.Get(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.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK.AsGuid()); int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid())) .Select(r => r.Id) .FirstOrDefault(); var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext); rockContext.SaveChanges(); // Location int workLocationTypeId = DefinedValueCache.Get(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); } } else { var newLocation = new LocationService(rockContext).Get( acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country); if (workLocation == null) { workLocation = new GroupLocation(); groupLocationService.Add(workLocation); workLocation.GroupId = adultFamilyMember.Group.Id; workLocation.GroupLocationTypeValueId = workLocationTypeId; } workLocation.Location = newLocation; workLocation.IsMailingLocation = true; } rockContext.SaveChanges(); hfBusinessId.Value = business.Id.ToString(); }); var queryParams = new Dictionary <string, string>(); queryParams.Add("businessId", hfBusinessId.Value); NavigateToCurrentPage(queryParams); }
/// <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(); } // 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 = NoteTypeCache.Read(Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE.AsGuid()); if (noteType != null) { 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(); }
static void Main(string[] args) { using (var studContext = new StudBankContext(true)) { var AccountService = new AccountService(studContext); Console.WriteLine("Accounts:"); foreach(var account in AccountService.Get()) { System.Console.WriteLine(string.Format("{0} {1} {2} {3} Transfers From: {4} Transfers To:{5}", account.IBAN, account.AccountType, account.MoneyAmount, account.Currency, account.BankTransfersFrom.Count, account.BankTransfersTo.Count)); } var BankTransferService = new BankTransferService(studContext); Console.WriteLine("Transfers:"); foreach (var transfer in BankTransferService.Get(includeProperties: "AccountFrom,AccountTo")) Console.WriteLine(string.Format("From: {0} To: {1} {2} {3} {4}", transfer.AccountFrom.IBAN, transfer.AccountTo.IBAN, transfer.Amount, transfer.Currency, transfer.TransferDate.ToShortDateString())); var LoanAgreementService = new LoanAgreementService(studContext); Console.WriteLine("Loan Agreements:"); foreach (var loanAgreement in LoanAgreementService.Get(includeProperties: "PayoutStatus")) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5} {6}", loanAgreement.Client.FirstName, loanAgreement.LoanType, loanAgreement.LoanProviding, loanAgreement.LoanRepayment, loanAgreement.Term, loanAgreement.Amount, loanAgreement.Currency)); var PayoutService = new PayoutService(studContext); Console.WriteLine("Payouts:"); foreach (var payout in PayoutService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5}", payout.PayoutWay, payout.LoanAmount, payout.ProcessingFee, payout.InterestAmount, payout.TotalAmount, payout.Currency)); var FineService = new FineService(studContext); Console.WriteLine("Fines:"); foreach (var fine in FineService.Get(includeProperties: "LoanAgreement")) Console.WriteLine(string.Format("{0} {1} {2} {3}", fine.LoanAgreement.Id, fine.DeadLineDate.ToShortDateString(), fine.FineRateOfInterest, fine.IsClosed)); var WithdrawalService = new WithdrawalService(studContext); Console.WriteLine("Withdrawals:"); foreach (var withdrawal in WithdrawalService.Get(includeProperties: "ClientAccount,LoanAgreement")) Console.WriteLine(string.Format("{0} {1} {2} {3} {4}", withdrawal.ClientAccount.Id, withdrawal.MoneyAmount, withdrawal.Currency, withdrawal.WithdrawalWay, withdrawal.Date.ToShortDateString())); var PersonService = new PersonService(studContext); Console.WriteLine("Persons:"); foreach (var person in PersonService.Get()) Console.WriteLine(string.Format("{0} {1} {2} Documents: {3} Records: {4}", person.FirstName, person.IdentificationNumber, person.MonthlyIncome, person.Documents.Count, person.CreditHistoryRecords.Count)); var HistoryService = new CreditHistoryRecordService(studContext); Console.WriteLine("Records:"); foreach (var record in HistoryService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4}", record.Person.FirstName, record.BankConstants.BIC, record.Amount, record.Currency, record.Interest)); var LoanService = new LoanService(studContext); Console.WriteLine("Loan programs:"); foreach (var program in LoanService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5}", program.Name, program.LoanProviding, program.LoanGuarantee, program.LoanRepayment, program.LoanType, program.MaxAmount)); var LoanApplicationService = new LoanApplicationService(studContext); Console.WriteLine("Loan applications:"); foreach (var loanApplication in LoanApplicationService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} First surety:{5}", loanApplication.Client.FirstName, loanApplication.Loan.Name, loanApplication.Amount, loanApplication.Currency, loanApplication.Term, loanApplication.Sureties.FirstOrDefault().FirstName)); var SuretyAgreementService = new SuretyAgreementService(studContext); Console.WriteLine("Surety agreements:"); foreach (var suretyAgreement in SuretyAgreementService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5}", suretyAgreement.Client.FirstName, suretyAgreement.Guarantor.FirstName, suretyAgreement.Amount, suretyAgreement.Currency, suretyAgreement.LoanTerm, suretyAgreement.SuretyTerm)); var BailAgreementService = new BailAgreementService(studContext); Console.WriteLine("Bail agreements:"); foreach (var bailAgreement in BailAgreementService.Get()) Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5}", bailAgreement.Client.FirstName, bailAgreement.BailObject, bailAgreement.Amount, bailAgreement.Currency, bailAgreement.LoanTerm, bailAgreement.BailTerm)); var SystemService = new SystemResolutionService(studContext); Console.WriteLine("System resolutions:"); foreach (var resolution in SystemService.Get()) Console.WriteLine(string.Format("Application: {0} {1} {2}", resolution.LoanApplication.Id, resolution.MaxLoanAmount, resolution.ScoringPoint)); var SecurityService = new SecurityResolutionService(studContext); Console.WriteLine("Security resolutions:"); foreach (var resolution in SecurityService.Get()) Console.WriteLine(string.Format("Application: {0} {1} {2}", resolution.LoanApplication.Id, resolution.Property, resolution.PropertyEstimate)); var ExpertService = new ExpertResolutionService(studContext); Console.WriteLine("Expert resolutions:"); foreach (var resolution in ExpertService.Get()) Console.WriteLine(string.Format("Application: {0} {1} {2}", resolution.LoanApplication.Id, resolution.Property, resolution.PropertyEstimate)); var CommitteeService = new CommitteeResolutionService(studContext); Console.WriteLine("Committee resolutions:"); foreach (var resolution in CommitteeService.Get()) Console.WriteLine(string.Format("Link: {0} {1}", resolution.ProtocolDocument.Link, resolution.Resolution)); } Console.WriteLine("\nAuthentification: "); using (var authContext = new StudAuthorizeContext(true)) { var userService = new EntityService<User>(authContext); var roleService = new EntityService<Role>(authContext); foreach (var user in userService.Get(includeProperties: "Roles")) { System.Console.WriteLine(string.Format("{0} {1} {2} {3}", user.FirstName, user.MiddleName, user.LastName, user.Roles.First().Name)); } System.Console.WriteLine(); userService.Get(user => user.FirstName == "Ivan").First().FirstName = "Vano"; authContext.SaveChanges(); foreach (var user in userService.Get(includeProperties: "Roles")) { System.Console.WriteLine(string.Format("{0} {1} {2} {3}", user.FirstName, user.MiddleName, user.LastName, user.Roles.First().Name)); } } System.Console.ReadKey(true); }
private void BindGrid() { var birthDateCol = gPeople.ColumnsOfType <DateField>().First(c => c.DataField == "BirthDate"); var ageCol = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Age"); var genderCol = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Gender"); var envelopeNumberField = gPeople.ColumnsOfType <RockLiteralField>().First(c => c.ID == "lEnvelopeNumber"); var spouseCol = gPeople.ColumnsOfType <RockTemplateField>().First(c => c.HeaderText == "Spouse"); var personGivingEnvelopeAttribute = AttributeCache.Get(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid()); if (personGivingEnvelopeAttribute != null) { envelopeNumberField.Visible = GlobalAttributesCache.Get().EnableGivingEnvelopeNumber&& this.GetAttributeValue("ShowEnvelopeNumber").AsBoolean(); } else { envelopeNumberField.Visible = false; } birthDateCol.Visible = GetAttributeValue("ShowBirthdate").AsBoolean(); ageCol.Visible = GetAttributeValue("ShowAge").AsBoolean(); genderCol.Visible = GetAttributeValue("ShowGender").AsBoolean(); spouseCol.Visible = _showSpouse; string type = PageParameter("SearchType"); string term = PageParameter("SearchTerm"); if (!string.IsNullOrWhiteSpace(type) && !string.IsNullOrWhiteSpace(term)) { term = term.Trim(); type = type.Trim(); var rockContext = new RockContext(); var personService = new PersonService(rockContext); IQueryable <Person> people = null; switch (type.ToLower()) { case ("name"): { bool allowFirstNameOnly = false; if (!bool.TryParse(PageParameter("allowFirstNameOnly"), out allowFirstNameOnly)) { allowFirstNameOnly = false; } people = personService.GetByFullName(term, allowFirstNameOnly, true); break; } case ("phone"): { var phoneService = new PhoneNumberService(rockContext); var personIds = phoneService.GetPersonIdsByNumber(term); people = personService.Queryable().Where(p => personIds.Contains(p.Id)); break; } case ("address"): { var groupMemberService = new GroupMemberService(rockContext); var personIds2 = groupMemberService.GetPersonIdsByHomeAddress(term); people = personService.Queryable().Where(p => personIds2.Contains(p.Id)); break; } case ("email"): { var searchKeyQry = new PersonSearchKeyService(rockContext).Queryable(); people = personService.Queryable() .Where(p => (term != "" && p.Email == term) || searchKeyQry.Any(a => a.PersonAlias.PersonId == p.Id && a.SearchValue == term)); break; } case ("birthdate"): { DateTime?birthDate = Request.QueryString["birthdate"].AsDateTime(); int? personId = Request.QueryString["person-id"].AsIntegerOrNull(); if (birthDate == null) { birthDate = term.AsDateTime(); } if (personId.HasValue) { people = personService.Queryable().Where(a => a.Id == personId.Value); } else { people = personService.Queryable().Where(p => p.BirthDate.HasValue && birthDate.HasValue && p.BirthDate == birthDate.Value); } break; } } IEnumerable <int> personIdList = people.Select(p => p.Id); // just leave the personIdList as a Queryable if it is over 10000 so that we don't throw a SQL exception due to the big list of ids if (people.Count() < 10000) { personIdList = personIdList.ToList(); } people = personService.Queryable(true).Where(p => personIdList.Contains(p.Id)); SortProperty sortProperty = gPeople.SortProperty; if (sortProperty != null) { people = people.Sort(sortProperty); } else { people = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName); } var familyGroupType = GroupTypeCache.GetFamilyGroupType(); int familyGroupTypeId = familyGroupType != null ? familyGroupType.Id : 0; var groupLocationTypeHome = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid()); int homeAddressTypeId = groupLocationTypeHome != null ? groupLocationTypeHome.Id : 0; var personList = people.Select(p => new PersonSearchResult { Id = p.Id, FirstName = p.FirstName, NickName = p.NickName, LastName = p.LastName, BirthDate = p.BirthDate, BirthYear = p.BirthYear, BirthMonth = p.BirthMonth, BirthDay = p.BirthDay, ConnectionStatusValueId = p.ConnectionStatusValueId, RecordStatusValueId = p.RecordStatusValueId, RecordTypeValueId = p.RecordTypeValueId, AgeClassification = p.AgeClassification, SuffixValueId = p.SuffixValueId, IsDeceased = p.IsDeceased, Email = p.Email, Gender = p.Gender, PhotoId = p.PhotoId, CampusIds = p.Members .Where(m => m.Group.GroupTypeId == familyGroupTypeId && m.Group.CampusId.HasValue) .Select(m => m.Group.CampusId.Value) .ToList(), HomeAddresses = p.Members .Where(m => m.Group.GroupTypeId == familyGroupTypeId) .SelectMany(m => m.Group.GroupLocations) .Where(gl => gl.GroupLocationTypeValueId == homeAddressTypeId) .Select(gl => gl.Location), PhoneNumbers = p.PhoneNumbers .Where(n => n.NumberTypeValueId.HasValue) .Select(n => new PersonSearchResultPhone { NumberTypeValueId = n.NumberTypeValueId.Value, Number = n.NumberFormatted }) .ToList(), TopSignalColor = p.TopSignalColor, TopSignalIconCssClass = p.TopSignalIconCssClass }).ToList(); if (personList.Count == 1) { Response.Redirect(string.Format("~/Person/{0}", personList[0].Id), false); Context.ApplicationInstance.CompleteRequest(); } else { if (type.ToLower() == "name") { var similarNames = personService.GetSimilarNames(term, personList.Select(p => p.Id).ToList(), true); if (similarNames.Any()) { var hyperlinks = new List <string>(); foreach (string name in similarNames.Distinct()) { var pageRef = CurrentPageReference; pageRef.Parameters["SearchTerm"] = name; hyperlinks.Add(string.Format("<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name)); } string altNames = string.Join(", ", hyperlinks); nbNotice.Text = string.Format("Other Possible Matches: {0}", altNames); nbNotice.Visible = true; } } _inactiveStatus = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE); var personIds = personList.Select(a => a.Id).ToList(); if (envelopeNumberField != null && envelopeNumberField.Visible) { _envelopeNumbers = new AttributeValueService(rockContext).Queryable() .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id) .Where(a => personIds.Contains(a.EntityId.Value)) .Select(a => new { PersonId = a.EntityId.Value, Value = a.Value }).ToList().ToDictionary(k => k.PersonId, v => v.Value); } gPeople.EntityTypeId = EntityTypeCache.GetId <Person>(); gPeople.DataSource = personList; gPeople.DataBind(); } } }
/// <summary> /// Gets the name of the Google user. /// </summary> /// <param name="googleUser">The Google user.</param> /// <param name="accessToken">The access token.</param> /// <returns></returns> public static string GetGoogleUser(GoogleUser googleUser, string accessToken = "") { string username = string.Empty; string googleId = googleUser.id; string googleLink = googleUser.link; string userName = "******" + googleId; UserLogin user = null; using (var rockContext = new RockContext()) { // Query for an existing user var userLoginService = new UserLoginService(rockContext); user = userLoginService.GetByUserName(userName); // If no user was found, see if we can find a match in the person table if (user == null) { // Get name/email from Google login string lastName = googleUser.family_name.ToString(); string firstName = googleUser.given_name.ToString(); string email = string.Empty; try { email = googleUser.email.ToString(); } catch { } Person person = null; // If person had an email, get the first person with the same name and email address. if (!string.IsNullOrWhiteSpace(email)) { var personService = new PersonService(rockContext); var people = personService.GetByMatch(firstName, lastName, email); if (people.Count() == 1) { person = people.First(); } } var personRecordTypeId = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; var personStatusPending = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id; rockContext.WrapTransaction(() => { if (person == null) { person = new Person(); person.IsSystem = false; person.RecordTypeValueId = personRecordTypeId; person.RecordStatusValueId = personStatusPending; person.FirstName = firstName; person.LastName = lastName; person.Email = email; person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; try { if (googleUser.gender.ToString() == "male") { person.Gender = Gender.Male; } else if (googleUser.gender.ToString() == "female") { person.Gender = Gender.Female; } else { person.Gender = Gender.Unknown; } } catch { } if (person != null) { PersonService.SaveNewPerson(person, rockContext, null, false); } } if (person != null) { int typeId = EntityTypeCache.Read(typeof(Google)).Id; user = UserLoginService.Create(rockContext, person, AuthenticationServiceType.External, typeId, userName, "goog", true); } }); } if (user != null) { username = user.UserName; if (user.PersonId.HasValue) { var converter = new ExpandoObjectConverter(); var personService = new PersonService(rockContext); var person = personService.Get(user.PersonId.Value); } } return(username); } }
public void ValidDetailsSaved() { var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); // Contract var cd = new EnergyTrading.MDM.Contracts.Sample.PersonDetails { Forename = "John", Surname = "Smith", Email = "*****@*****.**" }; var nexus = new EnergyTrading.Mdm.Contracts.SystemData { StartDate = new DateTime(2012, 1, 1) }; var identifier = new EnergyTrading.Mdm.Contracts.MdmId { SystemName = "Test", Identifier = "A" }; var contract = new EnergyTrading.MDM.Contracts.Sample.Person { Details = cd, MdmSystemData = nexus }; contract.Identifiers.Add(identifier); // Domain var system = new SourceSystem { Name = "Test" }; var mapping = new PersonMapping { System = system, MappingValue = "A" }; var d1 = new PersonDetails { Id = 1, FirstName = "Bill", LastName = "Jones", Email = "*****@*****.**", Timestamp = 74UL.GetVersionByteArray() }; var entity = new Person(); entity.AddDetails(d1); var d2 = new PersonDetails { FirstName = "John", LastName = "Smith", Email = "*****@*****.**" }; var range = new DateRange(new DateTime(2012, 1, 1), DateTime.MaxValue); validatorFactory.Setup(x => x.IsValid(It.IsAny<CreateMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true); validatorFactory.Setup(x => x.IsValid(It.IsAny<EnergyTrading.MDM.Contracts.Sample.Person>(), It.IsAny<IList<IRule>>())).Returns(true); repository.Setup(x => x.FindOne<Person>(1)).Returns(entity); mappingEngine.Setup(x => x.Map<EnergyTrading.MDM.Contracts.Sample.PersonDetails, PersonDetails>(cd)).Returns(d2); mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.SystemData, DateRange>(nexus)).Returns(range); mappingEngine.Setup(x => x.Map<EnergyTrading.Mdm.Contracts.MdmId, PersonMapping>(identifier)).Returns(mapping); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); // Act service.Update(1, 74, contract); // Assert Assert.AreEqual(2, entity.Details.Count, "Details count differs"); Assert.AreEqual(1, entity.Mappings.Count, "Mapping count differs"); repository.Verify(x => x.Save(entity)); repository.Verify(x => x.Flush()); }
private HashSet <int> SyncFromMailChimp(IEnumerable <Member> listMembers) { RockContext rockContext = GenerateRockContext(); MailChimpPersonAliasService mailChimpPersonAliasService = new MailChimpPersonAliasService(rockContext); var personService = new PersonService(rockContext); HashSet <int> seenPesonAliasIds = new HashSet <int>(); int count = 0; int recordTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; int recordStatusId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id; int connectionStatusValueId = DefinedValueCache.Read(_newPersonConnectionStatusGuid).Id; foreach (Member listMember in listMembers.Where(l => l.Status != Status.Undefined && l.Status != Status.Unsubscribed)) { count++; if (count > 200) { count = 0; rockContext.SaveChanges(); rockContext = GenerateRockContext(); mailChimpPersonAliasService = new MailChimpPersonAliasService(rockContext); personService = new PersonService(rockContext); } MailChimpPersonAlias mailChimpPersonAlias = null; // Get by unique ID if no personaliasid seen, else use personaliasid mailChimpPersonAlias = ((!listMember.MergeFields.ContainsKey(Utils.PERSON_ALIAS_KEY) || !listMember.MergeFields[Utils.PERSON_ALIAS_KEY].ToString().AsIntegerOrNull().HasValue) ? mailChimpPersonAliasService.GetByMailChimpUniqueId(listMember.UniqueEmailId) : mailChimpPersonAliasService.GetByPersonAliasId(listMember.MergeFields[Utils.PERSON_ALIAS_KEY].ToString().AsInteger())); if (mailChimpPersonAlias == null) { // Can't find a match in our database, guess we better try and find or create a person if (_workflowTypeGuid.HasValue) { // defer to workflow LaunchWorkflow(listMember.MergeFields[Utils.FIRST_NAME_KEY].ToString(), listMember.MergeFields[Utils.LAST_NAME_KEY].ToString(), listMember.EmailAddress); } else { // do it ourselves mailChimpPersonAlias = CreatePerson(rockContext, personService, recordTypeId, recordStatusId, connectionStatusValueId, listMember); } } else { var person = mailChimpPersonAlias.PersonAlias.Person; if (person.EmailPreference != EmailPreference.EmailAllowed) { _api.RemoveFromMailChimp(mailChimpPersonAlias).Wait(); } // Handle change of email address, Rock always wins else if (person.Email != mailChimpPersonAlias.Email) { _api.RemoveFromMailChimp(mailChimpPersonAlias).Wait(); try { Utils.AddOrUpdatePerson(_api, person, rockContext); _syncCount++; } catch (Exception e) { _exceptions.Add(new Exception("Failed to add or update person", e)); } } else { // Check to see if person has been updated if (Utils.IsSyncNeeded(person, listMember)) { try { Utils.AddOrUpdatePerson(_api, mailChimpPersonAlias.PersonAlias.Person, rockContext); _syncCount++; } catch (Exception e) { _exceptions.Add(new Exception("Failed to add or update person", e)); } } } } seenPesonAliasIds.Add(mailChimpPersonAlias.PersonAliasId); } return(seenPesonAliasIds); }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { var rockContext = (RockContext)serviceInstance.Context; string[] selectionValues = selection.Split('|'); if (selectionValues.Length < 4) { return(null); } ComparisonType comparisonType = selectionValues[0].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo); decimal amount = selectionValues[1].AsDecimalOrNull() ?? 0.00M; DateRange dateRange; if (selectionValues.Length >= 7) { string slidingDelimitedValues = selectionValues[6].Replace(',', '|'); dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues); } else { // if converting from a previous version of the selection DateTime?startDate = selectionValues[2].AsDateTime(); DateTime?endDate = selectionValues[3].AsDateTime(); dateRange = new DateRange(startDate, endDate); if (dateRange.End.HasValue) { // the DateRange picker doesn't automatically add a full day to the end date dateRange.End.Value.AddDays(1); } } var accountIdList = new List <int>(); if (selectionValues.Length >= 5) { var accountGuids = selectionValues[4].Split(',').Select(a => a.AsGuid()).ToList(); accountIdList = new FinancialAccountService((RockContext)serviceInstance.Context).GetByGuids(accountGuids).Select(a => a.Id).ToList(); } bool combineGiving = false; if (selectionValues.Length >= 6) { combineGiving = selectionValues[5].AsBooleanOrNull() ?? false; } int transactionTypeContributionId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid()).Id; var financialTransactionQry = new FinancialTransactionService(rockContext).Queryable() .Where(xx => xx.AuthorizedPersonAliasId.HasValue) .Where(xx => xx.TransactionTypeValueId == transactionTypeContributionId); if (dateRange.Start.HasValue) { financialTransactionQry = financialTransactionQry.Where(xx => xx.TransactionDateTime >= dateRange.Start.Value); } if (dateRange.End.HasValue) { financialTransactionQry = financialTransactionQry.Where(xx => xx.TransactionDateTime < dateRange.End.Value); } bool limitToAccounts = accountIdList.Any(); // Create an explicit join to person alias so that rendered SQL is an INNER Join vs OUTER join var personAliasQry = new PersonAliasService(rockContext).Queryable(); var financialTransactionGivingGroupQry = financialTransactionQry .Join(personAliasQry, t => t.AuthorizedPersonAliasId, p => p.Id, (t, p) => new { Txn = t, GivingGroupId = p.Person.GivingGroupId }); // query transactions for individuals. // If CombineGiving, exclude people that are Giving Group, and we'll get those when we union with CombineGiving var financialTransactionDetailsIndividualQry = financialTransactionGivingGroupQry.Where(a => !combineGiving || !a.GivingGroupId.HasValue).Select(a => a.Txn) .GroupBy(xx => xx.AuthorizedPersonAlias.PersonId ).Select(xx => new { PersonId = xx.Key, AnyAmount = xx.Any(ss => ss.TransactionDetails.Where(td => !limitToAccounts || accountIdList.Contains(td.AccountId)).Any()), TotalAmount = xx.Sum(ss => ss.TransactionDetails.Where(td => !limitToAccounts || accountIdList.Contains(td.AccountId)).Sum(td => td.Amount)) }); bool excludePersonsWithTransactions = false; if (comparisonType == ComparisonType.LessThan) { // NOTE: Since we want people that have less than the specified, but also want to include people to didn't give anything at all (no transactions) // make this query the same as the GreaterThan, but use it to EXCLUDE people that gave MORE than the specified amount. That // way the filter will include people that had no transactions for the specified date/range and account financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.TotalAmount >= amount); excludePersonsWithTransactions = true; } else if (comparisonType == ComparisonType.EqualTo) { financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.TotalAmount == amount); } else if (comparisonType == ComparisonType.GreaterThanOrEqualTo) { // NOTE: if the amount filter is 'they gave $0.00 or more', and doing a GreaterThanOrEqualTo, then we don't need to calculate and compare against TotalAmount if (amount == 0.00M) { // just query if there is 'any' amount financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.AnyAmount); } else { financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.TotalAmount >= amount); } } var innerQryIndividual = financialTransactionDetailsIndividualQry.Select(xx => xx.PersonId).AsQueryable(); IQueryable <int> qryTransactionPersonIds; if (combineGiving) { // if CombineGiving=true, do another query to total by GivingGroupId for people with GivingGroupId specified var financialTransactionDetailsGivingGroupQry = financialTransactionGivingGroupQry.Where(a => a.GivingGroupId.HasValue) .GroupBy(xx => new { xx.GivingGroupId }).Select(xx => new { GivingGroupId = xx.Key, AnyAmount = xx.Any(ss => ss.Txn.TransactionDetails.Where(td => !limitToAccounts || accountIdList.Contains(td.AccountId)).Any()), TotalAmount = xx.Sum(ss => ss.Txn.TransactionDetails.Where(td => !limitToAccounts || accountIdList.Contains(td.AccountId)).Sum(td => td.Amount)) }); if (comparisonType == ComparisonType.LessThan) { // NOTE: Since we want people that have less than the specified amount, but also want to include people to didn't give anything at all (no transactions) // make this query the same as the GreaterThan, but use it to EXCLUDE people that gave MORE than the specified amount. That // way the filter will include people that had no transactions for the specified date/range and account financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.TotalAmount >= amount); excludePersonsWithTransactions = true; } else if (comparisonType == ComparisonType.EqualTo) { financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.TotalAmount == amount); } else if (comparisonType == ComparisonType.GreaterThanOrEqualTo) { // NOTE: if the amount filter is 'they gave $0.00 or more', and doing a GreaterThanOrEqualTo, then we don't need to calculate and compare against TotalAmount if (amount == 0.00M) { // don't query against TotalAmount if we don't care about amount or accounts financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.AnyAmount); } else { financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.TotalAmount >= amount); } } var personService = new PersonService(rockContext); IQueryable <int> innerQryGivingGroupPersons = personService.Queryable() .Where(a => financialTransactionDetailsGivingGroupQry.Select(xx => xx.GivingGroupId).AsQueryable().Any(gg => gg.GivingGroupId == a.GivingGroupId)) .Select(s => s.Id); // include people that either give as individuals or are members of a giving group qryTransactionPersonIds = innerQryIndividual.Union(innerQryGivingGroupPersons); } else { // don't factor in GivingGroupId. Only include people that are directly associated with the transaction qryTransactionPersonIds = innerQryIndividual; } IQueryable <Rock.Model.Person> qry; if (excludePersonsWithTransactions) { // the filter is for people that gave LESS than the specified amount, so return people that didn't give MORE than the specified amount qry = new PersonService(rockContext).Queryable().Where(p => !qryTransactionPersonIds.Any(xx => xx == p.Id)); } else { qry = new PersonService(rockContext).Queryable().Where(p => qryTransactionPersonIds.Any(xx => xx == p.Id)); } Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"); return(extractedFilterExpression); }
public UserController(PersonService personService) { this.personService = personService ?? throw new ArgumentNullException(nameof(personService)); }
public void VersionConflict() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var message = new AmendMappingRequest { MappingId = 12, Mapping = new MdmId { SystemName = "Test", Identifier = "A" }, Version = 34 }; var person = new MDM.Person(); person.AddDetails(new MDM.PersonDetails() { Timestamp = BitConverter.GetBytes(25L) }); var mapping = new PersonMapping { Person = person }; validatorFactory.Setup(x => x.IsValid(It.IsAny<AmendMappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true); repository.Setup(x => x.FindOne<PersonMapping>(12)).Returns(mapping); // Act service.UpdateMapping(message); }
public void PersonService_LookupAsync_ReturnsNoPersons() { //Arrange var mockDbContextScopeFac = new Mock<IDbContextScopeFactory>(); var mockDbContextScope = new Mock<IDbContextReadOnlyScope>(); var mockEfDbContext = new Mock<EFDbContext>(); mockDbContextScopeFac.Setup(x => x.CreateReadOnly(DbContextScopeOption.JoinExisting)).Returns(mockDbContextScope.Object); mockDbContextScope.Setup(x => x.DbContexts.Get<EFDbContext>()).Returns(mockEfDbContext.Object); var groupManager1 = new Person { Id = "dummyUserId1", FirstName = "FirstManager1", LastName = "LastManager1" }; var groupManager2 = new Person { Id = "dummyUserId2", FirstName = "FirstManager2", LastName = "LastManager2" }; var personGroupDbEntry1 = new PersonGroup { GroupManagers = new List<Person> { groupManager1 }, }; var personGroupDbEntry2 = new PersonGroup { GroupManagers = new List<Person> { groupManager2 }, }; var dbEntry1 = new Person { Id = "dummyEntryId1", FirstName = "First1", LastName = "Last1", IsActive_bl = false, Initials = "FLA1", PersonGroups = new List<PersonGroup> {personGroupDbEntry1}}; var dbEntry2 = new Person { Id = "dummyEntryId2", FirstName = "First2", LastName = "Last2", IsActive_bl = true, Initials = "FLA2", PersonGroups = new List<PersonGroup> {personGroupDbEntry1}}; var dbEntry3 = new Person { Id = "dummyEntryId3", FirstName = "First3", LastName = "Last3", IsActive_bl = true, Initials = "FLA3", PersonGroups = new List<PersonGroup> { personGroupDbEntry1 }}; var dbEntry4 = new Person { Id = "dummyEntryId4", FirstName = "First4", LastName = "Last4", IsActive_bl = true, Initials = "FLA4", PersonGroups = new List<PersonGroup> { personGroupDbEntry2 }}; var personDbEntries = (new List<Person> { dbEntry1, dbEntry2, dbEntry3, dbEntry4 }).AsQueryable(); var mockDbSet = new Mock<DbSet<Person>>(); mockDbSet.As<IDbAsyncEnumerable<Person>>().Setup(m => m.GetAsyncEnumerator()).Returns(new MockDbAsyncEnumerator<Person>(personDbEntries.GetEnumerator())); mockDbSet.As<IQueryable<Person>>().Setup(m => m.Provider).Returns(new MockDbAsyncQueryProvider<Person>(personDbEntries.Provider)); mockDbSet.As<IQueryable<Person>>().Setup(m => m.Expression).Returns(personDbEntries.Expression); mockDbSet.As<IQueryable<Person>>().Setup(m => m.ElementType).Returns(personDbEntries.ElementType); mockDbSet.As<IQueryable<Person>>().Setup(m => m.GetEnumerator()).Returns(personDbEntries.GetEnumerator()); mockEfDbContext.Setup(x => x.Persons).Returns(mockDbSet.Object); var personService = new PersonService(mockDbContextScopeFac.Object, groupManager1.Id); //Act var returnedProjects = personService.LookupAsync("FLA1").Result; //Assert Assert.IsTrue(returnedProjects.Count == 0); }
public void SuccessMatch() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); // Domain details var start = new DateTime(1999, 12, 31); var finish = new DateTime(2020, 1, 1); var system = new SourceSystem { Name = "Endur" }; var mapping = new PersonMapping { System = system, MappingValue = "A" }; var details = new PersonDetails { FirstName = "John", LastName = "Smith", Email = "*****@*****.**", Validity = new DateRange(start, finish) }; var person = new Person { Id = 1 }; person.AddDetails(details); person.ProcessMapping(mapping); // Contract details var identifier = new EnergyTrading.Mdm.Contracts.MdmId { SystemName = "Endur", Identifier = "A" }; var cDetails = new EnergyTrading.MDM.Contracts.Sample.PersonDetails { Forename = "John", Surname = "Smith", Email = "*****@*****.**" }; mappingEngine.Setup(x => x.Map<PersonMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping)).Returns(identifier); mappingEngine.Setup(x => x.Map<PersonDetails, EnergyTrading.MDM.Contracts.Sample.PersonDetails>(details)).Returns(cDetails); validatorFactory.Setup(x => x.IsValid(It.IsAny<MappingRequest>(), It.IsAny<IList<IRule>>())).Returns(true); var list = new List<PersonMapping> { mapping }; repository.Setup(x => x.Queryable<PersonMapping>()).Returns(list.AsQueryable()); var request = new MappingRequest { SystemName = "Endur", Identifier = "A", ValidAt = SystemTime.UtcNow(), Version = 1 }; // Act var response = service.Map(request); var candidate = response.Contract; // Assert mappingEngine.Verify(x => x.Map<PersonMapping, EnergyTrading.Mdm.Contracts.MdmId>(mapping)); mappingEngine.Verify(x => x.Map<PersonDetails, EnergyTrading.MDM.Contracts.Sample.PersonDetails>(details)); repository.Verify(x => x.Queryable<PersonMapping>()); Assert.IsNotNull(candidate, "Contract null"); Assert.AreEqual(2, candidate.Identifiers.Count, "Identifier count incorrect"); // NB This is order dependent Assert.AreSame(identifier, candidate.Identifiers[1], "Different identifier assigned"); Assert.AreSame(cDetails, candidate.Details, "Different details assigned"); Assert.AreEqual(start, candidate.MdmSystemData.StartDate, "Start date differs"); Assert.AreEqual(finish, candidate.MdmSystemData.EndDate, "End date differs"); }
public void SavePerson_updates_timestamp() { // //Arrange Person _p = (Person)Records.person.Clone(); _repo = new Mock<IPersonRepository>(); _uow = new Mock<IUnitOfWork>(); _lcache = new Mock<ILookupCache>(); string user = "******"; _p.datecreated = DateTime.MinValue; _p.dateupdated = DateTime.MinValue; var _serv = new PersonService(_repo.Object, _uow.Object, _lcache.Object); // //Act _serv.Save(_p, user); // //Assert Assert.IsTrue(_p.Updatedby == user); Assert.IsTrue(_p.dateupdated > DateTime.MinValue); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService(rockContext); var groupService = new GroupService(rockContext); var groupTypeService = new GroupTypeService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personService = new PersonService(rockContext); var personAliasService = new PersonAliasService(rockContext); var entityTypeService = new EntityTypeService(rockContext); var registrationRegistrantService = new RegistrationRegistrantService(rockContext); var eiogmService = new EventItemOccurrenceGroupMapService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var locationService = new LocationService(rockContext); var signatureDocumentServce = new SignatureDocumentService(rockContext); var phoneNumberService = new PhoneNumberService(rockContext); int[] signatureDocumentIds = { }; if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates"))) { signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse); } int[] registrationInstanceIds = { }; if (!string.IsNullOrWhiteSpace(GetAttributeValue("RegistrationInstances"))) { registrationInstanceIds = Array.ConvertAll(GetAttributeValue("RegistrationInstances").Split(','), int.Parse); } Guid bbGroup = GetAttributeValue("Group").AsGuid(); var group = new GroupService(rockContext).Get(bbGroup); Guid hsmGroupTypeGuid = GetAttributeValue("MSMGroupType").AsGuid(); int? hsmGroupTypeId = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault(); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id; var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList(); hlGroup.NavigateUrl = "/group/" + group.Id; var attributeIds = attributeService.Queryable() .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) || (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) || (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue))) .Select(a => a.Id).ToList(); var gmTmpqry = groupMemberService.Queryable() .Where(gm => (gm.GroupId == group.Id)); var qry = gmTmpqry .Join(personAliasService.Queryable(), obj => obj.PersonId, pa => pa.PersonId, (obj, pa) => new { GroupMember = obj, PersonAlias = pa } ) .Join(registrationRegistrantService.Queryable(), obj => obj.PersonAlias.Id, rr => rr.PersonAliasId, (obj, rr) => new { GroupMember = obj.GroupMember, Person = obj.GroupMember.Person, RegistrationRegistrant = rr }) .GroupJoin(attributeValueService.Queryable(), obj => new { PersonId = (int?)obj.Person.Id, AttributeId = 739 }, av => new { PersonId = av.EntityId, av.AttributeId }, (obj, av) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, School = av.Select(s => s.Value).FirstOrDefault() }) .GroupJoin(attributeValueService.Queryable(), obj => obj.GroupMember.Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ }) .GroupJoin(attributeValueService.Queryable(), obj => obj.RegistrationRegistrant.Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ }) .Where(obj => registrationInstanceIds.Contains(obj.RegistrationRegistrant.Registration.RegistrationInstanceId)); var qry2 = gmTmpqry .GroupJoin( groupMemberService.Queryable() .Join(groupService.Queryable(), gm => new { Id = gm.GroupId, GroupTypeId = 10 }, g => new { g.Id, g.GroupTypeId }, (gm, g) => new { GroupMember = gm, Group = g }) .Join(groupLocationService.Queryable(), obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = (int?)19 }, gl => new { gl.GroupId, gl.GroupLocationTypeValueId }, (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl }) .Join(locationService.Queryable(), obj => obj.GroupLocation.LocationId, l => l.Id, (obj, l) => new { GroupMember = obj.GroupMember, Location = l }), gm => gm.PersonId, glgm => glgm.GroupMember.PersonId, (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() } ) .GroupJoin(signatureDocumentServce.Queryable() .Join(personAliasService.Queryable(), sd => sd.AppliesToPersonAliasId, pa => pa.Id, (sd, pa) => new { SignatureDocument = sd, Alias = pa }), obj => obj.GroupMember.PersonId, sd => sd.Alias.PersonId, (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds }) .GroupJoin(phoneNumberService.Queryable(), obj => obj.GroupMember.PersonId, p => p.PersonId, (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn }); if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix)))) { string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower(); qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable(); } decimal?lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull(); decimal?upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull(); if (lowerVal != null && upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal && q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable(); } else if (lowerVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal).AsQueryable(); } else if (upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable(); } else if (!string.IsNullOrEmpty(cmpCampus.SelectedValue)) { CampusCache campus = CampusCache.Read(cmpCampus.SelectedCampusId.Value); qry = qry.ToList().Where(q => q.RegistrationAttributeValues.Where(ra => ra.AttributeKey == "Whichcampus" && ra.Value.Contains(campus.Name.Replace(" ", ""))).Any()).AsQueryable(); } var stopwatch = new Stopwatch(); stopwatch.Start(); var tmp = qry.ToList(); var tmp2 = qry2.ToList(); lStats.Text = "Query Runtime: " + stopwatch.Elapsed; stopwatch.Reset(); stopwatch.Start(); var newQry = tmp.Select(g => new { Id = g.GroupMember.Id, RegisteredBy = new ModelValue <Person>(g.RegistrationRegistrant.Registration.PersonAlias.Person), Registrant = new ModelValue <Person>(g.Person), Age = g.Person.Age, GraduationYear = g.Person.GraduationYear, RegistrationId = g.RegistrationRegistrant.RegistrationId, Group = new ModelValue <Rock.Model.Group>((Rock.Model.Group)g.GroupMember.Group), DOB = g.Person.BirthDate.HasValue ? g.Person.BirthDate.Value.ToShortDateString() : "", Address = new ModelValue <Rock.Model.Location>((Rock.Model.Location)tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location).FirstOrDefault()), Email = g.Person.Email, Gender = g.Person.Gender, // (B & B Registration) GraduationYearProfile = g.Person.GraduationYear, // (Person Profile) HomePhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), CellPhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), GroupMemberData = new Func <GroupMemberAttributes>(() => { GroupMemberAttributes gma = new GroupMemberAttributes(g.GroupMember, g.Person, g.GroupMemberAttributeValues); return(gma); })(), RegistrantData = new Func <RegistrantAttributes>(() => { RegistrantAttributes row = new RegistrantAttributes(g.RegistrationRegistrant, g.RegistrationAttributeValues); return(row); })(), School = string.IsNullOrEmpty(g.School)?"":DefinedValueCache.Read(g.School.AsGuid()) != null?DefinedValueCache.Read(g.School.AsGuid()).Value:"", LegalRelease = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.SignatureDocuments).OrderByDescending(sd => sd.SignatureDocument.CreatedDateTime).Where(sd => signatureDocumentIds.Contains(sd.SignatureDocument.SignatureDocumentTemplateId)).Select(sd => sd.SignatureDocument.SignatureDocumentTemplate.Name + " (" + sd.SignatureDocument.Status.ToString() + ")").FirstOrDefault(), Departure = g.GroupMemberAttributeValues.Where(av => av.AttributeKey == "Departure").Select(av => av.Value).FirstOrDefault(), Campus = group.Campus, // Role = group.ParentGroup.GroupType.Name.Contains("Serving") || group.Name.ToLower().Contains("leader")? "Leader":"Student", // MSMGroup = String.Join(", ", groupMemberService.Queryable().Where(gm => gm.PersonId == g.GroupMember.PersonId && gm.Group.GroupTypeId == hsmGroupTypeId && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.Group.Name).ToList()), Person = g.Person, AddressStreet = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null?gm.Location.Street1:"").FirstOrDefault(), AddressCityStateZip = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null ? gm.Location.City + ", " + gm.Location.State + " " + gm.Location.PostalCode : "").FirstOrDefault(), RegistrantName = g.Person.FullName, }).OrderBy(w => w.Registrant.Model.LastName).ToList().AsQueryable(); lStats.Text += "<br />Object Build Runtime: " + stopwatch.Elapsed; stopwatch.Stop(); gReport.GetRecipientMergeFields += GReport_GetRecipientMergeFields; var mergeFields = new List <String>(); mergeFields.Add("Id"); mergeFields.Add("RegisteredBy"); mergeFields.Add("Group"); mergeFields.Add("Registrant"); mergeFields.Add("Age"); mergeFields.Add("GraduationYear"); mergeFields.Add("DOB"); mergeFields.Add("Address"); mergeFields.Add("Email"); mergeFields.Add("Gender"); mergeFields.Add("GraduationYearProfile"); mergeFields.Add("HomePhone"); mergeFields.Add("CellPhone"); mergeFields.Add("GroupMemberData"); mergeFields.Add("RegistrantData"); mergeFields.Add("LegalRelease"); mergeFields.Add("Departure"); mergeFields.Add("Campus"); mergeFields.Add("Role"); mergeFields.Add("MSMGroup"); gReport.CommunicateMergeFields = mergeFields; /* * if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}POA", keyPrefix)))) * { * string poa = GetUserPreference(string.Format("{0}POA", keyPrefix)); * if (poa == "[Blank]") * { * poa = ""; * } * newQry = newQry.Where(q => q.GroupMemberData.POA == poa); * } */ SortProperty sortProperty = gReport.SortProperty; if (sortProperty != null) { gReport.SetLinqDataSource(newQry.Sort(sortProperty)); } else { gReport.SetLinqDataSource(newQry.OrderBy(p => p.Registrant.Model.LastName)); } gReport.DataBind(); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The workflow action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> /// <exception cref="System.NotImplementedException"></exception> public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages) { var checkInState = GetCheckInState(entity, out errorMessages); if (checkInState != null && checkInState.CheckIn.SearchType != null) { var personService = new PersonService(rockContext); var memberService = new GroupMemberService(rockContext); Guid familyGroupTypeGuid = SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); var dvInactive = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid()); if (checkInState.CheckIn.SearchType.Guid.Equals(new Guid(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER))) { string numericPhone = checkInState.CheckIn.SearchValue.AsNumeric(); var personRecordTypeId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; // Find the families with any member who has a phone number that contains selected value var familyQry = memberService .Queryable().AsNoTracking() .Where(m => m.Group.GroupType.Guid.Equals(familyGroupTypeGuid) && m.Person.RecordTypeValueId == personRecordTypeId); if (checkInState.CheckInType != null && checkInState.CheckInType.PreventInactivePeopele && dvInactive != null) { familyQry = familyQry.Where(m => m.Person.RecordStatusValueId != dvInactive.Id); } if (checkInState.CheckInType == null || checkInState.CheckInType.PhoneSearchType == PhoneSearchType.EndsWith) { familyQry = familyQry.Where(m => m.Person.PhoneNumbers.Any(n => n.Number.EndsWith(numericPhone))); } else { familyQry = familyQry.Where(m => m.Person.PhoneNumbers.Any(n => n.Number.Contains(numericPhone))); } var familyIdQry = familyQry .Select(m => m.GroupId) .Distinct(); int maxResults = checkInState.CheckInType != null ? checkInState.CheckInType.MaxSearchResults : 100; if (maxResults > 0) { familyIdQry = familyIdQry.Take(maxResults); } var familyIds = familyIdQry.ToList(); // Load the family members var familyMembers = memberService .Queryable("Group,GroupRole,Person").AsNoTracking() .Where(m => familyIds.Contains(m.GroupId)) .ToList(); // Add each family foreach (int familyId in familyIds) { // Get each of the members for this family var familyMemberQry = familyMembers .Where(m => m.GroupId == familyId && m.Person.NickName != null); if (checkInState.CheckInType != null && checkInState.CheckInType.PreventInactivePeopele && dvInactive != null) { familyMemberQry = familyMemberQry .Where(m => m.Person.RecordStatusValueId != dvInactive.Id); } var thisFamilyMembers = familyMemberQry.ToList(); if (thisFamilyMembers.Any()) { var group = thisFamilyMembers .Select(m => m.Group) .FirstOrDefault(); var firstNames = thisFamilyMembers .OrderBy(m => m.GroupRole.Order) .ThenBy(m => m.Person.BirthYear) .ThenBy(m => m.Person.BirthMonth) .ThenBy(m => m.Person.BirthDay) .ThenBy(m => m.Person.Gender) .Select(m => m.Person.NickName) .ToList(); var family = new CheckInFamily(); family.Group = group.Clone(false); family.Caption = group.ToString(); family.SubCaption = firstNames.AsDelimited(", "); checkInState.CheckIn.Families.Add(family); } } } else if (checkInState.CheckIn.SearchType.Guid.Equals(new Guid(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_NAME))) { var people = personService.GetByFullName(checkInState.CheckIn.SearchValue, false).AsNoTracking(); if (checkInState.CheckInType != null && checkInState.CheckInType.PreventInactivePeopele && dvInactive != null) { people = people.Where(p => p.RecordStatusValueId != dvInactive.Id); } foreach (var person in people) { foreach (var group in person.Members.Where(m => m.Group.GroupType.Guid.Equals(familyGroupTypeGuid)).Select(m => m.Group).ToList()) { var family = checkInState.CheckIn.Families.Where(f => f.Group.Id == group.Id).FirstOrDefault(); if (family == null) { family = new CheckInFamily(); family.Group = group.Clone(false); family.Group.LoadAttributes(rockContext); family.Caption = group.ToString(); if (checkInState.CheckInType == null || !checkInState.CheckInType.PreventInactivePeopele) { family.SubCaption = memberService.GetFirstNames(group.Id).ToList().AsDelimited(", "); } else { family.SubCaption = memberService.GetFirstNames(group.Id, false, false).ToList().AsDelimited(", "); } checkInState.CheckIn.Families.Add(family); } } } } else { errorMessages.Add("Invalid Search Type"); return(false); } return(true); } errorMessages.Add("Invalid Check-in State"); return(false); }
public void DeletePerson() { // //Arrange Person _p = (Person)Records.person.Clone(); _repo = new Mock<IPersonRepository>(); _uow = new Mock<IUnitOfWork>(); _lcache = new Mock<ILookupCache>(); string user = "******"; int id = 1; Person dp = new Person(); _repo.Setup(r => r.Delete(It.IsAny<Person>())).Callback((Person p) => { dp = p; }); _repo.Setup(r => r.GetById(id)).Returns(_p); var _serv = new PersonService(_repo.Object, _uow.Object, _lcache.Object); // //Act _serv.Delete(id, user); // //Assert Assert.AreEqual(dp, _p); }
public Form1() { InitializeComponent(); personService = new PersonService(); }
public void TestInitialize() { _repo = new Mock<IPersonRepository>(); _uow = new Mock<IUnitOfWork>(); _lcache = new Mock<ILookupCache>(); _serv = new PersonService(_repo.Object, _uow.Object, _lcache.Object); }
/// <summary> /// Creates the person. /// </summary> /// <returns></returns> private Person CreatePerson() { var rockContext = new RockContext(); DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read(GetAttributeValue("ConnectionStatus").AsGuid()); DefinedValueCache dvcRecordStatus = DefinedValueCache.Read(GetAttributeValue("RecordStatus").AsGuid()); Person person = new Person(); person.FirstName = tbFirstName.Text; person.LastName = tbLastName.Text; person.Email = tbEmail.Text; person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; if (dvcConnectionStatus != null) { person.ConnectionStatusValueId = dvcConnectionStatus.Id; } if (dvcRecordStatus != null) { person.RecordStatusValueId = dvcRecordStatus.Id; } 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; } } bool smsSelected = false; foreach (RepeaterItem item in rPhoneNumbers.Items) { HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField; PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl("cbUnlisted") as CheckBox; CheckBox cbSms = item.FindControl("cbSms") as CheckBox; if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { int phoneNumberTypeId; if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId)) { var phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add(phoneNumber); phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); // Only allow one number to have SMS selected if (smsSelected) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; } } } PersonService.SaveNewPerson(person, rockContext, null, false); // save address if (pnlAddress.Visible) { if (acAddress.IsValid && !string.IsNullOrWhiteSpace(acAddress.Street1) && !string.IsNullOrWhiteSpace(acAddress.City) && !string.IsNullOrWhiteSpace(acAddress.PostalCode)) { Guid locationTypeGuid = GetAttributeValue("LocationType").AsGuid(); if (locationTypeGuid != Guid.Empty) { Guid familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); GroupService groupService = new GroupService(rockContext); GroupLocationService groupLocationService = new GroupLocationService(rockContext); var family = groupService.Queryable().Where(g => g.GroupType.Guid == familyGroupTypeGuid && g.Members.Any(m => m.PersonId == person.Id)).FirstOrDefault(); var groupLocation = new GroupLocation(); groupLocation.GroupId = family.Id; groupLocationService.Add(groupLocation); var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country); groupLocation.Location = location; groupLocation.GroupLocationTypeValueId = DefinedValueCache.Read(locationTypeGuid).Id; groupLocation.IsMailingLocation = true; groupLocation.IsMappedLocation = true; rockContext.SaveChanges(); } } } return(person); }
public void Bride(PersonModel model) { model.GoomBride = Models.Data.EnumGroomBride.Bride; PersonService.Save(model); }
/// <summary> /// Translates the users. /// </summary> /// <param name="tableData">The table data.</param> /// <param name="totalRows">The total rows.</param> public void TranslateUsers(IQueryable <Row> tableData, long totalRows = 0) { var lookupContext = new RockContext(); var personService = new PersonService(lookupContext); var rockAuthenticatedTypeId = EntityTypeCache.Get(typeof(Rock.Security.Authentication.Database)).Id; var staffGroupId = new GroupService(lookupContext).GetByGuid(new Guid(Rock.SystemGuid.Group.GROUP_STAFF_MEMBERS)).Id; var memberGroupRoleId = new GroupTypeRoleService(lookupContext).Queryable() .Where(r => r.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_SECURITY_GROUP_MEMBER))) .Select(r => r.Id).FirstOrDefault(); var userLoginService = new UserLoginService(lookupContext); var importedUserCount = userLoginService.Queryable().Count(u => u.ForeignId != null); var newUserLogins = new List <UserLogin>(); var newStaffMembers = new List <GroupMember>(); var updatedPersonList = new List <Person>(); if (totalRows == 0) { totalRows = tableData.Count(); } var completedItems = 0; var percentage = (totalRows - 1) / 100 + 1; ReportProgress(0, $"Verifying user import ({totalRows:N0} found, {importedUserCount:N0} already exist)."); foreach (var row in tableData.Where(r => r != null)) { var individualId = row["LinkedIndividualID"] as int?; var userName = row["UserLogin"] as string; var userId = row["UserID"] as int?; if (userId.HasValue && individualId.HasValue && !string.IsNullOrWhiteSpace(userName)) { var personKeys = GetPersonKeys(individualId, null); if (personKeys != null) { var createdDate = row["UserCreatedDate"] as DateTime?; var userEmail = row["UserEmail"] as string; var userTitle = row["UserTitle"] as string; var userPhone = row["UserPhone"] as string; var isEnabled = row["IsUserEnabled"] as bool?; var isStaff = row["IsStaff"] as bool?; var isActive = isEnabled ?? false; var user = AddUserLogin(lookupContext, rockAuthenticatedTypeId, personKeys.PersonId, userName.Trim(), null, isEnabled, false, createdDate, userId.ToString(), ImportPersonAliasId); if (user != null) { // track the user's id and person alias for use with notes PortalUsers.AddOrReplace((int)userId, personKeys.PersonAliasId); if (isStaff == true) { // add this user to the staff group var staffMember = new GroupMember { GroupId = staffGroupId, PersonId = personKeys.PersonId, GroupRoleId = memberGroupRoleId, CreatedDateTime = createdDate, CreatedByPersonAliasId = ImportPersonAliasId, GroupMemberStatus = isActive ? GroupMemberStatus.Active : GroupMemberStatus.Inactive }; newStaffMembers.Add(staffMember); } // set user login email to person's primary email if one isn't set if (!string.IsNullOrWhiteSpace(userEmail) && userEmail.IsEmail()) { var person = !updatedPersonList.Any(p => p.Id == personKeys.PersonId) ? personService.Queryable(includeDeceased: true).FirstOrDefault(p => p.Id == personKeys.PersonId) : updatedPersonList.FirstOrDefault(p => p.Id == personKeys.PersonId); if (person != null && string.IsNullOrWhiteSpace(person.Email)) { person.Email = userEmail.Left(75); person.EmailNote = userTitle; person.IsEmailActive = isEnabled != false; person.EmailPreference = EmailPreference.EmailAllowed; lookupContext.SaveChanges(DisableAuditing); updatedPersonList.Add(person); } } newUserLogins.Add(user); completedItems++; if (completedItems % percentage < 1) { var percentComplete = completedItems / percentage; ReportProgress(percentComplete, $"{completedItems:N0} users imported ({percentComplete}% complete)."); } else if (completedItems % ReportingNumber < 1) { SaveUsers(newUserLogins, newStaffMembers); updatedPersonList.Clear(); newUserLogins.Clear(); newStaffMembers.Clear(); ReportPartialProgress(); } } } } else { LogException("User Import", $"User: {userId} - UserName: {userName} is not linked to a person or already exists."); } } if (newUserLogins.Any()) { SaveUsers(newUserLogins, newStaffMembers); } ReportProgress(100, $"Finished user import: {completedItems:N0} users imported."); }
public PeopleController(PersonService personService) { _personService = personService; }
private void MenuUpdate_Click(object sender, RoutedEventArgs e) { try { if (tb == null) { MessageBox.Show("表格数据不存在"); return; } db = Bll.NewBllNoRelation();//第三个参数要true,不然数据迁移无法用 departments = db.Departments.ToList(); var parentDepName = "3DL粉焦区域";//"中电四会热电有限公司" var parentDep = departments.Find(i => i.Name.Trim() == parentDepName); if (parentDep == null) { parentDep = AddDepartment(parentDepName, departments[1]); } if (parentDep == null) { return; } var ps = new PersonService(db); foreach (DataRow item in tb.Rows) { try { var departmentName = (item[0] + "").Trim(); var personName = (item[1] + "").Trim(); var personCount = (item[2] + "").Trim(); var personNumber = (item[3] + "").Trim(); var cardCode = (item[4] + "").Trim(); var post = (item[5] + "").Trim(); var remark = (item[6] + "").Trim(); //添加部门 var department = departments.Find(i => i.Name.Trim() == departmentName); if (department == null) { department = AddDepartment(departmentName, parentDep); } if (parentDep == null) { return; } LocationCard card = null; if (!string.IsNullOrEmpty(cardCode)) { card = db.LocationCards.Find(i => i.Code.Trim() == cardCode); if (card == null) { //MessageBox.Show("未找到定位卡:" + cardCode + "\n请确认数据是否正确!");//必须有正确的卡号 //return; card = new LocationCard(cardCode, 2);//管理人员卡 var r1 = db.LocationCards.Add(card); if (r1 == false) { MessageBox.Show("添加定位卡失败:" + cardCode + "\n" + db.LocationCards.ErrorMessage); return; } else { Log.Info("添加定位卡:" + cardCode); } } else { } } if (personName == "刘钢") { } Personnel person = db.Personnels.Find(i => i.Name.Trim() == personName); var list = db.LocationCardToPersonnels.ToList(); if (list != null && card != null) { var cTpList = list.Where(i => i.LocationCardId == card.Id).ToList(); if (cTpList != null && cTpList.Count > 0) //已经存在关系 { if (cTpList.Count == 1) //只有一个关系 { var cTp0 = cTpList[0]; Personnel person2 = db.Personnels.Find(i => i.Id == cTp0.PersonnelId); if (person2 != null) { if (person2.Name.StartsWith("Tag_")) //自动创建的 { EditPerson(person2, department, personName, personNumber, post); //更新人员信息 return; } else { } } else { } } else//多个关系 { foreach (LocationCardToPersonnel cpt in cTpList) { if (person != null) { if (cpt.PersonnelId == person.Id) { continue; } } db.LocationCardToPersonnels.Remove(cpt);//清空以前的卡关联关系 } } } else { } } //Personnel person = db.Personnels.Find(i => i.Name.Trim() == personName); if (person == null) { person = AddPerson(department, personName, personNumber, post); if (person == null) { return; } } else { EditPerson(person, department, personName, personNumber, post); } if (card != null) { var cTp1 = list.Find(i => i.LocationCardId == card.Id); var cTp2 = list.Find(i => i.PersonnelId == person.Id); var r2 = ps.BindWithTag(person.Id, card.Id); var cTpList2 = db.LocationCardToPersonnels.Where(i => i.LocationCardId == card.Id); if (r2 == false) { //MessageBox.Show("设置绑定失败:" + personName + "," + cardCode + "\n" + db.Personnels.ErrorMessage); continue; } else { Log.Info("设置绑定:" + personName + "," + cardCode); } } } catch (Exception ex) { MessageBox.Show("解析并写入数据出错:" + ex); return; } } MessageBox.Show("更新成功"); } catch (Exception ex) { MessageBox.Show("更新出错:" + ex); } }
public void UnsuccessfulMatchReturnsNotFound() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); var list = new List<PersonMapping>(); repository.Setup(x => x.Queryable<PersonMapping>()).Returns(list.AsQueryable()); var request = new CrossMappingRequest { SystemName = "Endur", Identifier = "A", ValidAt = SystemTime.UtcNow(), TargetSystemName = "Trayport" }; // Act var contract = service.CrossMap(request); // Assert Assert.IsNotNull(contract, "Contract null"); Assert.IsFalse(contract.IsValid, "Contract valid"); Assert.AreEqual(ErrorType.NotFound, contract.Error.Type, "ErrorType difers"); }
public PersonServiceTest() { _personService = new PersonService("mongodb://localhost", "FamilyTreeTest"); }
public void SuccessMatch() { // Arrange var validatorFactory = new Mock<IValidatorEngine>(); var mappingEngine = new Mock<IMappingEngine>(); var repository = new Mock<IRepository>(); var searchCache = new Mock<ISearchCache>(); var service = new PersonService(validatorFactory.Object, mappingEngine.Object, repository.Object, searchCache.Object); // Domain details var system = new MDM.SourceSystem { Name = "Endur" }; var mapping = new PersonMapping { System = system, MappingValue = "A" }; var targetSystem = new MDM.SourceSystem { Name = "Trayport" }; var targetMapping = new PersonMapping { System = targetSystem, MappingValue = "B", IsDefault = true }; var details = new MDM.PersonDetails { FirstName = "John", LastName = "Smith", Email = "*****@*****.**" }; var person = new MDM.Person { Id = 1 }; person.AddDetails(details); person.ProcessMapping(mapping); person.ProcessMapping(targetMapping); // Contract details var targetIdentifier = new MdmId { SystemName = "Trayport", Identifier = "B" }; mappingEngine.Setup(x => x.Map<PersonMapping, MdmId>(targetMapping)).Returns(targetIdentifier); var list = new List<PersonMapping> { mapping }; repository.Setup(x => x.Queryable<PersonMapping>()).Returns(list.AsQueryable()); var request = new CrossMappingRequest { SystemName = "Endur", Identifier = "A", TargetSystemName = "trayport", ValidAt = SystemTime.UtcNow(), Version = 1 }; // Act var response = service.CrossMap(request); var candidate = response.Contract; // Assert Assert.IsNotNull(response, "Contract null"); Assert.IsTrue(response.IsValid, "Contract invalid"); Assert.IsNotNull(candidate, "Mapping null"); Assert.AreEqual(1, candidate.Mappings.Count, "Identifier count incorrect"); Assert.AreSame(targetIdentifier, candidate.Mappings[0], "Different identifier assigned"); }
/// <summary> /// Gets the name of the facebook user. /// </summary> /// <param name="facebookUser">The facebook user.</param> /// <param name="syncFriends">if set to <c>true</c> [synchronize friends].</param> /// <param name="accessToken">The access token.</param> /// <returns></returns> public static string GetFacebookUserName(FacebookUser facebookUser, bool syncFriends = false, string accessToken = "") { // accessToken is required if (accessToken.IsNullOrWhiteSpace()) { return(null); } string username = string.Empty; string facebookId = facebookUser.id; string facebookLink = facebookUser.link; string userName = "******" + facebookId; UserLogin user = null; using (var rockContext = new RockContext()) { // Query for an existing user var userLoginService = new UserLoginService(rockContext); user = userLoginService.GetByUserName(userName); // If no user was found, see if we can find a match in the person table if (user == null) { // Get name/email from Facebook login string lastName = facebookUser.last_name.ToStringSafe(); string firstName = facebookUser.first_name.ToStringSafe(); string email = string.Empty; try { email = facebookUser.email.ToStringSafe(); } catch { } Person person = null; // If person had an email, get the first person with the same name and email address. if (!string.IsNullOrWhiteSpace(email)) { var personService = new PersonService(rockContext); person = personService.FindPerson(firstName, lastName, email, true); } var personRecordTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; var personStatusPending = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id; rockContext.WrapTransaction(() => { if (person == null) { person = new Person(); person.IsSystem = false; person.RecordTypeValueId = personRecordTypeId; person.RecordStatusValueId = personStatusPending; person.FirstName = firstName; person.LastName = lastName; person.Email = email; person.IsEmailActive = true; person.EmailPreference = EmailPreference.EmailAllowed; try { if (facebookUser.gender.ToString() == "male") { person.Gender = Gender.Male; } else if (facebookUser.gender.ToString() == "female") { person.Gender = Gender.Female; } else { person.Gender = Gender.Unknown; } } catch { } if (person != null) { PersonService.SaveNewPerson(person, rockContext, null, false); } } if (person != null) { int typeId = EntityTypeCache.Get(typeof(Facebook)).Id; user = UserLoginService.Create(rockContext, person, AuthenticationServiceType.External, typeId, userName, "fb", true); } }); } if (user != null) { username = user.UserName; if (user.PersonId.HasValue) { var converter = new ExpandoObjectConverter(); var personService = new PersonService(rockContext); var person = personService.Get(user.PersonId.Value); if (person != null) { // If person does not have a photo, try to get their Facebook photo if (!person.PhotoId.HasValue) { var restClient = new RestClient(string.Format("https://graph.facebook.com/v3.3/{0}/picture?redirect=false&type=square&height=400&width=400", facebookId)); var restRequest = new RestRequest(Method.GET); restRequest.RequestFormat = DataFormat.Json; restRequest.AddHeader("Accept", "application/json"); var restResponse = restClient.Execute(restRequest); if (restResponse.StatusCode == HttpStatusCode.OK) { dynamic picData = JsonConvert.DeserializeObject <ExpandoObject>(restResponse.Content, converter); bool isSilhouette = picData.data.is_silhouette; string url = picData.data.url; // If Facebook returned a photo url if (!isSilhouette && !string.IsNullOrWhiteSpace(url)) { // Download the photo from the URL provided restClient = new RestClient(url); restRequest = new RestRequest(Method.GET); restResponse = restClient.Execute(restRequest); if (restResponse.StatusCode == HttpStatusCode.OK) { var bytes = restResponse.RawBytes; // Create and save the image BinaryFileType fileType = new BinaryFileTypeService(rockContext).Get(Rock.SystemGuid.BinaryFiletype.PERSON_IMAGE.AsGuid()); if (fileType != null) { var binaryFileService = new BinaryFileService(rockContext); var binaryFile = new BinaryFile(); binaryFileService.Add(binaryFile); binaryFile.IsTemporary = false; binaryFile.BinaryFileType = fileType; binaryFile.MimeType = "image/jpeg"; binaryFile.FileName = user.Person.NickName + user.Person.LastName + ".jpg"; binaryFile.FileSize = bytes.Length; binaryFile.ContentStream = new MemoryStream(bytes); rockContext.SaveChanges(); person.PhotoId = binaryFile.Id; rockContext.SaveChanges(); } } } } } if (syncFriends && !string.IsNullOrWhiteSpace(accessToken)) { // Get the friend list (only includes friends who have also authorized this app) var restRequest = new RestRequest(Method.GET); restRequest.AddParameter("access_token", accessToken); restRequest.RequestFormat = DataFormat.Json; restRequest.AddHeader("Accept", "application/json"); var restClient = new RestClient(string.Format("https://graph.facebook.com/v3.3/{0}/friends", facebookId)); var restResponse = restClient.Execute(restRequest); if (restResponse.StatusCode == HttpStatusCode.OK) { // Get a list of the facebook ids for each friend dynamic friends = JsonConvert.DeserializeObject <ExpandoObject>(restResponse.Content, converter); var facebookIds = new List <string>(); foreach (var friend in friends.data) { facebookIds.Add(friend.id); } // Queue a transaction to add/remove friend relationships in Rock var facebookFriendGroupMembers = new UpdateFacebookFriendGroupMembers.Message { FacebookIds = facebookIds, PersonId = person.Id, }; facebookFriendGroupMembers.Send(); } } } } } return(username); } }