示例#1
0
        public void Handle(UpdateContactPhone command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var entity = _entities.Get <AgreementContactPhone>()
                         .Single(x => x.Id == command.PhoneId && x.OwnerId == command.ContactId && x.Owner.AgreementId == command.AgreementId);

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    command.AgreementId,
                    command.ContactId,
                    command.PhoneId,
                    command.Type,
                    command.Value,
                }),
                PreviousState = entity.ToJsonAudit(),
            };

            // update fields
            entity.Type  = command.Type;
            entity.Value = command.Value;

            audit.NewState = entity.ToJsonAudit();
            _entities.Create(audit);
            _entities.Update(entity);
            _unitOfWork.SaveChanges();
        }
        public void Handle(UpdateLanguageExpertise command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            /* Retrieve the expertise to update. */
            var target = _entities.Get <LanguageExpertise>().SingleOrDefault(a => a.RevisionId == command.Id);

            if (target == null)
            {
                string message = String.Format("LanguageExpertise Id {0} not found.", command.Id);
                throw new Exception(message);
            }

            /* Update fields */
            target.LanguageId           = command.LanguageId;
            target.Other                = command.Other;
            target.Dialect              = command.Dialect;
            target.SpeakingProficiency  = command.SpeakingProficiency;
            target.ListeningProficiency = command.ListeningProficiency;
            target.ReadingProficiency   = command.ReadingProficiency;
            target.WritingProficiency   = command.WritingProficiency;
            target.UpdatedOnUtc         = command.UpdatedOn.ToUniversalTime();
            target.UpdatedByPrincipal   = command.Principal.Identity.Name;

            _entities.Update(target);

            if (!command.NoCommit)
            {
                _unitOfWork.SaveChanges();
            }
        }
示例#3
0
        public void Handle(UpdateMyEmailValueCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            command.ChangedState = false;

            // get the email address
            var email = _entities.Get <EmailAddress>()
                        .ByUserNameAndNumber(command.Principal.Identity.Name, command.Number);

            // only process matching email
            if (email == null)
            {
                return;
            }

            // only update the value if it was respelled
            if (email.Value == command.NewValue)
            {
                return;
            }

            email.Value = command.NewValue;
            _entities.Update(email);
            command.ChangedState = true;
        }
示例#4
0
        public void Handle(CreatePasswordCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // get the confirmation
            var confirmation = _entities.Get <EmailConfirmation>()
                               .EagerLoad(_entities, new Expression <Func <EmailConfirmation, object> >[]
            {
                c => c.EmailAddress.Person.User.EduPersonScopedAffiliations,
                c => c.EmailAddress.Person.User.SubjectNameIdentifiers,
            })
                               .ByToken(command.Token);

            // set up user accounts
            var person = confirmation.EmailAddress.Person;

            person.User                     = person.User ?? new User();
            person.User.Name                = person.User.Name ?? confirmation.EmailAddress.Value;
            person.User.IsRegistered        = true;
            person.User.EduPersonTargetedId = null;
            person.User.EduPersonScopedAffiliations.Clear();
            person.User.SubjectNameIdentifiers.Clear();

            confirmation.RetiredOnUtc = DateTime.UtcNow;
            confirmation.SecretCode   = null;
            confirmation.Ticket       = null;
            _entities.Update(confirmation);

            _passwords.Create(confirmation.EmailAddress.Person.User.Name, command.Password);
        }
示例#5
0
        public void Handle(RedeemEmailConfirmation command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // get the confirmation
            var confirmation = _entities.Get <EmailConfirmation>()
                               .EagerLoad(_entities, new Expression <Func <EmailConfirmation, object> >[]
            {
                c => c.EmailAddress
            })
                               .ByToken(command.Token);

            // redeem
            if (!confirmation.RedeemedOnUtc.HasValue)
            {
                confirmation.EmailAddress.IsConfirmed = true;
                confirmation.RedeemedOnUtc            = DateTime.UtcNow;
                confirmation.Ticket = HandleGenerateRandomSecretQuery.Handle(
                    new GenerateRandomSecret(256));
                _entities.Update(confirmation);
            }

            command.Ticket = confirmation.Ticket;
        }
示例#6
0
        public void Handle(DeleteMyPhoto command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var person = _entities.Get <Person>()
                         .EagerLoad(_entities, new Expression <Func <Person, object> >[]
            {
                x => x.Photo,
            })
                         .ByUserName(command.Principal.Identity.Name);

            // if command has filenames, only delete photo if it matches one of them
            if (command.FileNames != null && !command.FileNames.Contains(person.Photo.Name))
            {
                return;
            }

            // only delete if there is a photo present
            var photo = person.Photo;

            if (photo == null)
            {
                return;
            }

            // unlink the photo before deleting
            person.Photo = null;

            // delete the photo from binary storage (if it exists there)
            if (!string.IsNullOrWhiteSpace(photo.Path))
            {
                _binaryData.Delete(photo.Path);
            }

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    command.FileNames,
                    User = command.Principal.Identity.Name,
                }),
                PreviousState = photo.ToJsonAudit(),
            };

            // push to database
            _entities.Update(person);
            _entities.Purge(photo);
            _entities.Create(audit);
            if (!command.NoCommit)
            {
                _unitOfWork.SaveChanges();
            }
        }
示例#7
0
        public void Handle(UpdateAgreement command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var entity = _entities.Get <Agreement>().Single(x => x.Id == command.AgreementId);

            // umbrella entity reference is needed for domain to update the hierarchy nodes
            var umbrella = command.UmbrellaId.HasValue
                ? _entities.Get <Agreement>().Single(x => x.Id == command.UmbrellaId.Value) : null;

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    command.AgreementId,
                    command.UmbrellaId,
                    command.Type,
                    command.Name,
                    command.Content,
                    command.Notes,
                    command.StartsOn,
                    command.ExpiresOn,
                    command.IsExpirationEstimated,
                    command.IsAutoRenew,
                    command.Status,
                    command.Visibility,
                }),
                PreviousState = entity.ToJsonAudit(),
            };

            entity.Umbrella              = umbrella;
            entity.UmbrellaId            = umbrella != null ? umbrella.Id : (int?)null;
            entity.Type                  = command.Type;
            entity.Name                  = command.Name;
            entity.Content               = command.Content;
            entity.Notes                 = command.Notes;
            entity.StartsOn              = command.StartsOn;
            entity.ExpiresOn             = command.ExpiresOn;
            entity.IsExpirationEstimated = command.IsExpirationEstimated;
            entity.IsAutoRenew           = command.IsAutoRenew;
            entity.Status                = command.Status;
            entity.Visibility            = command.Visibility.AsEnum <AgreementVisibility>();
            entity.UpdatedByPrincipal    = command.Principal.Identity.Name;
            entity.UpdatedOnUtc          = DateTime.UtcNow;

            audit.NewState = entity.ToJsonAudit();
            _entities.Create(audit);
            _entities.Update(entity);
            _hierarchyHandler.Handle(new UpdateAgreementHierarchy(entity));
            _unitOfWork.SaveChanges();
        }
