Пример #1
0
        public async Task <Topic> RequireTopic(PangulDbContext db, UserContext user, string topic)
        {
            var existingTopic = await _getTopic.Execute(db, new GetTopic()
            {
                UserContext      = user,
                TopicName        = topic,
                IgnoreRowVersion = true
            });

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

            using (var outOfBandContext = db.CreateScope())
            {
                var newTopic = await _createTopic.Execute(outOfBandContext, new CreateTopic()
                {
                    UserContext = user,
                    TopicName   = topic
                });

                await outOfBandContext.SaveChangesAsync();

                return(newTopic);
            }
        }
Пример #2
0
        public IActionResult Get(string clientId, string clientVersion)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }

                var fetchTogglesForClientQuery = new FetchTogglesForClient(clientId, clientVersion);
                var toggles = _queryHandler.Execute(fetchTogglesForClientQuery);

                if (toggles.Any())
                {
                    return(Ok(toggles));
                }

                var notFoundMessage = $"The {clientId}:{clientVersion} client does not have any toggles";
                _log.LogError($"Resource not found:{notFoundMessage}");
                return(NotFound(notFoundMessage));
            }
            catch (Exception e)
            {
                _log.LogError($"{Resources.InternalErrorMessage}:{e.Message}");
                return(this.InternalServerError());
            }
        }
Пример #3
0
        public void GetTogglesForClient()
        {
            var result = _handler.Execute(new FetchTogglesForClient("client1", "*"))
                         .ToList();

            Assert.NotNull(result);
            Assert.NotEmpty(result);
            Assert.Equal(1, result.Count);
            Assert.Equal(result[0].Key, "toggleA");
            Assert.True(result[0].Value);
        }
Пример #4
0
 private Task <User> GetByUsername(PangulDbContext db, string usernmae)
 {
     try
     {
         return(_getUserDetails.Execute(db, new GetUserDetails()
         {
             Login = usernmae
         }));
     }
     catch (Exception error)
     {
         throw new PangulCommandFailedException(CommandFailureType.TransactionFailed, error);
     }
 }
        public string Execute(CreateReceipt cmd)
        {
            var client  = new RestClient(_endpoint);
            var request = new RestRequest(Method.POST);
            var token   = _tokenHandler.Execute(new GetToken());

            request.AddParameter("AuthToken", token, ParameterType.QueryString);
            var jsonContent = JsonConvert.SerializeObject(cmd);

            request.AddHeader("Accept", "application/json");
            request.RequestFormat = DataFormat.Json;
            request.AddParameter("application/json", jsonContent, ParameterType.RequestBody);
            var response = client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(response.StatusDescription);
            }

            var fermaResponse = JsonConvert.DeserializeObject <CreateReceiptResponse>(response.Content);

            if (!String.Equals(fermaResponse.Status, "Success", StringComparison.OrdinalIgnoreCase))
            {
                Log.ErrorFormat("... {error}", fermaResponse.Error);
                throw new Exception(fermaResponse.Status);
            }

            return(fermaResponse.Data.ReceiptId);
        }
