Ejemplo n.º 1
0
        public GeoPlanetPlace Handle(SingleGeoPlanetPlaceByGeoNameId query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            // try manual mappings first
            if (KnownWoeIds.ToGeoNameIds.ContainsValue(query.GeoNameId))
            {
                return(_queryProcessor.Execute(new SingleGeoPlanetPlace(
                                                   KnownWoeIds.ToGeoNameIds.Single(d => d.Value == query.GeoNameId).Key)));
            }

            // try concordance
            var concordance = _geoPlanet.Concordance(
                ConcordanceNamespace.GeoNames, query.GeoNameId);

            if (concordance != null && concordance.GeoNameId != 0 && concordance.WoeId != 0)
            {
                return(_queryProcessor.Execute(
                           new SingleGeoPlanetPlace(concordance.WoeId)));
            }

            return(null);
        }
Ejemplo n.º 2
0
        protected override bool IsValid(PropertyValidatorContext context)
        {
            var ticket = (string)context.PropertyValue;
            var token  = _token((T)context.Instance);

            // there should be another validator which detects emptiness of ticket
            if (string.IsNullOrWhiteSpace(ticket))
            {
                return(true);
            }

            var verification = _queries.Execute(new EmailVerificationBy(ticket)).Result;

            // there should be another validator which detects the presence of the entity by ticket
            if (verification == null)
            {
                return(true);
            }

            // token is not valid unless it matches the ticket's token
            var query   = new EmailVerificationTokenIsValid(token, ticket, verification.Purpose);
            var isValid = _queries.Execute(query).Result&& verification.Token == token &&
                          !string.IsNullOrWhiteSpace(token);

            if (isValid)
            {
                return(true);
            }

            context.MessageFormatter.AppendArgument("PropertyName", context.PropertyDescription.ToLower());
            return(false);
        }
        public void Handle(SendConfirmEmailMessageCommand command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // get the person
            var person = _entities.Get <Person>()
                         .EagerLoad(_entities, new Expression <Func <Person, object> >[]
            {
                p => p.Emails,
            })
                         .ByEmail(command.EmailAddress);

            // get the email
            var email = person.GetEmail(command.EmailAddress);

            // create the confirmation
            var secretCode = GenerateRandomSecretHandler.Handle(
                new GenerateRandomSecretQuery(12));
            var confirmation = new EmailConfirmation(command.Intent)
            {
                EmailAddress = email,
                SecretCode   = secretCode,
            };

            command.ConfirmationToken = confirmation.Token;
            _entities.Create(confirmation);

            // get the email template
            var template = _queryProcessor.Execute(
                new GetEmailTemplateByNameQuery
            {
                Name = command.TemplateName.AsSentenceFragment(),
            }
                );

            // create the message
            var message = _queryProcessor.Execute(
                new ComposeEmailMessageQuery(template, email)
            {
                Formatters = _queryProcessor.Execute(
                    new GetConfirmEmailFormattersQuery(confirmation, command.SendFromUrl)
                    )
            }
                );

            _entities.Create(message);

            // send the message
            _sendHandler.Handle(
                new SendEmailMessageCommand
            {
                PersonId      = message.ToPerson.RevisionId,
                MessageNumber = message.Number,
            }
                );
        }