示例#8
0
        public void Handle(UpdateMyPhoto command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var person = _entities.Get <Person>()
                         .EagerLoad(_entities, new Expression <Func <Person, object> >[]
            {
                x => x.Photo,
            })
                         .ByUserName(command.Principal.Identity.Name);

            // delete previous file
            _photoDeleteHandler.Handle(new DeleteMyPhoto(command.Principal)
            {
                NoCommit = true,
            });

            // create new file
            var path         = string.Format(Person.PhotoPathFormat, person.RevisionId, Guid.NewGuid());
            var externalFile = new ExternalFile
            {
                Name     = command.Name,
                Path     = path,
                Length   = command.Content.Length,
                MimeType = command.MimeType,
            };

            person.Photo = externalFile;
            _binaryData.Put(path, command.Content);

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    User = command.Principal.Identity.Name,
                    command.Content,
                    command.Name,
                    command.MimeType,
                }),
                NewState = externalFile.ToJsonAudit(),
            };

            // push to database
            _entities.Create(externalFile);
            _entities.Update(person);
            _entities.Create(audit);
            if (!command.NoCommit)
            {
                _unitOfWork.SaveChanges();
            }
        }
        public void Handle(UpdateMyPreference command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var preferences = _entities.Get <Preference>();

            if (command.HasPrincipal)
            {
                preferences = preferences.ByPrincipal(command.Principal);
            }
            else if (command.IsAnonymous)
            {
                preferences = preferences.ByAnonymousId(command.AnonymousId);
            }

            var preference = preferences
                             .ByCategory(command.Category)
                             .ByKey(command.Key)
                             .SingleOrDefault();

            if (preference == null)
            {
                if (command.HasPrincipal)
                {
                    preference = new Preference(_entities.Get <User>().ByPrincipal(command.Principal));
                }

                else if (command.IsAnonymous)
                {
                    preference = new Preference(command.AnonymousId);
                }

                else
                {
                    return;
                }

                preference.Category = command.Category.ToString();
                preference.Key      = command.Key.ToString();
                preference.Value    = command.Value;
                _entities.Create(preference);
            }
            else
            {
                preference.Value = command.Value;
                _entities.Update(preference);
            }
        }
示例#10
0
        public void Handle(ResetPassword command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // get the confirmation
            var confirmation = _entities.Get <EmailConfirmation>()
                               .ByToken(command.Token);

            _passwords.Reset(confirmation.EmailAddress.Person.User.Name, command.Password);
            confirmation.RetiredOnUtc = DateTime.UtcNow;
            confirmation.SecretCode   = null;
            confirmation.Ticket       = null;
            _entities.Update(confirmation);
        }
示例#11
0
        public void Handle(CreateLanguageName command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var language = _entities.FindByPrimaryKey <Language>(command.LanguageId);

            language.Names.Add(new LanguageName
            {
                Number = language.Names.NextNumber(),
                Text   = command.Text,
                TranslationToLanguageId = command.TranslationToLanguageId,
            });

            _entities.Update(language);
        }
示例#12
0
        public void Handle(UpdateRole command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            if (!command.Principal.IsInRole(RoleName.AuthorizationAgent))
            {
                throw new InvalidOperationException(string.Format(
                                                        "User '{0}' does not have privileges to invoke this function.",
                                                        command.Principal.Identity.Name));
            }

            var entity = _entities.Get <Role>()
                         .EagerLoad(_entities, new Expression <Func <Role, object> >[]
            {
                r => r.Grants.Select(g => g.User)
            })
                         .SingleOrDefault(x => x.EntityId == command.EntityId);

            if (entity == null)
            {
                throw new InvalidOperationException(string.Format(
                                                        "Entity '{0}' could not be found.", command.EntityId));
            }
            command.ChangeCount = 0;

            if (entity.Description != command.Description)
            {
                ++command.ChangeCount;
            }
            entity.Description = command.Description;

            if (command.ChangeCount < 1)
            {
                return;
            }

            entity.UpdatedByPrincipal = command.Principal.Identity.Name;
            entity.UpdatedOnUtc       = DateTime.UtcNow;

            _entities.Update(entity);
        }
示例#13
0
        public void Handle(UpdateEstablishment command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var entity = _entities.Get <Establishment>()
                         .EagerLoad(_entities, new Expression <Func <Establishment, object> >[]
            {
                e => e.Location.Places,
            })
                         .By(command.Id);

            if (command.CenterLatitude.HasValue && command.CenterLongitude.HasValue)
            {
                entity.Location.Center = new Coordinates(command.CenterLatitude, command.CenterLongitude);
            }

            if (command.NorthLatitude.HasValue && command.EastLongitude.HasValue &&
                command.SouthLatitude.HasValue && command.WestLongitude.HasValue)
            {
                entity.Location.BoundingBox = new BoundingBox(command.NorthLatitude, command.EastLongitude,
                                                              command.SouthLatitude, command.WestLongitude);
            }

            if (command.GoogleMapZoomLevel.HasValue)
            {
                entity.Location.GoogleMapZoomLevel = command.GoogleMapZoomLevel;
            }

            if (command.PlaceIds != null && command.PlaceIds.Any())
            {
                entity.Location.Places.Clear();
                foreach (var placeId in command.PlaceIds)
                {
                    entity.Location.Places.Add(_entities.Get <Place>().By(placeId));
                }
            }

            _entities.Update(entity);
            _hierarchy.Handle(new UpdateEstablishmentHierarchyCommand(entity));
        }