Пример #6
0
            public string Execute(GetTranslation.Query query)
            {
                _logger.Debug($"Executing query for resource key `{query.Key}` for language: `{query.Language.Name}...");

                var service = ServiceLocator.Current.GetInstance<LocalizationService>();
                var foundTranslation = service.GetStringByCulture(query.Key, query.Language);

                // * if asked for fallback language and there is no resource translation for that language
                //   Episerver gonna return me string.Empty - LocalizationService.GetMissingFallbackResourceValue()
                //   this is a bit more trickier that initially might look like
                // * if asked to return translation explicitly in InvariantCulture
                //   Episerver will understand this as whichever fallback language is configured
                //   and will pass in that language to look for translation
                //   so we must check this explicitly here
                if(string.IsNullOrEmpty(foundTranslation)
                   && service.FallbackBehavior.HasFlag(FallbackBehaviors.FallbackCulture)
                   && query.UseFallback
                   && (Equals(query.Language, service.FallbackCulture) || Equals(query.Language.Parent, CultureInfo.InvariantCulture)))
                {
                    // no translation found for this language
                    // we need to respect fallback settings
                    _logger.Debug($"Null returned for resource key `{query.Key}` for language: `{query.Language.Name}`. Executing InvariantCulture fallback...");

                    return _originalHandler.Execute(new GetTranslation.Query(query.Key, CultureInfo.InvariantCulture, false));
                }

                return foundTranslation;
            }
 public async Task <List <DynamicMetadataDto> > GetAllMovieMetadatas(string movieId)
 {
     return(await _getMovieMetadataQueryHandler.Execute(new GetMovieMetadataQuery
     {
         MovieId = movieId
     }));
 }
        public int CalculateFullPrice(GoodLeadDto[] dtos)
        {
            var result = 0;

            foreach (var dto in dtos)
            {
                var good = _getGoods.Execute(new GetGoods()).First(x => x.ParkerId == dto.GoodId);
                result += dto.Count * good.Price;
                if (good.AbleToEngraving && !string.IsNullOrEmpty(dto.Engraving))
                {
                    result += GetEngravingPrice() * dto.Count;
                }
            }

            return(result);
        }
Пример #9
0
        public async Task <Answer> Execute(PangulDbContext db, CreateNewAnswer command)
        {
            command.Validate();

            // Fetch the question
            var question = await _getQuestion.Execute(db, new GetQuestion()
            {
                UserContext      = command.UserContext,
                QuestionId       = command.QuestionId,
                LightWeightOnly  = true,
                IgnoreRowVersion = true
            });

            if (question == null)
            {
                throw new PangulCommandFailedException(CommandFailureType.InvalidRelation, $"No such question: {command.QuestionId}");
            }

            // Create answer
            var answer = new Answer()
            {
                Body             = command.Body,
                User             = command.UserContext.User,
                QuestionId       = question.QuestionId,
                AnswerGlobalMeta = new AnswerGlobalMeta()
                {
                    Votes = 0
                }
            };

            await db.Answer.AddAsync(answer);

            // Return instance
            return(answer);
        }
Пример #10
0
        public TResult Send <TQuery, TResult>(TQuery query)
            where TQuery : IQuery
        {
            IQueryHandler <TQuery, TResult> handler = this._resolver.Resolve <IQueryHandler <TQuery, TResult> >();

            return(handler.Execute(query));
        }
        public ReceiptStatusDto Execute(GetReceiptStatus query)
        {
            var client  = new RestClient(_endpoint);
            var request = new RestRequest(Method.POST);
            var token   = _getTokenHandler.Execute(new GetToken());

            request.AddParameter("AuthToken", token, ParameterType.QueryString);
            var jsonContent = JsonConvert.SerializeObject(query);

            request.AddHeader("Accept", "application/json");
            request.RequestFormat = DataFormat.Json;
            request.AddParameter("application/json", jsonContent, ParameterType.RequestBody);
            var response = client.Execute(request);

            if (response.StatusCode != HttpStatusCode.OK)
            {
                throw new Exception(response.StatusDescription);
            }

            var fermaResponse = JsonConvert.DeserializeObject <ReceiptStatusResponse>(response.Content);

            if (!String.Equals(fermaResponse.Status, "Success", StringComparison.OrdinalIgnoreCase))
            {
                Log.ErrorFormat("... {error}", fermaResponse.Error);
                throw new Exception(fermaResponse.Status);
            }

            var data = fermaResponse.Data;

            return(new ReceiptStatusDto(data.StatusCode, data.StatusName, data.StatusMessage, data.ModifiedDateUtc,
                                        data.ReceiptDateUtc, data.Device.DeviceId, data.Device.RNM, data.Device.ZN,
                                        data.Device.FN, data.Device.FDN, data.Device.FPD));
        }
Пример #12
0
        // GET: Home
        public ActionResult Index(AllUsersQuery query)
        {
            var model = _allUsersQueryHandler.Execute(query);

            //В данном случае не важен движок рендеринга вью
            //Модель мы собираем извне и передаем в слой рендеринга.
            return(View(model));
        }