Ejemplo n.º 4
0
        public async Task Handle(SignOn command)
        {
            if (command.Principal.Identity.IsAuthenticated)
            {
                command.SignedOn = await _queries.Execute(new UserBy(command.Principal));

                return;
            }

            // try to find user by external login credentials
            var externalLogin = await _queries.Execute(new PrincipalRemoteMembershipTicket(command.Principal));

            if (externalLogin == null)
            {
                return;
            }

            var user = await _queries.Execute(new UserBy(externalLogin.Login));

            if (user != null)
            {
                await _authenticator.SignOn(user, command.IsPersistent);

                command.SignedOn = user;
                return;
            }

            // if they don't exist, check with email claim
            var emailClaim = await _queries.Execute(new ExternalCookieClaim(ClaimTypes.Email));

            if (emailClaim != null)
            {
                var emailAddress = await _queries.Execute(new EmailAddressBy(emailClaim)
                {
                    IsVerified = true,
                    EagerLoad  = new Expression <Func <EmailAddress, object> >[]
                    {
                        x => x.User,
                    },
                });

                if (emailAddress != null)
                {
                    // need to add the external login credentials
                    user = emailAddress.User;
                    _entities.Update(user); // make sure it is attached to the context
                    await _commands.Execute(new CreateRemoteMembership
                    {
                        Principal = command.Principal,
                        User      = user,
                    });

                    await _authenticator.SignOn(user, command.IsPersistent);

                    command.SignedOn = user;
                }
            }
        }
        public void Seed()
        {
            if (_entities.Get <Place>().Any())
            {
                return;
            }

            var earth = _queryProcessor.Execute(new PlaceByWoeId(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 PlaceByWoeId(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 PlaceByWoeId(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 PlaceByWoeId(geoPlanetState.WoeId));
            //        Debug.Assert(state != null);
            //    }
            //}
        }
Ejemplo n.º 6
0
        private Language ById(int id)
        {
            var entity = _queries.Execute(new LanguageById(id)
            {
                EagerLoad = EagerLoad,
            });

            return(entity);
        }
Ejemplo n.º 7
0
        public async Task Handle(CreateEmailVerification command)
        {
            // find or create the email address
            var emailAddress = await _entities.Get <EmailAddress>().ByValueAsync(command.EmailAddress)
                               ?? new EmailAddress
            {
                Value       = command.EmailAddress.ToLower(), // TODO: allow users to change capitalization of email?
                HashedValue = await _queries.Execute(new HashedEmailValueBy(command.EmailAddress)),
            };

            // create random secret and ticket
            // note that changing the length of the secret requires updating the
            // email messages sent to the address, since those mention secret length
            var secret = _queries.Execute(new RandomSecret(10, 12));
            var ticket = _queries.Execute(new RandomSecret(20, 25));

            // make sure ticket is unique
            while (_entities.Query <EmailVerification>().ByTicket(ticket) != null)
            {
                ticket = _queries.Execute(new RandomSecret(20, 25));
            }

            // serialize a new user token to a string
            var token = await _userManager.UserTokenProvider.GenerateAsync(command.Purpose.ToString(), _userManager,
                                                                           new UserTicket
            {
                UserName = ticket,
            });

            // create the verification
            var verification = new EmailVerification
            {
                EmailAddress = emailAddress,
                Purpose      = command.Purpose,
                Secret       = secret,
                Ticket       = ticket,
                Token        = token,

                // change this, and you have to change the content of the email messages to reflect new expiration
                ExpiresOnUtc = DateTime.UtcNow.AddMinutes(30),
            };

            _entities.Create(verification);

            if (command.Commit)
            {
                await _entities.SaveChangesAsync();
            }

            command.CreatedEntity = verification;
        }
Ejemplo n.º 8
0
        public Place Handle(PlaceByGeoNameId query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            // first look in the db
            var place = _entities.Get <Place>()
                        .EagerLoad(_entities, query.EagerLoad)
                        .ByGeoNameId(query.GeoNameId)
            ;

            if (place != null)
            {
                return(place);
            }

            // load toponym from storage
            var toponym = _queryProcessor.Execute(
                new SingleGeoNamesToponym(query.GeoNameId)
            {
                NoCommit = true,
            });

            // convert toponym to place
            place = toponym.ToPlace();

            // match place hierarchy to toponym hierarchy
            if (toponym.Parent != null)
            {
                place.Parent = Handle(
                    new PlaceByGeoNameId(toponym.Parent.GeoNameId));
            }

            // try to match to geoplanet
            if (place.GeoPlanetPlace == null && place.GeoNamesToponym != null)
            {
                place.GeoPlanetPlace = _queryProcessor.Execute(
                    new SingleGeoPlanetPlaceByGeoNameId(place.GeoNamesToponym.GeoNameId));
            }

            // map ancestors
            _updateHierarchy.Handle(new UpdatePlaceHierarchy(place));

            // add to db & save
            _entities.Create(place);
            _unitOfWork.SaveChanges();

            return(place);
        }
        //[Authorize(Users = "*****@*****.**")]
        public virtual ActionResult Browse()
        {
            //var entities = _establishments.FindMany(new EstablishmentQuery().OrderBy(e => e.OfficialName));
            var entities = _queryProcessor.Execute(new FindAllEstablishmentsQuery
            {
                OrderBy = new Dictionary <Expression <Func <Establishment, object> >, OrderByDirection>
                {
                    { e => e.OfficialName, OrderByDirection.Ascending },
                },
            });
            var models = Mapper.Map <IEnumerable <EstablishmentSearchResult> >(entities);

            return(View(models));
        }
Ejemplo n.º 10
0
        protected override bool IsValid(PropertyValidatorContext context)
        {
            var userName = (string)context.PropertyValue;

            if (string.IsNullOrWhiteSpace(userName))
            {
                return(true);
            }

            if (!EmailAddress.ValueRegex.IsMatch(userName))
            {
                return(true);
            }

            if (_ticket != null)
            {
                var ticket       = _ticket((T)context.Instance);
                var verification = _queries.Execute(new EmailVerificationBy(ticket)
                {
                    EagerLoad = new Expression <Func <EmailVerification, object> >[]
                    {
                        x => x.EmailAddress,
                    },
                }).Result;
                if (verification == null)
                {
                    return(true);
                }
                if (verification.EmailAddress.Value.Equals(userName, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }
            }
            else
            {
                var userId         = _userId((T)context.Instance);
                var emailAddresses = _queries.Execute(new EmailAddressesBy(userId)
                {
                    IsVerified = true,
                }).Result;
                var matchingAddress = emailAddresses.ByValueAsync(userName).Result;
                if (matchingAddress != null)
                {
                    return(true);
                }
            }

            context.MessageFormatter.AppendArgument("PropertyName", User.Constraints.NameLabel.ToLower());
            return(false);
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> GetCustomers(CancellationToken cancellationToken)
        {
            var customers = await _queries.Execute(new CustomersBy(), cancellationToken).ConfigureAwait(false);

            var contract = customers.Select(customer => new CustomerDto
            {
                Id           = customer.Id,
                FirstName    = customer.FirstName,
                LastName     = customer.LastName,
                EmailAddress = customer.EmailAddress
            });

            return(Ok(contract));
        }
Ejemplo n.º 12
0
        public void Perform(SeedAtlanticOcean job)
        {
            var reportBuilder = new WorkReportBuilder("Seed Atlantic Ocean");

            try
            {
                var atlantics = _queryProcessor.Execute(new PlacesWithName
                {
                    MaxResults        = 5,
                    Term              = AtlanticOceanText,
                    TermMatchStrategy = StringMatchStrategy.Equals,
                });
                if (atlantics.Any())
                {
                    reportBuilder.Report("At least {0} Place(s) named '{1}' already exist(s).", atlantics.Count(), AtlanticOceanText);
                }
                else
                {
                    reportBuilder.Report("There are no Places named '{0}'.", AtlanticOceanText);
                    reportBuilder.Report("Seeding '{0}'.", AtlanticOceanText);

                    var geoPlanetPlaces   = _geoPlanet.Places(AtlanticOceanText);
                    var geoPlanetToponyms = _geoNames.Search(new SearchOptions(SearchType.NameEquals, AtlanticOceanText));

                    var geoNamesToponym = geoPlanetToponyms.FirstOrDefault(x => x.FeatureClassCode == "H");
                    var geoPlanetPlace  = geoPlanetPlaces.FirstOrDefault(x => x.Type.Code == 37 || x.Type.Code == 38);

                    if (geoPlanetPlace != null && geoNamesToponym != null)
                    {
                        _queryProcessor.Execute(new PlaceByWoeId(geoPlanetPlace.WoeId, geoNamesToponym.GeoNameId));
                    }

                    reportBuilder.Report("There is/are now {0} Place(s) named '{1}'.", atlantics.Count(), AtlanticOceanText);
                }
            }
            catch (Exception ex)
            {
                reportBuilder.Report("");
                reportBuilder.Report("JOB FAILED!");
                reportBuilder.Report(ex.GetType().Name);
                reportBuilder.Report(ex.Message);
                reportBuilder.Report(ex.StackTrace);
                _exceptionLogger.Log(ex);
            }
            finally
            {
                reportBuilder.Send(_mailSender);
            }
        }
Ejemplo n.º 13
0
        public static void ClientCookie(this HttpResponseBase response, string userId, IProcessQueries queries)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            if (queries == null)
            {
                throw new ArgumentNullException("queries");
            }

            var cookie = new HttpCookie(CookieName, "");

            int userIdInt;

            if (int.TryParse(userId, out userIdInt))
            {
                var    data        = queries.Execute(new ClientCookieBy(userIdInt)).Result;
                var    json        = JsonConvert.SerializeObject(data);
                byte[] jsonBytes   = MachineKey.Protect(Encoding.UTF8.GetBytes(json), "Cookie");
                string cookieValue = HttpServerUtility.UrlTokenEncode(jsonBytes);
                cookie.Values[ClientCookieKey] = cookieValue;
                //cookie.Expires = DateTime.UtcNow.AddDays(60);
            }
            else
            {
                cookie.Expires = DateTime.UtcNow.AddDays(-2);
            }

            response.SetCookie(cookie);
        }
Ejemplo n.º 14
0
        public AgreementVisibility Handle(MyAgreementVisibility query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            var visibility = AgreementVisibility.Public;

            if (!query.Principal.Identity.IsAuthenticated)
            {
                return(visibility);
            }

            // when i own the agreement owner, i have protected access
            var myOwnedTenantIds  = _queryProcessor.Execute(new MyOwnedTenantIds(query.Principal));
            var agreementOwnerIds = _entities.Query <Agreement>()
                                    .Where(x => x.Id == query.AgreementId)
                                    .SelectMany(x => x.Participants.Where(y => y.IsOwner).Select(y => y.EstablishmentId));

            if (agreementOwnerIds.All(x => myOwnedTenantIds.Contains(x)))
            {
                visibility = AgreementVisibility.Protected;
            }

            if (visibility == AgreementVisibility.Protected && query.Principal.IsInAnyRole(RoleName.AgreementManagers))
            {
                visibility = AgreementVisibility.Private;
            }

            return(visibility);
        }
Ejemplo n.º 15
0
        protected override bool IsValid(PropertyValidatorContext context)
        {
            var principal = (IPrincipal)context.PropertyValue;
            var userName  = principal.Identity.Name;
            var activity  = _activity != null?_activity((T)context.Instance) : null;

            if (activity == null)
            {
                var activityId = _activityId((T)context.Instance);
                activity = _queryProcessor.Execute(new ActivityById(activityId)
                {
                    EagerLoad = new Expression <Func <Activity, object> >[]
                    {
                        x => x.Person.User,
                    },
                });
            }

            // return null when activity doesn't exist to prevent exceptions on deletion
            // any other validator must check for the existence of activity first
            if (activity == null || (activity.Person.User != null &&
                                     activity.Person.User.Name.Equals(userName, StringComparison.OrdinalIgnoreCase)))
            {
                return(true);
            }

            context.MessageFormatter.AppendArgument("UserName", userName);
            context.MessageFormatter.AppendArgument("CommandName", typeof(T).Name);
            context.MessageFormatter.AppendArgument("ActivityId", activity.RevisionId != 0
                ? activity.RevisionId.ToString(CultureInfo.InvariantCulture)
                : activity.EntityId.ToString());
            return(false);
        }
Ejemplo n.º 16
0
        public Agreement Handle(AgreementById query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            var ownedTenantIds = _queryProcessor.Execute(new MyOwnedTenantIds(query.Principal));

            var queryable = _entities.Query <Agreement>().EagerLoad(_entities, query.EagerLoad);

            if (query.MustBeOwnedByPrincipal.HasValue && query.MustBeOwnedByPrincipal.Value)
            {
                queryable = queryable.OwnedBy(query.Principal, ownedTenantIds);
            }
            else
            {
                queryable = queryable.VisibleTo(query.Principal, ownedTenantIds);
            }

            var agreement = queryable.ById(query.Id);

            if (agreement == null)
            {
                return(null);
            }

            agreement.ApplySecurity(query.Principal, _queryProcessor);

            return(agreement);
        }
Ejemplo n.º 17
0
        public void Handle(PurgeInstitutionalAgreement command)
        {
            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            // find agreement
            var agreement = _queryProcessor.Execute(
                new GetMyInstitutionalAgreementByGuidQuery(command.Principal, command.AgreementId));

            if (agreement == null)
            {
                return;
            }

            agreement = _entities.Get <InstitutionalAgreement>().Single(x => x.EntityId == command.AgreementId);

            if (agreement.Files != null && agreement.Files.Any())
            {
                foreach (var file in agreement.Files.Where(x => !string.IsNullOrWhiteSpace(x.Path)))
                {
                    _binaryData.Delete(file.Path);
                }
            }

            _entities.Purge(agreement);
            _unitOfWork.SaveChanges();
        }
        public EmployeeModuleSettings Handle(EmployeeSettingsByPerson query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            int?establishmentId;

            if (!query.PersonId.HasValue)
            {
                // get settings from user's default affiliation
                establishmentId = _entities.Query <Affiliation>()
                                  .Where(x => x.IsDefault && x.Person.User != null && x.Person.User.Name.Equals(query.Principal.Identity.Name, StringComparison.OrdinalIgnoreCase))
                                  .Select(x => (int?)x.EstablishmentId).SingleOrDefault();
            }
            else
            {
                // otherwise, get settings for the person's default affiliation
                establishmentId = _entities.Query <Affiliation>()
                                  .Where(x => x.IsDefault && x.PersonId == query.PersonId.Value)
                                  .Select(x => (int?)x.EstablishmentId).SingleOrDefault();
            }

            return(establishmentId.HasValue
                ? _queryProcessor.Execute(new EmployeeSettingsByEstablishment(establishmentId.Value))
                : null);
        }
Ejemplo n.º 19
0
        public PagedQueryResult <ActivityValues> Handle(ActivityValuesPageBy query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            var queryable = _queryProcessor.Execute(new ActivityValuesBy
            {
                PersonId            = query.PersonId,
                Principal           = query.Principal,
                PlaceIds            = query.PlaceIds,
                CountryCode         = query.CountryCode,
                ActivityTypeIds     = query.ActivityTypeIds,
                Since               = query.Since,
                Until               = query.Until,
                IncludeUndated      = query.IncludeUndated,
                EstablishmentDomain = query.EstablishmentDomain,
                EstablishmentId     = query.EstablishmentId,
                Keyword             = query.Keyword,
                EagerLoad           = query.EagerLoad,
                OrderBy             = query.OrderBy,
            });

            if (query.OrderBy == null || !query.OrderBy.Any())
            {
                queryable = queryable.OrderBy(x => x.RevisionId);
            }
            var result = new PagedQueryResult <ActivityValues>(queryable, query.PageSize, query.PageNumber);

            return(result);
        }
Ejemplo n.º 20
0
        protected override bool IsValid(PropertyValidatorContext context)
        {
            if (!(context.PropertyValue is IPrincipal))
            {
                throw new NotSupportedException(string.Format(
                                                    "The {0} PropertyValidator can only operate on IPrincipal properties", GetType().Name));
            }

            var principal = (IPrincipal)context.PropertyValue;
            var degreeId  = _degreeId((T)context.Instance);

            context.MessageFormatter.AppendArgument("UserName", principal.Identity.Name);
            context.MessageFormatter.AppendArgument("DegreeId", degreeId);


            var eagerLoad = new Expression <Func <Degree, object> >[] { x => x.Person.User, };
            var degree    = _entities != null
                ? _entities.Query <Degree>()
                            .EagerLoad(_entities, eagerLoad)
                            .SingleOrDefault(x => x.RevisionId == degreeId)

                : _queryProcessor.Execute(new DegreeById(degreeId)
            {
                EagerLoad = eagerLoad
            });

            return(degree != null && degree.Person.User != null &&
                   degree.Person.User.Name.Equals(principal.Identity.Name, StringComparison.OrdinalIgnoreCase));
        }
Ejemplo n.º 21
0
        public virtual async Task <ActionResult> Index(string ticket, string returnUrl)
        {
            // todo: make sure we still have a remote login

            var verification = await _queries.Execute(new EmailVerificationBy(ticket)
            {
                EagerLoad = new Expression <Func <EmailVerification, object> >[]
                {
                    x => x.EmailAddress,
                }
            });

            if (verification == null)
            {
                return(HttpNotFound());
            }

            // todo: verification token must not be redeemed, expired, or for different purpose

            ViewBag.ReturnUrl = returnUrl;
            ViewBag.ActionUrl = Url.Action(MVC.SignOnVerifySecret.Post());
            ViewBag.Ticket    = ticket;
            ViewBag.Purpose   = EmailVerificationPurpose.CreateRemoteUser;
            if (Session.VerifyEmailTickets().Contains(ticket))
            {
                ViewBag.EmailAddress = verification.EmailAddress.Value;
            }
            return(View(MVC.Security.Views.SignOn.VerifySecret));
        }
Ejemplo n.º 22
0
        public async Task Handle(CreateLocalMembership command)
        {
            // does user already exist?
            var hasUserId = command.Principal != null && command.Principal.Identity.HasAppUserId();
            var user      = hasUserId ? await _entities.GetAsync <User>(command.Principal.Identity.GetUserId <int>()) : null;

            if (!hasUserId)
            {
                var createUser = new CreateUser {
                    Name = command.UserName
                };
                await _commands.Execute(createUser);

                user = createUser.CreatedEntity;

                // verify & associate email address
                await _commands.Execute(new RedeemEmailVerification(user)
                {
                    Commit = false,
                    Token  = command.Token,
                    Ticket = command.Ticket,
                });
            }

            user.LocalMembership = new LocalMembership
            {
                User         = user,
                PasswordHash = await _queries.Execute(new HashedPassword(command.Password)),
            };
            user.SecurityStamp = Guid.NewGuid().ToString();
            await _entities.SaveChangesAsync();

            command.CreatedEntity = user.LocalMembership;
        }
Ejemplo n.º 23
0
        protected override bool IsValid(PropertyValidatorContext context)
        {
            if (!(context.PropertyValue is int) && !(context.PropertyValue is int?))
            {
                throw new NotSupportedException(string.Format(
                                                    "The {0} PropertyValidator can only operate on integer properties", GetType().Name));
            }

            var agreementId = (int)context.PropertyValue;
            var principal   = _principal((T)context.Instance);

            context.MessageFormatter.AppendArgument("AgreementId", agreementId);

            var entity = _queryProcessor.Execute(new AgreementById(principal, agreementId)
            {
                EagerLoad = new Expression <Func <Agreement, object> >[]
                {
                    x => x.Offspring,
                }
            });

            if (entity != null && entity.Offspring.Any())
            {
                var offspringAgreementIds = entity.Offspring.Select(x => x.OffspringId)
                                            .Select(x => x.ToString(CultureInfo.InvariantCulture));
                context.MessageFormatter.AppendArgument("OffspringIds", offspringAgreementIds.Implode(", "));
                return(false);
            }

            return(true);
        }
        public EmployeeActivityCountsView Handle(EmployeeActivityCountsViewByEstablishment query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            var view = query.EstablishmentId.HasValue
                ? _projector.Get(query.EstablishmentId.Value)
                : _projector.Get(query.Domain);

            if (view != null)
            {
                return(view);
            }

            var emptyView = new EmployeeActivityCountsView();

            if (query.EstablishmentId.HasValue)
            {
                emptyView.EstablishmentId = query.EstablishmentId.Value;
            }
            else
            {
                var establishment = _queryProcessor.Execute(new EstablishmentByDomain(query.Domain));
                if (establishment != null)
                {
                    emptyView.EstablishmentId = establishment.RevisionId;
                }
            }
            return(emptyView);
        }
Ejemplo n.º 25
0
        protected override bool IsValid(PropertyValidatorContext context)
        {
            var userId = (int)context.PropertyValue;
            var entity = _queries.Execute(new UserBy(userId)).Result;

            return(entity != null);
        }
Ejemplo n.º 26
0
        public EmployeeActivityCountsView Get(string domain)
        {
            var establishment = _queries.Execute(new EstablishmentByDomain(domain));

            return(establishment != null
                ? Get(establishment.RevisionId) : null);
        }
Ejemplo n.º 27
0
        public PagedQueryResult <Role> Handle(RolesByKeyword query)
        {
            if (query == null)
            {
                throw new ArgumentNullException("query");
            }

            var internalQuery = new RolesUnfiltered(query.Principal)
            {
                EagerLoad = query.EagerLoad,
                OrderBy   = query.OrderBy,
            };

            var internalQueryable = _queryProcessor.Execute(internalQuery);

            if (!string.IsNullOrWhiteSpace(query.Keyword))
            {
                var loweredKeyword = query.Keyword.ToLower();
                internalQueryable = internalQueryable.Where(x =>
                                                            x.Name.ToLower().Contains(loweredKeyword) ||
                                                            x.Description.ToLower().Contains(loweredKeyword)
                                                            );
            }


            var pagedResults = new PagedQueryResult <Role>(internalQueryable, query.PageSize, query.PageNumber);

            return(pagedResults);
        }
Ejemplo n.º 28
0
        protected override bool IsValid(PropertyValidatorContext context)
        {
            var emailAddressId = (int)context.PropertyValue;
            var entity         = _queries.Execute(new EmailAddressBy(emailAddressId)).Result;

            return(entity != null);
        }
Ejemplo n.º 29
0
        public async Task <Claim> Handle(ExternalCookieClaim query)
        {
            var claims = await _queries.Execute(new ExternalCookieClaims(query.AuthenticationType))
                         .ConfigureAwait(false);

            return(claims.FirstOrDefault(x => x.Type == query.ClaimType));
        }
Ejemplo n.º 30
0
        public virtual async Task <ActionResult> Index(string ticket, string returnUrl)
        {
            var confirmation = await _queries.Execute(new EmailVerificationBy(ticket)
            {
                EagerLoad = new Expression <Func <EmailVerification, object> >[]
                {
                    x => x.EmailAddress,
                }
            });

            if (confirmation == null)
            {
                return(HttpNotFound());
            }

            // todo: confirmation token must not be redeemed, expired, or for different purpose

            ViewBag.ReturnUrl = returnUrl;
            ViewBag.ActionUrl = Url.Action(MVC.ResetPasswordVerifySecret.Post());
            ViewBag.Ticket    = ticket;
            ViewBag.Purpose   = EmailVerificationPurpose.ForgotPassword;
            if (Session.VerifyEmailTickets().Contains(ticket))
            {
                ViewBag.EmailAddress = confirmation.EmailAddress.Value;
            }
            return(View(MVC.Security.Views.ResetPassword.VerifySecret));
        }
Ejemplo n.º 31
0
        internal static IQueryable<Agreement> OwnedBy(this IQueryable<Agreement> agreements, IPrincipal principal, IProcessQueries queryProcessor)
        {
            if (agreements == null) return null;
            if (principal == null) throw new ArgumentNullException("principal");
            if (queryProcessor == null) throw new ArgumentNullException("queryProcessor");

            var ownedTenantIds = queryProcessor.Execute(new MyOwnedTenantIds(principal));
            return agreements.OwnedBy(principal, ownedTenantIds);
        }
Ejemplo n.º 32
0
        internal static void ApplySecurity(this Agreement agreement, IPrincipal principal, IProcessQueries queryProcessor)
        {
            if (agreement == null) return;
            if (principal == null) throw new ArgumentNullException("principal");
            if (queryProcessor == null) throw new ArgumentNullException("queryProcessor");

            var ownedTenantIds = queryProcessor.Execute(new MyOwnedTenantIds(principal));
            agreement.ApplySecurity(principal, ownedTenantIds);
        }
Ejemplo n.º 33
0
        public static bool NameMatchesEntity(string name, IProcessQueries queryProcessor,
            IEnumerable<Expression<Func<User, object>>> eagerLoad, out User entity)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                entity = null;
                return false;
            }

            entity = queryProcessor.Execute(
                new GetUserByNameQuery
                {
                    Name = name,
                    EagerLoad = eagerLoad,
                }
            );

            // return true (valid) if there is an entity
            return entity != null;
        }
Ejemplo n.º 34
0
        public static void ClientCookie(this HttpResponseBase response, string userId, IProcessQueries queries)
        {
            if (response == null) throw new ArgumentNullException("response");
            if (queries == null) throw new ArgumentNullException("queries");

            var cookie = new HttpCookie(CookieName, "");

            int userIdInt;
            if (int.TryParse(userId, out userIdInt))
            {
                var data = queries.Execute(new ClientCookieBy(userIdInt)).Result;
                var json = JsonConvert.SerializeObject(data);
                byte[] jsonBytes = MachineKey.Protect(Encoding.UTF8.GetBytes(json), "Cookie");
                string cookieValue = HttpServerUtility.UrlTokenEncode(jsonBytes);
                cookie.Values[ClientCookieKey] = cookieValue;
                //cookie.Expires = DateTime.UtcNow.AddDays(60);
            }
            else
            {
                cookie.Expires = DateTime.UtcNow.AddDays(-2);
            }

            response.SetCookie(cookie);
        }
        private void Build(int retryCount)
        {
            _queryProcessor = ServiceProviderLocator.Current.GetService<IProcessQueries>();
            _updateEstablishment = ServiceProviderLocator.Current.GetService<IHandleCommands<UpdateEstablishment>>();
            _unitOfWork = ServiceProviderLocator.Current.GetService<IUnitOfWork>();
            _placeFinder = ServiceProviderLocator.Current.GetService<IConsumePlaceFinder>();
            try
            {
                var establishment = _queryProcessor.Execute(new GetEstablishmentByIdQuery(_establishmentId));
                if (!establishment.Location.Center.HasValue) return;

                var latitude = establishment.Location.Center.Latitude;
                var longitude = establishment.Location.Center.Longitude;
                if (!latitude.HasValue || !longitude.HasValue) return;

                var result = _placeFinder.Find(new PlaceByCoordinates(latitude.Value, longitude.Value)).SingleOrDefault();
                if (result == null) return;
                if (!result.WoeId.HasValue)
                {
                    throw new NotSupportedException(string.Format(
                        "Could not find WOE ID for coordinates {0},{1}", latitude, longitude));
                }
                //var place = _placeFactory.FromWoeId(result.WoeId.Value);
                var place = _queryProcessor.Execute(
                    new GetPlaceByWoeIdQuery
                    {
                        WoeId = result.WoeId.Value,
                    });
                var places = place.Ancestors.OrderByDescending(n => n.Separation).Select(a => a.Ancestor).ToList();
                places.Add(place);
                var command = new UpdateEstablishment
                {
                    Id = establishment.RevisionId,
                    PlaceIds = places.Select(p => p.RevisionId).ToArray(),
                };
                _updateEstablishment.Handle(command);
                //_establishment.Location.Places.Clear();
                //_establishment.Location.Places = places;
                //_objectCommander.Update(_establishment, true);
                //_entities.Update(_establishment);
                _unitOfWork.SaveChanges();
            }
            catch (Exception ex)
            {
                var exceptionLogger = ServiceProviderLocator.Current.GetService<ILogExceptions>();
                exceptionLogger.LogException(ex);

                if (ex is NotSupportedException)
                {
                    retryCount = 3;
                }

                if (retryCount < 2)
                {
                    Build(++retryCount);
                }
            }
        }
Ejemplo n.º 36
0
        internal static void ApplySecurity(this IEnumerable<Agreement> agreements, IPrincipal principal, IProcessQueries queryProcessor)
        {
            if (agreements == null) return;
            if (principal == null) throw new ArgumentNullException("principal");

            var ownedTenantIds = queryProcessor.Execute(new MyOwnedTenantIds(principal));
            foreach (var agreement in agreements)
                agreement.ApplySecurity(principal, ownedTenantIds);
        }
Ejemplo n.º 37
0
 internal static bool WorkCopy(int activityId, IProcessQueries queryProcessor)
 {
     var activity = queryProcessor.Execute(new ActivityById(activityId));
     return activity != null && activity.Original != null;
 }