示例#14
0
        public void Handle(SendEmailMessageCommand command)
        {
            // get a fresh email address from the database
            EmailMessage emailMessage = null;

            while (emailMessage == null && ++_retryCount < RetryLimit)
            {
                if (_retryCount > 1)
                {
                    Thread.Sleep(300);
                }

                var person = _entities.Get <Person>()
                             .EagerLoad(_entities, new Expression <Func <Person, object> >[]
                {
                    p => p.Messages,
                })
                             .SingleOrDefault(x => x.RevisionId == command.PersonId);
                emailMessage = person != null
                    ? person.Messages.SingleOrDefault(x => x.Number == command.MessageNumber) : null;
            }
            if (emailMessage == null)
            {
                var exception = new OperationCanceledException(string.Format(
                                                                   "Unable to locate EmailMessage number '{0}' for person '{1}'. The message send operation was canceled after {2} retries.",
                                                                   command.MessageNumber, command.PersonId, _retryCount));
                _exceptionLogger.Log(exception);
                throw exception;
            }

            // convert email message to mail message
            var mail = _queryProcessor.Execute(
                new ComposeMailMessage(emailMessage)
                );

            // send the mail message
            _mailSender.Send(mail);

            // log when the message was sent
            emailMessage.SentOnUtc = DateTime.UtcNow;
            _entities.Update(emailMessage);
        }
示例#15
0
        public void Handle(UpdateFile command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var entity = _entities.Get <AgreementFile>().Single(x => x.Id == command.FileId);

            // TODO: This will have to be removed when visibility for agreement files is patched.
            if (string.IsNullOrWhiteSpace(entity.VisibilityText))
            {
                entity.Visibility = AgreementVisibility.Private;
            }

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    command.AgreementId,
                    command.FileId,
                    command.CustomName,
                    Visibility = command.Visibility.AsEnum <AgreementVisibility>(),
                }),
                PreviousState = entity.ToJsonAudit(),
            };

            entity.Visibility         = command.Visibility.AsEnum <AgreementVisibility>();
            entity.Name               = HandleCreateFileCommand.GetExtensionedCustomName(command.CustomName, entity.FileName);
            entity.UpdatedByPrincipal = command.Principal.Identity.Name;
            entity.UpdatedOnUtc       = DateTime.UtcNow;

            audit.NewState = entity.ToJsonAudit();
            _entities.Create(audit);
            _entities.Update(entity);
            _unitOfWork.SaveChanges();
        }
        public void Handle(UpdateGeographicExpertiseLocation command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            /* Retrieve the degree to update. */
            var target = _entities.Get <GeographicExpertiseLocation>().Single(a => a.RevisionId == command.Id);

            if (target == null)
            {
                string message = String.Format("GeographicExpertiseLocation Id {0} not found.", command.Id);
                throw new Exception(message);
            }

            var updateExpertise = new GeographicExpertiseLocation
            {
                PlaceId = command.PlaceId,
            };

            if (target.Equals(updateExpertise))
            {
                return;
            }

            /* Update fields */
            target.PlaceId            = command.PlaceId;
            target.UpdatedOnUtc       = command.UpdatedOn.ToUniversalTime();
            target.UpdatedByPrincipal = command.Principal.Identity.Name;

            _entities.Update(target);

            if (!command.NoCommit)
            {
                _unitOfWork.SaveChanges();
            }
        }
示例#17
0
        public void Handle(UpdateDegree command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            /* Retrieve the degree to update. */
            var target = _entities.Get <Degree>().Single(a => a.RevisionId == command.DegreeId);

            var updateDegree = new Degree
            {
                Title         = command.Title,
                FieldOfStudy  = command.FieldOfStudy,
                YearAwarded   = command.YearAwarded,
                InstitutionId = command.InstitutionId
            };

            if (target.Equals(updateDegree))
            {
                return;
            }

            /* Update fields */
            target.Title              = command.Title;
            target.FieldOfStudy       = command.FieldOfStudy;
            target.YearAwarded        = command.YearAwarded;
            target.InstitutionId      = command.InstitutionId;
            target.UpdatedOnUtc       = DateTime.UtcNow;
            target.UpdatedByPrincipal = command.Principal.Identity.Name;

            _entities.Update(target);

            if (!command.NoCommit)
            {
                _unitOfWork.SaveChanges();
            }
        }