Пример #13
0
 public Task <Question> GetQuestion(PangulDbContext db, UserContext user, string questionId)
 {
     return(_getQuestion.Execute(db, new GetQuestion()
     {
         UserContext = user,
         QuestionId = questionId,
         IgnoreRowVersion = true,
     }));
 }
Пример #14
0
        private void executeToolStripButton_Click(object sender, EventArgs e)
        {
            IQueryHandler queryHandler = GetHandler <IQueryHandler>();

            if (queryHandler != null)
            {
                queryHandler.Execute();
            }
        }
Пример #15
0
        public IActionResult GetUsers(string nombres)
        {
            ListarUsuariosParameters Param = new ListarUsuariosParameters();

            Param.Nombre = nombres;
            var users = (ListarUsuariosResult)_user.Execute(Param);

            return(Ok(users.Hits));
        }
Пример #16
0
 public QueryModule(IQueryHandler <Guid, Person> queryHandler)
 {
     //for test guid e36c166a-4497-4be2-8a52-0faa15912f1d
     Get["/api/v1/persons/{id}"] = parameters =>
     {
         Person person = queryHandler.Execute(parameters.id);
         return(person == null ? HttpStatusCode.NotFound : Response.AsJson(Mapper.Map <PersonDto>(person)));
     };
 }
Пример #17
0
        public async Task Execute(PangulDbContext db, UpdateTopic command)
        {
            command.Validate();

            var topic = await _getTopic.Execute(db, new GetTopic()
            {
                TopicId     = command.TopicId,
                RowVersion  = command.RowVersion,
                UserContext = command.UserContext
            });

            if (topic == null)
            {
                throw new PangulCommandFailedException(CommandFailureType.MissingData, $"No such topic ({command.DerivedProperties.TopicId})");
            }

            command.ApplyTo(topic);
        }
Пример #18
0
 public async Task <Answer> GetAnswer(PangulDbContext db, UserContext user, string answerId)
 {
     return(await _getAnswer.Execute(db, new GetAnswer()
     {
         UserContext = user,
         AnswerId = answerId,
         IgnoreRowVersion = true
     }));
 }
        public QueryResult <TResult> Execute <TCommand, TResult>(TCommand commandMessage, IQueryHandler <TCommand, TResult> handler)
        {
            TResult result = default(TResult);

            var errors = Execute(commandMessage,
                                 delegate { result = handler.Execute(commandMessage); });

            return(new QueryResult <TResult>(errors, result));
        }
Пример #20
0
        public IActionResult getAllRolesForUser(int UserId)
        {
            var Param = new ListarRolesPorUsuarioParameter
            {
                UserId = UserId
            };
            var roles = (ListarRolesPorUsuarioResult)_hanlder_RolUser.Execute(Param);

            return(Ok(roles.Hits));
        }
        public IActionResult GetOrderDetail(long Id)
        {
            var param = new ObtenerOrdenReciboDetalleParameter {
                Id = Id
            };

            var resp = (ObtenerOrdenReciboDetalleResult)_handlerDetalle.Execute(param);

            return(Ok(resp));
        }
        public IActionResult GetOrderbyEquipoTransporte(long EquipoTransporteId)
        {
            var param = new ListarOrdenReciboByEquipoTransporteParameter
            {
                EquipoTransporteId = EquipoTransporteId,
            };
            var resp = (ListarOrdenReciboByEquipoTransporteResult)_handlerByEquipoTransporte.Execute(param);

            return(Ok(resp.Hits));
        }
Пример #23
0
        public IActionResult GetAll(Guid?Id)
        {
            var param = new ListarInventarioParameter {
                Id = Id
            };

            var resp = (ListarInventarioResult)_handler.Execute(param);

            return(Ok(resp.Hits));
        }
