public void Handle(CreateMyNewActivityCommand command) { if (command == null) { throw new ArgumentNullException("command"); } //var person = _queryProcessor.Execute( // new GetMyPersonQuery(command.Principal)); var person = _entities.Get <Person>() .ByUserName(command.Principal.Identity.Name); var otherActivities = _entities.Query <Activity>() .WithPersonId(person.RevisionId) ; var activity = new Activity { Person = person, PersonId = person.RevisionId, Number = otherActivities.NextNumber(), }; _entities.Create(activity); command.CreatedActivity = activity; }
public User Handle(GetUserByNameQuery query) { return(_entities.Query <User>() .EagerLoad(_entities, query.EagerLoad) .ByName(query.Name) ); }
public void Seed() { if (_entities.Query <Place>().Any(x => x.IsRegion || x.Components.Any())) { return; } // map Woe ID's to GeoName ID's var regionsToImport = new Dictionary <int, int?> { { 24865706, 7729891 }, // Caribbean { 24865716, 7730009 }, // Latin America //{ 55949058, null }, // Americas { 24865707, 7729892 }, // Central America { 55949061, 7729893 }, // Central Asia { 55949062, 7729895 }, // South Asia { 28289414, 7729896 }, // SouthEast Asia { 28289416, 7729894 }, // East Asia { 28289415, 7729897 }, // West Asia { 24865721, 6269133 }, // Middle East { 24865722, 7729887 }, // North Africa { 55949067, 7729883 }, // North Europe { 55949066, 7729882 }, // South Europe { 28289419, 7729884 }, // East Europe { 28289418, 7729881 }, // West Europe }; foreach (var woeId in regionsToImport.Keys) { var geoNameId = regionsToImport[woeId]; var geoPlanet = _entities.Query <GeoPlanetPlace>().SingleOrDefault(x => x.WoeId == woeId) ?? _queryProcessor.Execute(new SingleGeoPlanetPlace(woeId)); GeoNamesToponym geoName = null; if (geoNameId.HasValue) { geoName = _entities.Query <GeoNamesToponym>().SingleOrDefault(x => x.GeoNameId == geoNameId.Value) ?? _queryProcessor.Execute(new SingleGeoNamesToponym(geoNameId.Value)); } if (geoPlanet.Place == null || (geoName != null && geoName.Place == null)) { _queryProcessor.Execute(new PlaceByWoeId(woeId, geoNameId)); } } ComposeRegionsFromGeoPlanet(); }
public InstitutionalAgreementConfiguration Handle(GetMyInstitutionalAgreementConfigurationQuery query) { if (query == null) { throw new ArgumentNullException("query"); } // make sure user is authorized to view settings if (!query.Principal.IsInAnyRoles(RoleName.InstitutionalAgreementManagers)) { throw new SecurityAccessDeniedException(string.Format( "User '{0}' does not have privileges to invoke this function.", query.Principal.Identity.Name)); } // first, get the principal's affiliation var person = _queryProcessor.Execute(new GetMyPersonQuery(query.Principal) { EagerLoad = new Expression <Func <Person, object> >[] { p => p.Affiliations.Select(a => a.Establishment), }, }); // from person's default affiliation, determine establishment var configurations = (query.IsWritable) ? _entities.Get <InstitutionalAgreementConfiguration>() : _entities.Query <InstitutionalAgreementConfiguration>(); configurations = configurations.EagerLoad(_entities, query.EagerLoad) .Where(c => c.ForEstablishment != null && c.ForEstablishment.IsMember && ( c.ForEstablishmentId == person.DefaultAffiliation.EstablishmentId || c.ForEstablishment.Offspring.Select(a => a.OffspringId) .Contains(person.DefaultAffiliation.EstablishmentId) ) ) .OrderBy(new Dictionary <Expression <Func <InstitutionalAgreementConfiguration, object> >, OrderByDirection> { { c => c.ForEstablishment.Ancestors.Count, OrderByDirection.Descending } }) ; return(configurations.FirstOrDefault()); }
public void Handle(CreateLooseFileCommand command) { if (command == null) { throw new ArgumentNullException("command"); } var entity = new LooseFile { Content = command.Content, Length = command.Content.Length, MimeType = command.MimeType, Name = command.Name, }; _entities.Create(entity); _unitOfWork.SaveChanges(); command.CreatedLooseFile = _entities.Query <LooseFile>() .By(entity.EntityId); }
public void Handle(CreatePlace command) { if (command == null) { throw new ArgumentNullException("command"); } var parent = command.ParentId.HasValue ? _entities.Get <Place>().Single(x => x.RevisionId == command.ParentId.Value) : null; var entity = new Place { OfficialName = command.OfficialName, ParentId = command.ParentId, Parent = parent, IsWater = command.IsWater, IsRegion = command.IsRegion, }; _entities.Create(entity); _hierarchy.Handle(new EnsurePlaceHierarchy(entity)); _entities.SaveChanges(); command.Created = _entities.Query <Place>().Single(x => x.RevisionId == entity.RevisionId); }
public void Perform(AddUsfEmailDomains job) { var emailDomains = new[] { "@usfsp.edu", "@acad.usf.edu", "@acnet.usf.edu", "@admin.usf.edu", "@afrotc.usf.edu", "@arch.usf.edu", "@arotc.usf.edu", "@arts.usf.edu", "@athena.arch.usf.edu", "@banshee.sar.usf.edu", "@bcs.usf.edu", "@bitt.usf.edu", "@cas.usf.edu", "@cchd.usf.edu", "@chuma.cas.usf.edu", "@chuma1.cas.usf.edu", "@coba.usf.edu", "@coedu.usf.edu", "@connect.usf.edu", "@crhsp.usf.edu", "@csl.usf.edu", "@cte.usf.edu", "@cutr.eng.usf.edu", "@cutr.usf.edu", "@cvpa.usf.edu", "@eng.usf.edu", "@enlace.usf.edu", "@fastmail.usf.edu", "@flkin.org", "@fmhi.usf.edu", "@forest.usf.edu", "@grad.usf.edu", "@gsis.usf.edu", "@healthlib.usf.edu", "@honors.usf.edu", "@housing.usf.edu", "@ibl.usf.edu", "@intellis.org", "@intellis.usf.edu", "@intellismedia.com", "@intellismedia.org", "@intellismedia.usf.edu", "@jmslc.usf.edu", "@lakeland.usf.edu", "@lib.usf.edu", "@lklnd.usf.edu", "@luna.cas.usf.edu", "@mail.cas.usf.edu", "@math.usf.edu", "@nrotc.usf.edu", "@phialphatheta.org", "@poly.usf.edu", "@pplant.usf.edu", "@research.usf.edu", "@reserv.usf.edu", "@ritchie.acomp.usf.edu", "@sa.usf.edu", "@sacd.arch.usf.edu", "@sar.usf.edu", "@sg.usf.edu", "@shell.cas.usf.edu", "@success.usf.edu", "@sundome.org", "@tarski.math.usf.edu", "@tempest.coedu.usf.edu", "@theclawatusf.org", "@trustees.usf.edu", "@ugs.usf.edu", "@ur.usf.edu", "@usfedu.mail.onmicrosoft.com", "@uspssenate.usf.edu", "@wateratlas.org", "@wusf.com", "@wusf.net", "@wusf.org", "@wusf.usf.edu", "@wusftv.usf.edu", }; var saveChanges = false; foreach (var emailDomain in emailDomains) { var exists = _entities.Query <EstablishmentEmailDomain>() .SingleOrDefault(x => x.Value.Equals(emailDomain, StringComparison.OrdinalIgnoreCase)); if (exists != null) { continue; } saveChanges = true; _entities.Create(new EstablishmentEmailDomain { EstablishmentId = 3306, Value = emailDomain, }); } if (saveChanges) { _entities.SaveChanges(); } }
public void Handle(ImportUsfEstablishments command) { if (command == null) { throw new ArgumentNullException("command"); } var reportBuilder = command.ReportBuilder ?? new WorkReportBuilder("Import USF Departments"); var service = command.Service; try { #region Skip import if not necessary // do we need to re-import? reportBuilder.Report("Determining whether USF department import should be skipped."); var isSkippable = !string.IsNullOrWhiteSpace(service.LastUpdate) // data has already been sync'd at least once // and the last sync date equals the command's requesting sync date && (string.IsNullOrWhiteSpace(command.LastUpdate) || service.LastUpdate.Equals(command.LastUpdate)) // and the status does not indicate a failure or in-progress state && service.Status == UsfFacultyProfileAttribute.Ready.ToString(); if (isSkippable) { reportBuilder.Report("USF department import will be skipped."); return; // note this will also happen when command.SyncDate == null } #endregion #region Wait on import already in progress // is there already an import in progress? // if so, wait on it to change reportBuilder.Report("Determining whether or not USF department import is in progress."); _entities.Reload(command.Service.Integration); // freshen status from db if (service.Status == UsfFacultyProfileAttribute.InProgress.ToString()) { // wait for the process to complete reportBuilder.Report("USF Department import is in progress, wait for completion."); WaitOnProgress(command, reportBuilder); // if was in progress, and is now ready, do not import again if (command.Service.Status == UsfFacultyProfileAttribute.Ready.ToString()) { reportBuilder.Report("USF Department import is ready, parallel import succeeded."); return; } } #endregion #region Update status, invoke USF service, and load comparison data // begin progress reportBuilder.Report("Setting status to '{0}'.", UsfFacultyProfileAttribute.InProgress.ToString()); command.Service.Status = UsfFacultyProfileAttribute.InProgress.ToString(); _entities.Update(command.Service.Integration); _entities.SaveChanges(); reportBuilder.Report("Status set to '{0}'.", UsfFacultyProfileAttribute.InProgress.ToString()); // invoke departments service reportBuilder.Report("Invoking USF department service."); var departmentsData = _queryProcessor.Execute(new UsfDepartments(command.Service) { ReportBuilder = reportBuilder }); if (departmentsData == null || departmentsData.Departments == null) { throw new InvalidOperationException(string.Format( "Could not obtain departments data for '{0}_{1}'service integration.", command.Service.Integration.Name, command.Service.Integration.TenantId)); } reportBuilder.Report("Deserialized USF department response to CLR object."); reportBuilder.Report("JSON value of deserialized response is:"); reportBuilder.Report(JsonConvert.SerializeObject(departmentsData)); // establishment types will be used later when creating establishments reportBuilder.Report("Loading establishment type entities."); var establishmentTypeName = KnownEstablishmentType.UniversityCampus.AsSentenceFragment(); var campusType = _entities.Query <EstablishmentType>().Single(t => t.EnglishName == establishmentTypeName); establishmentTypeName = KnownEstablishmentType.College.AsSentenceFragment(); var collegeType = _entities.Query <EstablishmentType>().Single(t => t.EnglishName == establishmentTypeName); establishmentTypeName = KnownEstablishmentType.Department.AsSentenceFragment(); var departmentType = _entities.Query <EstablishmentType>().Single(t => t.EnglishName == establishmentTypeName); // order the service results by campus, college, deptid departmentsData.Departments = departmentsData.Departments .OrderBy(x => x.CampusName).ThenBy(x => x.CollegeName).ThenBy(x => x.DepartmentId).ToArray(); // all units will be children of USF reportBuilder.Report("Loading USF establishment entity."); var usf = _entities.Get <Establishment>() .EagerLoad(_entities, new Expression <Func <Establishment, object> >[] { x => x.Children, x => x.Offspring.Select(y => y.Offspring), }) .Single(x => x.RevisionId == command.Service.Integration.TenantId); reportBuilder.Report("USF establishment entity loaded with id '{0}'.", usf.RevisionId); var isChanged = false; #endregion #region Populate campuses // populate the campuses first (they are ranked) var campusRanks = new Dictionary <string, int> { { "Tampa", 1 }, { "Petersburg", 2 }, { "Sarasota", 3 }, }; var campusNames = departmentsData.Departments.Select(x => x.CampusName).Distinct().ToArray(); //campusNames = campusNames.Union(new[] { "Unidentified Campus" }).ToArray(); if (campusNames.Any(x => !campusRanks.Keys.Any(x.Contains))) { throw new InvalidOperationException(string.Format( "USF Service returned unexpected campus '{0}'.", campusNames.First(x => !campusRanks.Keys.Any(x.Contains)))); } reportBuilder.Report("Iterating over {0} campus names.", campusNames.Length); foreach (var campusName in campusNames) { // note that the service returns USF Sarasota, but we want official name to be USF Sarasota-Manatee var campusByName = usf.Children.SingleOrDefault(x => x.Names.Any(y => y.Text.Equals(campusName))); if (campusByName == null) { var createCampusCommand = new CreateEstablishment(command.Principal) { NoCommit = true, NoHierarchy = true, Parent = usf, TypeId = campusType.RevisionId, Rank = campusRanks.Single(x => campusName.Contains(x.Key)).Value, OfficialName = new CreateEstablishmentName(command.Principal) { NoCommit = true, IsOfficialName = true, Text = !campusName.Contains("Sarasota") ? campusName : "USF Sarasota-Manatee", }, }; _createEstablishment.Handle(createCampusCommand); if (campusName.Contains("Sarasota")) { var createCampusNameCommand = new CreateEstablishmentName(command.Principal) { NoCommit = true, Owner = createCampusCommand.Created, Text = campusName, }; _createEstablishmentName.Handle(createCampusNameCommand); } isChanged = true; } } #endregion #region Populate Colleges // get all unique combinations of campus / college var campusColleges = departmentsData.Departments .Select(x => new { x.CampusName, x.CollegeName, }).Distinct() .OrderBy(x => x.CampusName).ThenBy(x => x.CollegeName) .ToArray(); reportBuilder.Report("Iterating over {0} campus colleges.", campusColleges.Length); foreach (var campusCollege in campusColleges) { var collegeInCampus = campusCollege; // does the college already exist? var campus = usf.Children .Single(x => x.Names.Any(y => y.Text.Equals(collegeInCampus.CampusName))); var officialName = string.Format("{0}, {1}", collegeInCampus.CollegeName, campus.OfficialName); var collegeByName = campus.Children .SingleOrDefault(x => x.OfficialName.Equals(officialName) || x.Names.Any(y => y.Text.Equals(collegeInCampus.CollegeName) && y.IsContextName)); if (collegeByName != null) { continue; } var createCollegeCommand = new CreateEstablishment(command.Principal) { NoCommit = true, NoHierarchy = true, Parent = campus, TypeId = collegeType.RevisionId, OfficialName = new CreateEstablishmentName(command.Principal) { NoCommit = true, IsOfficialName = true, Text = officialName, }, }; _createEstablishment.Handle(createCollegeCommand); var createCollegeNameCommand = new CreateEstablishmentName(command.Principal) { NoCommit = true, IsContextName = true, Owner = createCollegeCommand.Created, Text = collegeInCampus.CollegeName, }; _createEstablishmentName.Handle(createCollegeNameCommand); isChanged = true; // does this college have any department id's? var customIds = departmentsData.Departments .Where(x => x.CollegeName == collegeInCampus.CollegeName && x.CampusName == collegeInCampus.CampusName && string.IsNullOrWhiteSpace(x.DepartmentName) ) .Select(x => x.DepartmentId).Distinct() // it is possible that this custom DEPTID is named elsewhere .Where(x => !departmentsData.Departments .Any(y => y.DepartmentId == x && !string.IsNullOrWhiteSpace(y.DepartmentName))) .ToArray(); //var doubleCheckCustomIds = departmentsData.Departments // .Where(x => customIds.Contains(x.DepartmentId)).ToArray(); foreach (var customId in customIds) { createCollegeCommand.Created.CustomIds.Add(new EstablishmentCustomId { Owner = createCollegeCommand.Created, Value = customId, }); } } #endregion #region Populate Departments // we are going to skip all unnamed departments var namedDepartments = departmentsData.Departments .Where(x => !string.IsNullOrWhiteSpace(x.DepartmentName)) .ToArray(); reportBuilder.Report("Iterating over {0} named departments.", namedDepartments.Length); foreach (var departmentData in namedDepartments) { var campus = usf.Children .Single(x => x.Names.Any(y => y.Text.Equals(departmentData.CampusName))); var college = campus.Children .Single(x => x.Names.Any(y => y.Text.Equals(departmentData.CollegeName))); var officialName = string.Format("{0}, {1}, {2}", departmentData.DepartmentName, departmentData.CollegeName, campus.OfficialName); // is the name of the department the same as the name of the college? if (departmentData.DepartmentName == departmentData.CollegeName) { if (college.CustomIds.All(x => x.Value != departmentData.DepartmentId)) { college.CustomIds.Add(new EstablishmentCustomId { Owner = college, Value = departmentData.DepartmentId, }); isChanged = true; } continue; } // does the department already exist? var departmentByName = college.Children .SingleOrDefault(x => x.OfficialName.Equals(officialName) || x.Names.Any(y => y.Text.Equals(departmentData.DepartmentName))); var departmentById = college.Children .SingleOrDefault(x => x.CustomIds.Select(y => y.Value).Contains(departmentData.DepartmentId)); if (departmentByName == null) { if (departmentById == null) { var createDepartmentCommand = new CreateEstablishment(command.Principal) { NoCommit = true, NoHierarchy = true, Parent = college, TypeId = departmentType.RevisionId, OfficialName = new CreateEstablishmentName(command.Principal) { NoCommit = true, IsOfficialName = true, Text = officialName, }, }; _createEstablishment.Handle(createDepartmentCommand); var createDepartmentNameCommand = new CreateEstablishmentName(command.Principal) { NoCommit = true, IsContextName = true, Owner = createDepartmentCommand.Created, Text = departmentData.DepartmentName, }; _createEstablishmentName.Handle(createDepartmentNameCommand); departmentByName = createDepartmentCommand.Created; } else { var formerContextNames = departmentById.Names.Where(x => x.IsContextName).ToArray(); foreach (var formerContextName in formerContextNames) { formerContextName.IsFormerName = true; } var newContextName = formerContextNames.SingleOrDefault(x => x.Text == departmentData.DepartmentName); if (newContextName != null) { newContextName.IsFormerName = false; } else { departmentById.Names.Add(new EstablishmentName { ForEstablishment = departmentById, IsContextName = true, Text = departmentData.DepartmentName, }); } departmentById.Names.Single(x => x.IsOfficialName).Text = officialName; departmentById.OfficialName = officialName; departmentByName = departmentById; } isChanged = true; } if (departmentById == null) { departmentByName.CustomIds.Add(new EstablishmentCustomId { Owner = departmentByName, Value = departmentData.DepartmentId, }); isChanged = true; } } #endregion #region Populate Unnamed Department Id's var unnamedDepartments = departmentsData.Departments .Where(x => string.IsNullOrWhiteSpace(x.DepartmentName)) .ToArray(); foreach (var departmentData in unnamedDepartments) { var campus = usf.Children .Single(x => x.Names.Any(y => y.Text.Equals(departmentData.CampusName))); var college = campus.Children .Single(x => x.Names.Any(y => y.Text.Equals(departmentData.CollegeName))); if (college.CustomIds.All(x => x.Value != departmentData.DepartmentId)) { college.CustomIds.Add(new EstablishmentCustomId { EstablishmentId = college.RevisionId, Owner = college, Value = departmentData.DepartmentId, }); isChanged = true; } } #endregion if (isChanged) { // TODO: only update hierarchy when establishments are added or removed reportBuilder.Report("USF Department import has pending database changes."); _updateHierarchy.Handle(new UpdateEstablishmentHierarchy(usf)); _entities.SaveChanges(); reportBuilder.Report("USF Department import pending database changes have been committed."); } reportBuilder.Report("USF Department import is complete."); reportBuilder.Report("Setting status to '{0}'.", UsfFacultyProfileAttribute.Ready.ToString()); command.Service.Status = UsfFacultyProfileAttribute.Ready.ToString(); reportBuilder.Report("Setting last update to '{0}'.", command.LastUpdate); command.Service.LastUpdate = command.LastUpdate; _entities.Update(command.Service.Integration); _entities.SaveChanges(); reportBuilder.Report("Status set to '{0}'.", UsfFacultyProfileAttribute.Ready.ToString()); } catch { reportBuilder.Report("USF Department import encountered an exception."); _entities.DiscardChanges(); reportBuilder.Report("Setting status to '{0}'.", UsfFacultyProfileAttribute.FailedState.ToString()); command.Service.Status = UsfFacultyProfileAttribute.FailedState.ToString(); _entities.Update(command.Service.Integration); _entities.SaveChanges(); reportBuilder.Report("Status set to '{0}'.", UsfFacultyProfileAttribute.FailedState.ToString()); reportBuilder.Report("Rethrowing exception."); throw; } }
public override void Seed() { if (_entities.Query <Place>().Any()) { return; } var earth = _queryProcessor.Execute(new GetPlaceByWoeIdQuery { WoeId = GeoPlanetPlace.EarthWoeId }); Debug.Assert(earth != null); var geoPlanetContinents = _geoPlanet.Continents() .OrderBy(c => c.Name) .ToArray() ; foreach (var geoPlanetContinent in geoPlanetContinents) { var continent = _queryProcessor.Execute(new GetPlaceByWoeIdQuery { WoeId = geoPlanetContinent.WoeId }); Debug.Assert(continent != null); } //var countriesToImport = new[] //{ // "United States", "China", "United Kingdom", "Peru", "South Africa", "Australia", "India", "Egypt", //}; var countriesToImport = new[] { "United States", "China", "United Kingdom", }; var geoPlanetCountries = _geoPlanet.Countries() .Where(c => countriesToImport.Contains(c.Name)) .OrderBy(c => c.Name) .ToArray() ; foreach (var geoPlanetCountry in geoPlanetCountries) { var country = _queryProcessor.Execute(new GetPlaceByWoeIdQuery { WoeId = geoPlanetCountry.WoeId }); Debug.Assert(country != null); } foreach (var geoPlanetCountry in geoPlanetCountries) { var geoPlanetStates = _geoPlanet.States(geoPlanetCountry.WoeId) .OrderBy(s => s.Name) .Take(5) .ToArray() ; if (!geoPlanetStates.Any()) { continue; } foreach (var geoPlanetState in geoPlanetStates) { var state = _queryProcessor.Execute(new GetPlaceByWoeIdQuery { WoeId = geoPlanetState.WoeId }); Debug.Assert(state != null); } } }
public void Handle(ImportUsfPerson command) { if (command == null) { throw new ArgumentNullException("command"); } var reportBuilder = command.ReportBuilder ?? new WorkReportBuilder("Import USF Person"); // find user by id reportBuilder.Report("Querying database for user #{0}.", command.UserId); var user = _entities.Get <User>() .EagerLoad(_entities, new Expression <Func <User, object> >[] { x => x.Person.Affiliations, }) .Single(x => x.RevisionId == command.UserId); reportBuilder.Report("Found matching user with name '{0}'.", user.Name); // invoke USF person service reportBuilder.Report("Invoking USF person service with user name '{0}'.", user.Name); //const string testJson = "{\"Last Name\":\"Hernandez\",\"First Name\":\"Mario\",\"Middle Name\":\" \",\"Suffix\":\" \",\"Gender\":\"Male\",\"USF Email Address\":\"[email protected]\",\"lastUpdate\":\"05-28-2013\",\"profile\":[{\"DEPTID\":\"0-5830-001\",\"Faculty Rank\":\"2\",\"Position Title\":\"Professor\",\"Institutional Affiliation\":\"USF Tampa\",\"College\":\"College of Behavioral and Community Sciences\",\"Department/Program\":\"Division of Administration and Communication\"},{\"DEPTID\":\"0-6405-000\",\"Faculty Rank\":\"2\",\"Position Title\":\"Professor\",\"Institutional Affiliation\":\"USF Tampa\",\"College\":\"College of Public Health\",\"Department/Program\":\"Department of Community and Family Health\"}]}"; //var usfPerson = JsonConvert.DeserializeObject<UsfPersonData>(testJson); var usfPerson = _queryProcessor.Execute(new UsfPerson(command.Service, user.Name) { ReportBuilder = reportBuilder, }); if (usfPerson == null) { throw new InvalidOperationException(string.Format( "Could not obtain data for user '{2}' using '{0}_{1}'service integration.", command.Service.Integration.Name, command.Service.Integration.TenantId, user.Name)); } reportBuilder.Report("Deserialized USF person response to CLR object."); reportBuilder.Report("JSON value of deserialized response is:"); reportBuilder.Report(JsonConvert.SerializeObject(usfPerson)); reportBuilder.Report("Invoking command to import USF organization data."); _importEstablishments.Handle(new ImportUsfEstablishments(command.Principal, command.Service, usfPerson.LastUpdate) { ReportBuilder = reportBuilder, }); // check affiliations (only do this once when created) if (usfPerson.Affiliations != null && usfPerson.Affiliations.Any()) { reportBuilder.Report("USF person has affiliations, loading offspring and module settings."); var usf = _entities.Query <Establishment>() .EagerLoad(_entities, new Expression <Func <Establishment, object> >[] { x => x.Offspring, }) .Single(x => x.RevisionId == command.Service.Integration.TenantId); var offspring = usf.Offspring.Select(x => x.Offspring).ToArray(); var settings = _queryProcessor.Execute(new EmployeeSettingsByEstablishment(usf.RevisionId) { EagerLoad = new Expression <Func <EmployeeModuleSettings, object> >[] { x => x.FacultyRanks, }, }); reportBuilder.Report("Iterating over {0} affiliations.", usfPerson.Affiliations.Length); var createdAffiliations = new List <Affiliation>(); foreach (var usfAffiliation in usfPerson.Affiliations) { // make sure the establishment exists var establishment = offspring.SingleOrDefault(x => x.CustomIds.Any(y => y.Value == usfAffiliation.DepartmentId)); if (establishment == null) { throw new InvalidOperationException(string.Format( "Could not find UCosmic establishment for USF Department '{0}'.", usfAffiliation.DepartmentId)); } // make sure the affiliation is not a duplicate if (createdAffiliations.Any(x => x.EstablishmentId == establishment.RevisionId && x.PersonId == user.Person.RevisionId)) { continue; } var facultyRank = settings.FacultyRanks.SingleOrDefault(x => x.Rank == usfAffiliation.PositionTitle); var createAffiliationCommand = new CreateAffiliation(command.Principal, user.Person.RevisionId, establishment.RevisionId) { NoCommit = true, FacultyRankId = facultyRank != null ? facultyRank.Id : (int?)null, }; _createAffiliation.Handle(createAffiliationCommand); createdAffiliations.Add(createAffiliationCommand.Created); } } // possibly add a new email addresss if (!user.Name.Equals(usfPerson.EmailAddress, StringComparison.OrdinalIgnoreCase)) { reportBuilder.Report("USF person has email address '{0}' different from username.", usfPerson.EmailAddress); // create user command will already have created an email based on the username / EPPN // we trust USF email addresses, so change the email added during person creation user.Person.Emails.Single(x => x.IsDefault).Value = usfPerson.EmailAddress; } // update person var displayName = _queryProcessor.Execute(new GenerateDisplayName { FirstName = usfPerson.FirstName, MiddleName = usfPerson.MiddleName, LastName = usfPerson.LastName, Suffix = usfPerson.Suffix, }); if (string.IsNullOrWhiteSpace(displayName)) { displayName = usfPerson.EmailAddress; } var updatePersonCommand = new UpdatePerson(command.Principal, user.Person.RevisionId) { NoCommit = true, FirstName = usfPerson.FirstName, MiddleName = usfPerson.MiddleName, LastName = usfPerson.LastName, Gender = string.IsNullOrWhiteSpace(usfPerson.Gender) ? "P" : usfPerson.Gender.Substring(0, 1).ToUpper(), Suffix = usfPerson.Suffix, DisplayName = displayName, IsDisplayNameDerived = false, IsActive = true, }; _updatePerson.Handle(updatePersonCommand); reportBuilder.Report("Committing changes based on USF person response."); _entities.SaveChanges(); reportBuilder.Report("Committed changes based on USF person response."); }