示例#18
0
        public void Handle(CreateOrUpdateConfigurationCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // make sure user is authorized to update settings
            if (!command.Principal.IsInRole(RoleName.InstitutionalAgreementSupervisor))
            {
                throw new SecurityAccessDeniedException(string.Format(
                                                            "User '{0}' does not have privileges to invoke this function.",
                                                            command.Principal.Identity.Name));
            }

            var configuration = command.Id != 0
                ? _queryProcessor.Execute(
                new GetMyInstitutionalAgreementConfigurationQuery(command.Principal)
            {
                IsWritable = true,
                EagerLoad  = new Expression <Func <InstitutionalAgreementConfiguration, object> >[]
                {
                    c => c.AllowedTypeValues,
                    c => c.AllowedStatusValues,
                    c => c.AllowedContactTypeValues,
                }
            })
                : new InstitutionalAgreementConfiguration
            {
                ForEstablishment = _entities.Get <Person>()
                                   .EagerLoad(_entities, new Expression <Func <Person, object> >[]
                {
                    x => x.Affiliations.Select(y => y.Establishment)
                })
                                   .ByUserName(command.Principal.Identity.Name)
                                   .DefaultAffiliation.Establishment,
            };

            if (configuration.RevisionId != command.Id)
            {
                throw new SecurityAccessDeniedException(string.Format(
                                                            "User '{0}' does not own '{1}' with id '{2}'.",
                                                            command.Principal.Identity.Name,
                                                            typeof(InstitutionalAgreementConfiguration).Name,
                                                            command.Id));
            }

            configuration.IsCustomTypeAllowed        = command.IsCustomTypeAllowed;
            configuration.IsCustomStatusAllowed      = command.IsCustomStatusAllowed;
            configuration.IsCustomContactTypeAllowed = command.IsCustomContactTypeAllowed;

            if (command.AllowedTypeValues != null)
            {
                var commandItems = command.AllowedTypeValues.ToArray();
                var entityItems  = configuration.AllowedTypeValues.ToList();
                foreach (var entityItem in entityItems)
                {
                    // remove when does not exist in command
                    var remove = commandItems.All(p => p != entityItem.Text);
                    if (remove)
                    {
                        _entities.Purge(entityItem);
                    }
                }
                foreach (var commandItem in commandItems)
                {
                    // add when does not exist in entity
                    var add = entityItems.All(p => p.Text != commandItem);
                    if (add)
                    {
                        _entities.Create(
                            new InstitutionalAgreementTypeValue
                        {
                            Configuration = configuration,
                            Text          = commandItem,
                        });
                    }
                }
            }

            if (command.AllowedStatusValues != null)
            {
                var commandItems = command.AllowedStatusValues.ToArray();
                var entityItems  = configuration.AllowedStatusValues.ToList();
                foreach (var entityItem in entityItems)
                {
                    // remove when does not exist in command
                    var remove = commandItems.All(p => p != entityItem.Text);
                    if (remove)
                    {
                        _entities.Purge(entityItem);
                    }
                }
                foreach (var commandItem in commandItems)
                {
                    // add when does not exist in entity
                    var add = entityItems.All(p => p.Text != commandItem);
                    if (add)
                    {
                        _entities.Create(
                            new InstitutionalAgreementStatusValue
                        {
                            Configuration = configuration,
                            Text          = commandItem,
                        });
                    }
                }
            }

            if (command.AllowedContactTypeValues != null)
            {
                var commandItems = command.AllowedContactTypeValues.ToArray();
                var entityItems  = configuration.AllowedContactTypeValues.ToList();
                foreach (var entityItem in entityItems)
                {
                    // remove when does not exist in command
                    var remove = commandItems.All(p => p != entityItem.Text);
                    if (remove)
                    {
                        _entities.Purge(entityItem);
                    }
                }
                foreach (var commandItem in commandItems)
                {
                    // add when does not exist in entity
                    var add = entityItems.All(p => p.Text != commandItem);
                    if (add)
                    {
                        _entities.Create(
                            new InstitutionalAgreementContactTypeValue
                        {
                            Configuration = configuration,
                            Text          = commandItem,
                        });
                    }
                }

                if (command.Id != 0)
                {
                    _entities.Update(configuration);
                }
                else
                {
                    _entities.Create(configuration);
                }
            }
        }
        public void Handle(UpdateInternationalAffiliation command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            /* Retrieve the expertise to update. */
            var target = _entities.Get <InternationalAffiliation>().SingleOrDefault(a => a.RevisionId == command.Id);

            if (target == null)
            {
                string message = String.Format("Affiliation Id {0} not found.", command.Id);
                throw new Exception(message);
            }

            var updated = new InternationalAffiliation
            {
                From        = command.From,
                To          = command.To,
                OnGoing     = command.OnGoing,
                Institution = command.Institution,
                Position    = command.Position,
                Locations   = command.Locations
            };

            /* If target fields equal new field values, we do not proceed. */
            if (target.Equals(updated))
            {
                return;
            }

            /* Run through all new locations and attempt to find same in target.  If not found, create.*/
            foreach (var location in command.Locations.ToList())
            {
                var targetLocation = target.Locations.SingleOrDefault(x => x.PlaceId == location.PlaceId);
                if (targetLocation == null)
                {
                    var createAffiliationLocation = new CreateInternationalAffiliationLocation(
                        command.Principal, target.RevisionId, location.PlaceId)
                    {
                        NoCommit = true
                    };

                    _createAffiliationLocation.Handle(createAffiliationLocation);
                }
            }

            /* Delete activity locations. Run through the targets list of locations and try to find
             *  a matching one in the updated list.  If not found, it must have been deleted. */
            foreach (var location in target.Locations.ToList())
            {
                var updateLocation = command.Locations.SingleOrDefault(x => x.PlaceId == location.PlaceId);
                if (updateLocation == null)
                {
                    var deleteAffiliationLocationCommand = new DeleteInternationalAffiliationLocation(
                        command.Principal, location.RevisionId)
                    {
                        NoCommit = true
                    };

                    _deleteAffiliationLocation.Handle(deleteAffiliationLocationCommand);
                }
            }

            /* Update fields */
            target.From               = command.From;
            target.To                 = command.To;
            target.OnGoing            = command.OnGoing;
            target.Institution        = command.Institution;
            target.Position           = command.Position;
            target.Locations          = command.Locations;
            target.UpdatedOnUtc       = command.UpdatedOn.ToUniversalTime();
            target.UpdatedByPrincipal = command.Principal.Identity.Name;

            _entities.Update(target);

            if (!command.NoCommit)
            {
                _unitOfWork.SaveChanges();
            }
        }
        public void Handle(UpdateEstablishment command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // load target
            var entity = _entities.Get <Establishment>()
                         .EagerLoad(_entities, new Expression <Func <Establishment, object> >[]
            {
                x => x.Type.Category,
                x => x.Parent,
            })
                         .Single(x => x.RevisionId == command.Id);

            // only mutate when state is modified
            var parentChanged = (command.ParentId.HasValue && entity.Parent == null) ||
                                (!command.ParentId.HasValue && entity.Parent != null) ||
                                (command.ParentId.HasValue && entity.Parent != null && command.ParentId != entity.Parent.RevisionId);

            if (command.TypeId == entity.Type.RevisionId &&
                command.CeebCode == entity.CollegeBoardDesignatedIndicator &&
                command.UCosmicCode == entity.UCosmicCode &&
                !parentChanged
                )
            {
                return;
            }

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    command.Id,
                    command.ParentId,
                    command.TypeId,
                    command.CeebCode,
                    command.UCosmicCode,
                    //command.ExternalId
                }),
                PreviousState = entity.ToJsonAudit(),
            };

            // update scalars
            if (entity.Type.RevisionId != command.TypeId)
            {
                var establishmentType = _entities.Get <EstablishmentType>()
                                        .Single(x => x.RevisionId == command.TypeId);
                entity.Type = establishmentType;
            }
            entity.CollegeBoardDesignatedIndicator = command.CeebCode;
            entity.UCosmicCode = command.UCosmicCode;
            //entity.ExternalId = command.ExternalId;

            // update parent
            if (parentChanged)
            {
                entity.Parent = command.ParentId.HasValue
                    ? _entities.Get <Establishment>().Single(x => x.RevisionId == command.ParentId)
                    : null;
            }

            audit.NewState = entity.ToJsonAudit();
            _entities.Create(audit);
            _entities.Update(entity);

            // update hierarchy
            _updateHierarchy.Handle(new UpdateEstablishmentHierarchy(entity));

            if (command.NoCommit)
            {
                return;
            }
            _entities.SaveChanges();
            _eventTrigger.Raise(new EstablishmentChanged());
        }