Пример #24
0
        public async Task Execute(PangulDbContext db, UpdateQuestion command)
        {
            command.Validate();

            // Get existing question
            var question = await _getQuestion.Execute(db, new GetQuestion()
            {
                UserContext     = command.UserContext,
                LightWeightOnly = false,
                QuestionId      = command.QuestionId,
                RowVersion      = command.RowVersion,
            });

            if (question == null)
            {
                throw new PangulCommandFailedException(CommandFailureType.MissingData, $"No such question ({command.QuestionId}, {command.RowVersion})");
            }

            // Verify user has permission
            await _internalUserPermissionService.RequireWriteAccessFor(question, command.UserContext);

            // Get tag lists
            var tags     = command.Tags ?? new string[0];
            var newTags  = tags.Where(i => question.Tags.All(j => j.Tag != i) && !string.IsNullOrWhiteSpace(i));
            var dropTags = question.Tags.Where(i => tags.All(j => j != i.Tag));

            // Update properties
            command.ApplyTo(question);

            // Drop old tags
            foreach (var tag in dropTags)
            {
                db.QuestionTag.Remove(tag);
            }

            // Create tags for those not present
            await db.QuestionTag.AddRangeAsync(newTags.Select(t => new QuestionTag
            {
                Tag        = t,
                QuestionId = question.QuestionId
            }));
        }
        public override string GetString(string originalKey, string[] normalizedKey, CultureInfo culture)
        {
            // we need to call handler directly here
            // if we would dispatch query and ask registered handler to execute
            // we would end up in stack-overflow as in EPiServer context
            // the same database localization provider is registered as the query handler
            var foundTranslation = _originalHandler.Execute(new GetTranslation.Query(originalKey, culture, false));

            // this is last chance for Episerver to find translation (asked in translation fallback language)
            // if no match is found and invariant fallback is configured - return invariant culture translation
            if (foundTranslation == null &&
                LocalizationService.Current.FallbackBehavior.HasFlag(FallbackBehaviors.FallbackCulture) &&
                ConfigurationContext.Current.EnableInvariantCultureFallback &&
                (Equals(culture, LocalizationService.Current.FallbackCulture) || Equals(culture.Parent, CultureInfo.InvariantCulture)))
            {
                return(_originalHandler.Execute(new GetTranslation.Query(originalKey, CultureInfo.InvariantCulture, false)));
            }

            return(foundTranslation);
        }
Пример #26
0
        public IActionResult GetProveedor(string criterio)
        {
            //   var result = await _repoProveedor.Get(x=>x.RazonSocial.Contains(razonsocial));
            var param = new ListarProveedorParameter
            {
                Criterio = criterio
            };
            var result = (ListarProveedorResult)_handlerProveedor.Execute(param);

            return(Ok(result.Hits));
        }
        public IActionResult GetOrder(Guid Id)
        {
            var param = new ObtenerOrdenReciboParameter {
                Id = Id
            };
            // var resp =  await  _repository.Get(x=>x.Id == Id);
            // var det =  await _repositoryDetalle.GetAll(x=>x.OrdenReciboId == Id);
            var resp = (ObtenerOrdenReciboResult)_handlerCab.Execute(param);

            return(Ok(resp));
        }
        public IActionResult ListEquipoTransporte(int?PropietarioId, int EstadoId, int?DaysAgo)
        {
            var param = new ListarEquipoTransporteParameter
            {
                EstadoId        = EstadoId
                , PropietarioId = PropietarioId
                , DaysAgo       = DaysAgo
            };
            var result = (ListarEquipoTransporteResult)_handlerListarEqTransporte.Execute(param);

            return(Ok(result.Hits.OrderByDescending(x => x.EquipoTransporte)));
        }
        public IActionResult GetOrders(int?PropietarioId, int?EstadoId, int?DaysAgo)
        {
            var param = new ListarOrdenReciboParameter
            {
                PropietarioId = PropietarioId,
                EstadoId      = EstadoId,
                DaysAgo       = DaysAgo
            };
            var resp = (ListarOrdenReciboResult)_handler.Execute(param);

            return(Ok(resp.Hits));
        }
Пример #30
0
        public async Task LoadPosts()
        {
            var query = new PostTeaserQuery(CurrentCategory?.Id, User)
            {
                IgnoreCategoryIfNull = !Options.IncludeAllCategories,
                PageNumber           = PageNumber ?? 0
            };

            var result = await _postTeaserHandler.Execute(query);

            Posts.AddRange(result);
        }