示例#21
0
        public void Handle(UpdatePerson command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // load target entity
            var entity = command.Person;

            if (entity == null)
            {
                var queryable = _entities.Get <Person>();
                entity = command.PersonId.HasValue
                    ? queryable.Single(x => x.RevisionId == command.PersonId.Value)
                    : queryable.ByUserName(command.Principal.Identity.Name, false);
            }

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    PersonId = command.Person != null ? command.Person.RevisionId : command.PersonId,
                    command.IsActive,
                    command.IsDisplayNameDerived,
                    command.DisplayName,
                    command.Salutation,
                    command.FirstName,
                    command.MiddleName,
                    command.LastName,
                    command.Suffix,
                    command.Gender,
                }),
                PreviousState = entity.ToJsonAudit(),
            };

            // update values
            entity.IsActive   = command.IsActive;
            entity.Salutation = command.Salutation;
            entity.FirstName  = command.FirstName;
            entity.MiddleName = command.MiddleName;
            entity.LastName   = command.LastName;
            entity.Suffix     = command.Suffix;
            entity.Gender     = command.Gender;
            if (string.IsNullOrWhiteSpace(command.DisplayName))
            {
                entity.DisplayName = _queryProcessor.Execute(new GenerateDisplayName
                {
                    Salutation = command.Salutation,
                    FirstName  = command.FirstName,
                    MiddleName = command.MiddleName,
                    LastName   = command.LastName,
                    Suffix     = command.Suffix,
                });
                entity.IsDisplayNameDerived = true;
            }
            else
            {
                entity.DisplayName          = command.DisplayName;
                entity.IsDisplayNameDerived = command.IsDisplayNameDerived;
            }

            // push to database
            audit.NewState = entity.ToJsonAudit();
            _entities.Create(audit);
            if (entity.RevisionId != default(int))
            {
                _entities.Update(entity);
            }

            if (command.NoCommit)
            {
                return;
            }

            _entities.SaveChanges();
        }
示例#22
0
        public void Handle(UpdateGeographicExpertise command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            /* Retrieve the expertise to update. */
            var target = _entities.Get <GeographicExpertise>().SingleOrDefault(a => a.RevisionId == command.Id);

            if (target == null)
            {
                string message = String.Format("GeographicExpertise Id {0} not found.", command.Id);
                throw new Exception(message);
            }

            /* Retrieve the expertise locations to update. */
            var targetLocations = _entities.Get <GeographicExpertiseLocation>().Where(a => a.ExpertiseId == target.RevisionId).ToArray();

            /* If target fields equal new field values, we do not proceed. */
            if ((target.Description == command.Description) &&
                targetLocations.SequenceEqual(command.Locations))
            {
                return;
            }

            /* Run through all new locations and attempt to find same in target.  If not found, create.*/
            foreach (var location in command.Locations.ToList())
            {
                var targetLocation = target.Locations.SingleOrDefault(x => x.PlaceId == location.PlaceId);
                if (targetLocation == null)
                {
                    var createGeographicExpertiseLocation = new CreateGeographicExpertiseLocation(
                        command.Principal, target.RevisionId, location.PlaceId)
                    {
                        NoCommit = true
                    };

                    _createGeographicExpertiseLocation.Handle(createGeographicExpertiseLocation);
                }
            }

            /* Delete activity locations. Run through the targets list of locations and try to find
             *  a matching one in the updated list.  If not found, it must have been deleted. */
            foreach (var location in target.Locations.ToList())
            {
                var updateLocation = command.Locations.SingleOrDefault(x => x.PlaceId == location.PlaceId);
                if (updateLocation == null)
                {
                    var deleteGeographicExpertiseLocationCommand = new DeleteGeographicExpertiseLocation(
                        command.Principal, location.RevisionId)
                    {
                        NoCommit = true
                    };

                    _deleteGeographicExpertiseLocation.Handle(deleteGeographicExpertiseLocationCommand);
                }
            }

            /* Update fields */
            target.Description        = command.Description;
            target.UpdatedOnUtc       = command.UpdatedOn.ToUniversalTime();
            target.UpdatedByPrincipal = command.Principal.Identity.Name;

            _entities.Update(target);

            if (!command.NoCommit)
            {
                _unitOfWork.SaveChanges();
            }
        }
        public void Handle(UpdateEstablishmentName command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // load target
            var establishmentName = _entities.Get <EstablishmentName>()
                                    .EagerLoad(_entities, new Expression <Func <EstablishmentName, object> >[]
            {
                x => x.ForEstablishment.Names.Select(y => y.TranslationToLanguage), // parent & siblings
                x => x.TranslationToLanguage,                                       // language
            })
                                    .Single(x => x.RevisionId == command.Id);

            // only mutate when state is modified
            if (command.Text == establishmentName.Text &&
                command.IsFormerName == establishmentName.IsFormerName &&
                command.IsOfficialName == establishmentName.IsOfficialName &&
                (!string.IsNullOrWhiteSpace(command.LanguageCode)
                    ? establishmentName.TranslationToLanguage != null &&
                 command.LanguageCode.Equals(establishmentName.TranslationToLanguage.TwoLetterIsoCode)
                    : establishmentName.TranslationToLanguage == null))
            {
                return;
            }

            // update previous official name and owner when changing official name
            if (!establishmentName.IsOfficialName && command.IsOfficialName)
            {
                var establishment = establishmentName.ForEstablishment;
                var officialName  = establishment.Names.Single(x => x.IsOfficialName);
                var changeCommand = new UpdateEstablishmentName(command.Principal)
                {
                    Id             = officialName.RevisionId,
                    Text           = officialName.Text,
                    IsFormerName   = officialName.IsFormerName,
                    IsOfficialName = false,
                    LanguageCode   = (officialName.TranslationToLanguage != null)
                        ? officialName.TranslationToLanguage.TwoLetterIsoCode : null,
                    NoCommit = true,
                };
                Handle(changeCommand);
                establishment.OfficialName = command.Text;
                _entities.Update(establishment);
            }

            // get new language
            var language = _entities.Get <Language>()
                           .SingleOrDefault(x => x.TwoLetterIsoCode.Equals(command.LanguageCode, StringComparison.OrdinalIgnoreCase));

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    command.Id,
                    command.Text,
                    command.IsFormerName,
                    command.IsOfficialName,
                    command.LanguageCode,
                }),
                PreviousState = establishmentName.ToJsonAudit(),
            };

            // update scalars
            establishmentName.Text                  = command.Text;
            establishmentName.IsFormerName          = command.IsFormerName;
            establishmentName.IsOfficialName        = command.IsOfficialName;
            establishmentName.TranslationToLanguage = language;

            audit.NewState = establishmentName.ToJsonAudit();
            _entities.Create(audit);
            _entities.Update(establishmentName);

            if (command.NoCommit)
            {
                return;
            }
            _entities.SaveChanges();
            _eventTrigger.Raise(new EstablishmentChanged());
        }
示例#24
0
        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 void Handle(CreateOrUpdateInstitutionalAgreementCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // start with an agreement entity
            var entity = _entities.Get <InstitutionalAgreement>()
                         .EagerLoad(_entities, new Expression <Func <InstitutionalAgreement, object> >[]
            {
                a => a.Umbrella,
            })
                         .By(command.RevisionId);

            if (entity == null && command.RevisionId == 0)
            {
                entity = new InstitutionalAgreement();
            }
            if (entity == null)
            {
                throw new InvalidOperationException(string.Format(
                                                        "Agreement with id '{0}' does not exist", command.RevisionId));
            }

            // update scalars
            CopyScalars(command, entity);

            // scenario 1: no previous umbrella, no current umbrella.
            // scenario 2: no previous umbrella, with current umbrella.
            // scenario 3: with previous umbrella, same current umbrella.
            // scenario 4: with previous umbrella, different current umbrella.
            // scenario 5: with previous umbrella, no current umbrella.
            var previousUmbrella = entity.Umbrella;

            if (command.UmbrellaEntityId.HasValue &&
                (previousUmbrella == null || previousUmbrella.EntityId != command.UmbrellaEntityId.Value))
            {
                entity.Umbrella = _entities.Get <InstitutionalAgreement>().By(command.UmbrellaEntityId.Value);
                ++command.ChangeCount;
            }
            else if (previousUmbrella != null && !command.UmbrellaEntityId.HasValue)
            {
                entity.Umbrella = null;
                ++command.ChangeCount;
            }

            #region Participants

            if (command.RemoveParticipantEstablishmentEntityIds != null)
            {
                foreach (var removedParticipantEstablishmentId in command.RemoveParticipantEstablishmentEntityIds)
                {
                    var remove = new RemoveParticipantFromAgreementCommand(
                        command.Principal, removedParticipantEstablishmentId, entity.EntityId);
                    _participantRemover.Handle(remove);
                    if (remove.IsNewlyRemoved)
                    {
                        ++command.ChangeCount;
                    }
                }
            }

            if (command.AddParticipantEstablishmentEntityIds != null)
            {
                foreach (var addedParticipantEstablishmentId in command.AddParticipantEstablishmentEntityIds)
                {
                    var add = new AddParticipantToAgreementCommand(command.Principal, addedParticipantEstablishmentId, entity);
                    _participantAdder.Handle(add);
                    if (add.IsNewlyAdded)
                    {
                        ++command.ChangeCount;
                    }
                }
            }

            #endregion
            #region Contacts

            if (command.RemoveContactEntityIds != null)
            {
                foreach (var removedContactEntityId in command.RemoveContactEntityIds.Where(v => v != Guid.Empty))
                {
                    var remove = new RemoveContactFromAgreementCommand(
                        command.Principal, removedContactEntityId, entity.EntityId);
                    _contactRemover.Handle(remove);
                    if (remove.IsNewlyRemoved)
                    {
                        ++command.ChangeCount;
                    }
                }
            }

            if (command.AddContactCommands != null)
            {
                foreach (var add in command.AddContactCommands)
                {
                    add.Agreement = entity;
                    _contactAdder.Handle(add);
                    if (add.IsNewlyAdded)
                    {
                        ++command.ChangeCount;
                    }
                }
            }

            #endregion
            #region Files

            if (command.DetachFileEntityIds != null)
            {
                foreach (var removedFileEntityId in command.DetachFileEntityIds)
                {
                    var detach = new DetachFileFromAgreementCommand(
                        command.Principal, removedFileEntityId, entity.EntityId);
                    _fileDetacher.Handle(detach);
                    if (detach.IsNewlyDetached)
                    {
                        ++command.ChangeCount;
                    }
                }
            }

            if (command.AttachFileEntityIds != null)
            {
                foreach (var attachedFileIds in command.AttachFileEntityIds)
                {
                    var attach = new AttachFileToAgreementCommand(command.Principal, attachedFileIds, entity);
                    _fileAttacher.Handle(attach);
                    if (attach.IsNewlyAttached)
                    {
                        ++command.ChangeCount;
                    }
                }
            }

            #endregion

            command.EntityId = entity.EntityId;
            if (entity.RevisionId == 0 || command.ChangeCount > 0)
            {
                if (entity.RevisionId == 0)
                {
                    _entities.Create(entity);
                }
                else if (command.ChangeCount > 0)
                {
                    _entities.Update(entity);
                }
                DeriveNodes(entity, previousUmbrella);
                command.RevisionId = entity.RevisionId;
            }
        }
示例#26
0
        public void Handle(UpdateContact command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var entity = _entities.Get <AgreementContact>()
                         .EagerLoad(_entities, new Expression <Func <AgreementContact, object> >[]
            {
                x => x.Person.Emails,
                x => x.Person.User,
            })
                         .Single(x => x.Id == command.ContactId && x.AgreementId == command.AgreementId);

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    command.AgreementId,
                    command.ContactId,
                    command.Type,
                    command.PersonId,
                    command.Salutation,
                    command.FirstName,
                    command.MiddleName,
                    command.LastName,
                    command.Suffix,
                    command.EmailAddress,
                    command.JobTitle,
                }),
                PreviousState = entity.ToJsonAudit(),
            };

            // update fields
            if (!string.IsNullOrWhiteSpace(command.Type))
            {
                entity.Type = command.Type;
            }
            entity.Title = command.JobTitle;
            entity.UpdatedByPrincipal = command.Principal.Identity.Name;
            entity.UpdatedOnUtc       = DateTime.UtcNow;

            // change to different person
            if (command.PersonId.HasValue && command.PersonId.Value != entity.PersonId)
            {
                entity.PersonId = command.PersonId.Value;
            }

            // update existing person only if they have no user account
            else if (entity.Person.User == null)
            {
                _updatePerson.Handle(new UpdatePerson(command.Principal, entity.PersonId)
                {
                    NoCommit             = true,
                    Salutation           = command.Salutation,
                    FirstName            = command.FirstName,
                    MiddleName           = command.MiddleName,
                    LastName             = command.LastName,
                    Suffix               = command.Suffix,
                    IsDisplayNameDerived = true,
                });

                // creating contact uses default email, so updating does as well
                if (!string.IsNullOrWhiteSpace(command.EmailAddress))
                {
                    var defaultEmail = entity.Person.Emails.SingleOrDefault(x => x.IsDefault);
                    if (defaultEmail != null)
                    {
                        _updateEmail.Handle(new UpdateEmailAddress(defaultEmail)
                        {
                            NoCommit    = true,
                            Value       = command.EmailAddress,
                            IsConfirmed = defaultEmail.IsConfirmed,
                            IsDefault   = defaultEmail.IsDefault,
                            IsFromSaml  = defaultEmail.IsFromSaml,
                        });
                    }
                }
            }

            audit.NewState = entity.ToJsonAudit();
            _entities.Create(audit);
            _entities.Update(entity);
            _unitOfWork.SaveChanges();
        }
示例#27
0
        public void Handle(ReceiveSamlAuthnResponseCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }
            if (command.SamlResponse == null)
            {
                throw new InvalidOperationException("The SAML Response cannot be null.");
            }
            var samlResponse = command.SamlResponse;

            // get the trusted establishment for this saml 2 response
            var establishment = GetTrustedIssuingEstablishment(samlResponse);

            // verify the response's signature
            VerifySignature(samlResponse);

            // first try to find user by SAML person targeted id
            var user = GetUserByEduPersonTargetedId(samlResponse);

            // when saml user does not exist, search for person
            if (user == null)
            {
                var person = GetPerson(samlResponse);
                user = person.User ?? new User {
                    Person = person
                };
            }

            // delete local account if it exists
            if (!string.IsNullOrWhiteSpace(user.Name) && _passwords.Exists(user.Name))
            {
                _passwords.Destroy(user.Name);
            }

            // enforce invariants on user
            user.Name = samlResponse.EduPersonPrincipalName;
            user.EduPersonTargetedId = samlResponse.EduPersonTargetedId;
            user.IsRegistered        = true;

            // remove previous scoped affiliations and add new ones
            var oldScopedAffiliations = user.EduPersonScopedAffiliations.ToArray();
            var newScopedAffiliations = samlResponse.EduPersonScopedAffiliations ?? new string[] {};

            newScopedAffiliations = newScopedAffiliations.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
            foreach (var oldScopedAffiliation in oldScopedAffiliations)
            {
                if (!newScopedAffiliations.Contains(oldScopedAffiliation.Value))
                {
                    user.EduPersonScopedAffiliations.Remove(oldScopedAffiliation);
                }
            }
            foreach (var newScopedAffiliation in newScopedAffiliations)
            {
                if (oldScopedAffiliations.ByValue(newScopedAffiliation) == null)
                {
                    user.EduPersonScopedAffiliations.Add(
                        new EduPersonScopedAffiliation
                    {
                        Value  = newScopedAffiliation,
                        Number = user.EduPersonScopedAffiliations.NextNumber(),
                    });
                }
            }

            // log the subject name id
            var subjectNameId = samlResponse.SubjectNameIdentifier;

            if (!string.IsNullOrWhiteSpace(subjectNameId))
            {
                var subjectNameIdentifier = user.SubjectNameIdentifiers.ByValue(subjectNameId);
                if (subjectNameIdentifier == null)
                {
                    user.SubjectNameIdentifiers.Add(
                        new SubjectNameIdentifier
                    {
                        Value  = subjectNameId,
                        Number = user.SubjectNameIdentifiers.NextNumber(),
                    });
                }
                else
                {
                    subjectNameIdentifier.UpdatedOnUtc = DateTime.UtcNow;
                }
            }


            // enforce invariants on person
            if (!user.Person.IsAffiliatedWith(establishment))
            {
                user.Person.AffiliateWith(establishment);
            }

            // remove previous saml mails, add new ones, and update existing ones
            var oldSamlMails = user.Person.Emails.FromSaml().ToArray();
            var newSamlMails = samlResponse.Mails ?? new string[] {};

            newSamlMails = newSamlMails.Where(s => !string.IsNullOrWhiteSpace(s)).ToArray();
            foreach (var oldSamlMail in oldSamlMails)
            {
                if (!newSamlMails.Contains(oldSamlMail.Value))
                {
                    user.Person.Emails.Remove(oldSamlMail);
                }
            }
            foreach (var newSamlMail in newSamlMails)
            {
                if (user.Person.GetEmail(newSamlMail) == null)
                {
                    user.Person.AddEmail(newSamlMail);
                }
            }
            foreach (var emailAddress in user.Person.Emails)
            {
                if (newSamlMails.Contains(emailAddress.Value))
                {
                    emailAddress.IsFromSaml  = true;
                    emailAddress.IsConfirmed = true;
                }
            }

            // make sure person has at least 1 confirmed email address
            var defaultEmail = user.Person.DefaultEmail;

            if (defaultEmail == null || !defaultEmail.IsConfirmed)
            {
                if (defaultEmail != null)
                {
                    defaultEmail.IsDefault = false;
                }
                defaultEmail             = user.Person.AddEmail(samlResponse.EduPersonPrincipalName);
                defaultEmail.IsDefault   = true;
                defaultEmail.IsConfirmed = true;
            }

            // update db
            if (user.RevisionId == 0)
            {
                _entities.Create(user);
            }
            else
            {
                _entities.Update(user);
            }
            _unitOfWork.SaveChanges();

            // sign on user
            _userSigner.SignOn(user.Name);
        }
示例#28
0
        public void Handle(UpdateMyNameCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // get the person for the principal
            var user = _entities.Get <User>()
                       .EagerLoad(_entities, new Expression <Func <User, object> >[]
            {
                u => u.Person,
            })
                       .ByName(command.Principal.Identity.Name);

            // update fields
            if (user.Person.IsDisplayNameDerived != command.IsDisplayNameDerived)
            {
                command.ChangeCount++;
            }
            user.Person.IsDisplayNameDerived = command.IsDisplayNameDerived;

            if (user.Person.DisplayName != command.DisplayName)
            {
                command.ChangeCount++;
            }
            user.Person.DisplayName = command.IsDisplayNameDerived
                ? new GenerateDisplayNameHandler().Handle(
                new GenerateDisplayNameQuery
            {
                Salutation = command.Salutation,
                FirstName  = command.FirstName,
                MiddleName = command.MiddleName,
                LastName   = command.LastName,
                Suffix     = command.Suffix,
            })
                : command.DisplayName;

            if (user.Person.Salutation != command.Salutation)
            {
                command.ChangeCount++;
            }
            user.Person.Salutation = command.Salutation;

            if (user.Person.FirstName != command.FirstName)
            {
                command.ChangeCount++;
            }
            user.Person.FirstName = command.FirstName;

            if (user.Person.MiddleName != command.MiddleName)
            {
                command.ChangeCount++;
            }
            user.Person.MiddleName = command.MiddleName;

            if (user.Person.LastName != command.LastName)
            {
                command.ChangeCount++;
            }
            user.Person.LastName = command.LastName;

            if (user.Person.Suffix != command.Suffix)
            {
                command.ChangeCount++;
            }
            user.Person.Suffix = command.Suffix;

            // store
            if (command.ChangeCount > 0)
            {
                _entities.Update(user.Person);
            }
        }
示例#29
0
        public void Handle(CreateEstablishmentUrl command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // load owner
            var establishment = command.Owner ?? _entities.Get <Establishment>()
                                .EagerLoad(_entities, new Expression <Func <Establishment, object> >[]
            {
                x => x.Urls,
            })
                                .Single(x => x.RevisionId == command.OwnerId.Value)
            ;

            // update previous official URL and owner when changing official URL
            if (command.IsOfficialUrl)
            {
                var officialUrl = establishment.Urls.SingleOrDefault(x => x.IsOfficialUrl);
                if (officialUrl != null)
                {
                    var changeCommand = new UpdateEstablishmentUrl(command.Principal)
                    {
                        Id            = officialUrl.RevisionId,
                        Value         = officialUrl.Value,
                        IsFormerUrl   = officialUrl.IsFormerUrl,
                        IsOfficialUrl = false,
                        NoCommit      = true,
                    };
                    _updateHandler.Handle(changeCommand);
                }
                establishment.WebsiteUrl = command.Value;
            }

            // create new establishment URL
            var establishmentUrl = new EstablishmentUrl
            {
                Value         = command.Value,
                IsOfficialUrl = command.IsOfficialUrl,
                IsFormerUrl   = command.IsFormerUrl,
            };

            establishment.Urls.Add(establishmentUrl);
            establishmentUrl.ForEstablishment = establishment;

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = command.Principal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    OwnerId = command.Owner != null ? command.Owner.RevisionId : command.OwnerId,
                    command.Value,
                    command.IsFormerUrl,
                    command.IsOfficialUrl,
                }),
                NewState = establishmentUrl.ToJsonAudit(),
            };

            _entities.Create(audit);
            if (establishment.RevisionId != default(int))
            {
                _entities.Update(establishment);
            }
            command.CreatedEntity = establishmentUrl;
            if (command.NoCommit)
            {
                return;
            }

            _entities.SaveChanges();
            command.Id = establishmentUrl.RevisionId;
            _eventTrigger.Raise(new EstablishmentChanged());
        }
        public void Handle(UpdateEmailAddress command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // load entity
            var entity = command.EmailAddress ?? _entities.Get <EmailAddress>()
                         .EagerLoad(_entities, new Expression <Func <EmailAddress, object> >[]
            {
                x => x.Person,
            })
                         .Single(x => x.PersonId == command.PersonId && x.Number == command.Number);

            // log audit
            var audit = new CommandEvent
            {
                RaisedBy = Thread.CurrentPrincipal.Identity.Name,
                Name     = command.GetType().FullName,
                Value    = JsonConvert.SerializeObject(new
                {
                    command.PersonId,
                    command.Number,
                    command.Value,
                    command.IsConfirmed,
                    command.IsDefault,
                    command.IsFromSaml,
                }),
                PreviousState = entity.ToJsonAudit(),
            };

            // clear previous default email
            if (command.IsDefault)
            {
                foreach (var email in entity.Person.Emails.Where(x => x.IsDefault && x.Number != command.Number))
                {
                    Handle(new UpdateEmailAddress(email)
                    {
                        NoCommit    = true,
                        IsDefault   = false,
                        IsConfirmed = email.IsConfirmed,
                        IsFromSaml  = email.IsFromSaml,
                        Value       = email.Value,
                    });
                }
            }

            // update scalars
            if (!string.IsNullOrWhiteSpace(command.Value))
            {
                entity.Value = command.Value;
            }
            entity.IsConfirmed = command.IsConfirmed;
            entity.IsDefault   = command.IsDefault;
            entity.IsFromSaml  = command.IsFromSaml;
            _entities.Update(entity);

            audit.NewState = entity.ToJsonAudit();
            _entities.Create(audit);

            // store
            if (!command.NoCommit)
            {
                _unitOfWork.SaveChanges();
            }
        }