コード例 #1
0
        public async Task <IActionResult> GetUserStatistics(
            [FromHeader(Name = "X-AuthToken"), Required] string token,
            [FromServices, Required] IStorage <string> tokens)
        {
            _logger.LogInformation($"{nameof(StatisticsController)}: Request to get user statistics.");
            var userId = (await tokens.GetAllAsync())
                         .Where(tk => tk.Item == token)
                         .Select(tk => tk.Id)
                         .FirstOrDefault();

            if (userId > 0)     //if user was found
            {
                _logger.LogInformation($"{nameof(StatisticsController)}: User with id {userId} was identified by his/her authorization token.");

                // get user statistics
                var statistics = await _statistics.GetAsync(userId);

                if (statistics == null)
                {
                    _logger.LogWarning($"{nameof(StatisticsController)}: There is no statistics (even empty) for the user with id {userId}. Return {HttpStatusCode.NotFound}");
                    return(NotFound($"No statistics for the user yet."));
                }

                var userLogin     = (await _users.GetAsync(userId)).GetLogin();
                var statisticsOut = ModelsMapper.ToStatisticsOut(userLogin, statistics);
                _logger.LogInformation($"{nameof(StatisticsController)}: Show personal statistics to the user with id {userId}. Return {HttpStatusCode.OK}");

                return(Ok(statisticsOut));
            }

            _logger.LogInformation($"{nameof(StatisticsController)}: Authorization token did not exist or expired. User was not identified. Return {HttpStatusCode.Forbidden}");
            return(StatusCode((int)HttpStatusCode.Forbidden, "User was not defined. Repeat authorization, please."));
        }
コード例 #2
0
ファイル: FanService.cs プロジェクト: DamyGenius/risk
        public Respuesta <Pagina <Grupo> > ListarGrupos(string misGrupos, string tipoGrupo = null, string aceptado = null, string incluirUsuarios = null, PaginaParametros paginaParametros = null)
        {
            JObject prms = new JObject();

            prms.Add("mis_grupos", misGrupos);
            prms.Add("tipo_grupo", tipoGrupo);
            prms.Add("aceptado", aceptado);
            prms.Add("incluir_usuarios", incluirUsuarios);

            if (paginaParametros != null)
            {
                prms.Add("pagina_parametros", JToken.FromObject(ModelsMapper.GetEntityFromModel <PaginaParametros, YPaginaParametros>(paginaParametros)));
            }

            string rsp = base.ProcesarOperacion(TipoOperacion.Servicio.GetStringValue(),
                                                NOMBRE_LISTAR_GRUPOS,
                                                DOMINIO_OPERACION,
                                                prms.ToString(Formatting.None));
            var entityRsp = JsonConvert.DeserializeObject <YRespuesta <YPagina <YGrupo> > >(rsp);

            Pagina <Grupo> datos = null;

            if (entityRsp.Datos != null)
            {
                datos = EntitiesMapper.GetPaginaFromEntity <Grupo, YGrupo>(entityRsp.Datos, EntitiesMapper.GetModelListFromEntity <Grupo, YGrupo>(entityRsp.Datos.Elementos));
            }

            return(EntitiesMapper.GetRespuestaFromEntity <Pagina <Grupo>, YPagina <YGrupo> >(entityRsp, datos));
        }
コード例 #3
0
        public async Task <IActionResult> GetStatisticsAsync()
        {
            _logger.LogInformation($"{nameof(StatisticsController)}: Request to get general statistics.");
            var statistics = await _statistics.GetAllAsync();

            if (statistics.Any())
            {
                var users = await _users.GetAllAsync();

                var statisticsOut = statistics
                                    .Join(users, st => st.Id, us => us.Id,
                                          (stat, user) => ModelsMapper.ToStatisticsOut(user.Item.GetLogin(), stat.Item))
                                    .Where(st => st.TotalRoundsCount > _options.MinRoundsCount)
                                    .OrderByDescending(st => st.TotalOutcomesCounts.WinsCount);

                if (statisticsOut.Count() > 0)
                {
                    _logger.LogInformation($"{nameof(StatisticsController)}: Show statistics for {statisticsOut.Count()} user(s). Return {HttpStatusCode.OK}");
                    return(Ok(statisticsOut));
                }
            }

            _logger.LogInformation($"{nameof(StatisticsController)}: No statisctics to show. Return {HttpStatusCode.OK}");
            return(Ok());
        }
コード例 #4
0
ファイル: FanService.cs プロジェクト: DamyGenius/risk
        public Respuesta <Pagina <Prediccion> > ListarPrediccionesPartidos(string usuario, int?partido = null, string torneo = null, string estadosPartidos = null, string estadosPredicciones = null, PaginaParametros paginaParametros = null, OrdenLista orden = OrdenLista.ASC)
        {
            JObject prms = new JObject();

            prms.Add("partido", partido);
            prms.Add("torneo", torneo);
            prms.Add("estados_partidos", estadosPartidos);
            prms.Add("estados_predicciones", estadosPredicciones);
            prms.Add("usuario", usuario);
            if (paginaParametros != null)
            {
                prms.Add("pagina_parametros", JToken.FromObject(ModelsMapper.GetEntityFromModel <PaginaParametros, YPaginaParametros>(paginaParametros)));
            }
            prms.Add("orden", orden.ToString());

            string rsp = base.ProcesarOperacion(TipoOperacion.Servicio.GetStringValue(),
                                                NOMBRE_LISTAR_PREDICCIONES_PARTIDOS,
                                                DOMINIO_OPERACION,
                                                prms.ToString(Formatting.None));
            var entityRsp = JsonConvert.DeserializeObject <YRespuesta <YPagina <YPrediccion> > >(rsp);

            Pagina <Prediccion> datos = null;

            if (entityRsp.Datos != null)
            {
                datos = EntitiesMapper.GetPaginaFromEntity <Prediccion, YPrediccion>(entityRsp.Datos, EntitiesMapper.GetModelListFromEntity <Prediccion, YPrediccion>(entityRsp.Datos.Elementos));
            }

            return(EntitiesMapper.GetRespuestaFromEntity <Pagina <Prediccion>, YPagina <YPrediccion> >(entityRsp, datos));
        }
コード例 #5
0
        /// <summary>
        /// Return a track with the specified id purchased by the specified user.
        /// </summary>
        /// <param name="trackId">
        /// The track id.
        /// </param>
        /// <param name="userId">
        /// The user id.
        /// </param>
        /// <returns>
        /// A track with the specified id purchased by the specified user if exists or <b>null</b>.
        /// </returns>
        public PurchasedTrackViewModel GetPurchasedTrack(int trackId, int userId)
        {
            PurchasedTrack track;

            using (var repository = Factory.GetPurchasedTrackRepository())
            {
                track = repository.FirstOrDefault(
                    p => p.UserId == userId && p.TrackId == trackId,
                    p => p.Track,
                    p => p.Track.Artist,
                    p => p.Track.Genre);
            }

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

            var trackViewModel = ModelsMapper.GetPurchasedTrackViewModel(track.Track);

            using (var repository = Factory.GetVoteRepository())
            {
                trackViewModel.Rating = repository.GetAverageMark(track.Id);
            }

            return(trackViewModel);
        }
コード例 #6
0
        public void GetFeedbackViewModelTest()
        {
            var artistDto = CreateArtist();
            var genreDto  = CreateGenre();
            var trackDto  = CreateTrack(artistDto, genreDto);

            var userData = new UserData
            {
                Id = 1
            };

            var feedbackDto = new Feedback
            {
                Id       = 1,
                Comments = "Some comments",
                Track    = trackDto,
                TrackId  = trackDto.Id,
                User     = userData,
                UserId   = userData.Id
            };
            var feedback = ModelsMapper.GetFeedbackViewModel(feedbackDto);

            Assert.IsNotNull(feedback);
            Assert.IsTrue(feedback.UserDataId == userData.Id);
            Assert.IsTrue(feedback.Comments.Equals(feedbackDto.Comments, StringComparison.OrdinalIgnoreCase));
        }
コード例 #7
0
        public void GetPriceViewModelForAlbumPriceTest()
        {
            var currencyDto   = CreateCurrency();
            var priceLevelDto = CreatePriceLevel();

            var albumDto = new Album
            {
                Id   = 1,
                Name = "Some album"
            };

            var albumPriceDto = new AlbumPrice
            {
                Id           = 1,
                AlbumId      = albumDto.Id,
                Album        = albumDto,
                CurrencyId   = currencyDto.Id,
                Currency     = currencyDto,
                Price        = 4.99m,
                PriceLevelId = priceLevelDto.Id,
                PriceLevel   = priceLevelDto
            };

            var priceViewModel = ModelsMapper.GetPriceViewModel(albumPriceDto);

            Assert.IsNotNull(priceViewModel);

            Assert.IsTrue(priceViewModel.Amount == albumPriceDto.Price);

            Assert.IsNotNull(priceViewModel.Currency);
            Assert.IsTrue(priceViewModel.Currency.Code == albumPriceDto.Currency.Code);
            Assert.IsTrue(priceViewModel.Currency.ShortName.Equals(albumPriceDto.Currency.ShortName, StringComparison.OrdinalIgnoreCase));
            Assert.IsTrue(priceViewModel.Currency.FullName.Equals(albumPriceDto.Currency.FullName, StringComparison.OrdinalIgnoreCase));
            Assert.IsTrue(priceViewModel.Currency.Symbol.Equals(albumPriceDto.Currency.Symbol, StringComparison.OrdinalIgnoreCase));
        }
コード例 #8
0
        public async Task <HttpOperationResult <UserDto> > GetCurrentUserAsync()
        {
            logger.LogInformation($"Start execution method {nameof(GetCurrentUserAsync)}");
            logger.LogInformation($"Current user: {CurrentUser.Id}");

            if (!await userService.ExistsAsync(CurrentUser.Id))
            {
                return(HttpOperationResult <UserDto> .Ok(new()
                {
                    Id = CurrentUser.Id,
                    Email = CurrentUser.Id,
                    Name = CurrentUser.Name,
                    IsRegistered = false,
                    ProjectAccesses = new()
                    {
                        Admin = new List <string>(),
                        User = new List <string>()
                    }
                }));
            }

            var currentUser = await userService.GetByIdAsync(CurrentUser.Id);

            return(HttpOperationResult <UserDto> .Ok(ModelsMapper.ConvertUserServiceModelToDto(currentUser)));
        }
コード例 #9
0
ファイル: ArtistService.cs プロジェクト: sergeyUzer/musicShop
        private ICollection <ArtistViewModel> CreateArtistViewModelsList(ICollection <Artist> artists)
        {
            List <ArtistViewModel> artistViewModels = new List <ArtistViewModel>();

            using (var repository = Factory.GetTrackRepository())
            {
                foreach (var artist in artists)
                {
                    var artistViewModel = ModelsMapper.GetArtistViewModel(artist);
                    if (artistViewModel != null)
                    {
                        artistViewModel.TracksCount = repository.Count(t => t.ArtistId == artist.Id);
                        artistViewModels.Add(artistViewModel);
                    }
                }
            }

            using (var repository = Factory.GetAlbumRepository())
            {
                foreach (var artistViewModel in artistViewModels)
                {
                    artistViewModel.AlbumsCount = repository.Count(a => a.ArtistId != null && a.ArtistId == artistViewModel.Id);
                }
            }

            return(artistViewModels);
        }
コード例 #10
0
        public ActionResult Edit(AdvertisementModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }
            try
            {
                //Update
                if (ModelState.IsValid)
                {
                    var advertisement = _advertisementService.GetAdvertisementById(model.Id);
                    advertisement = new ModelsMapper().CreateMap <AdvertisementModel, Advertisement>(model, advertisement);
                    advertisement.UpdatedOnUtc = DateTime.UtcNow;
                    _advertisementService.UpdateAdvertisement(advertisement);
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception exc)
            {
                ModelState.AddModelError("", exc.Message + "<br />" + exc.InnerException.InnerException.Message);
            }

            PrepareAdvertisementModel(model, null, false, true);
            //AddLocales(_languageService, model.Locales);
            //PrepareAclModel(model, null, false);
            PrepareStoresMappingModel(model, null, false);
            return(View());
        }
コード例 #11
0
        public async Task <BuildConfig> CreateAsync(BuildConfig buildConfig)
        {
            var dbBuildConfig =
                await buildConfigRepository.AddAsync(ModelsMapper.ConvertBuildConfigServiceModelToDbModel(buildConfig));

            return(ModelsMapper.ConvertBuildConfigDbModelToServiceModel(dbBuildConfig));
        }
コード例 #12
0
        public Respuesta <Pagina <Error> > ListarErrores(string idError = null, PaginaParametros paginaParametros = null)
        {
            JObject prms = new JObject();

            prms.Add("id_error", idError);

            if (paginaParametros != null)
            {
                prms.Add("pagina_parametros", JToken.FromObject(ModelsMapper.GetEntityFromModel <PaginaParametros, YPaginaParametros>(paginaParametros)));
            }

            string rsp = base.ProcesarOperacion(TipoOperacion.Servicio.GetStringValue(),
                                                NOMBRE_LISTAR_ERRORES,
                                                DOMINIO_OPERACION,
                                                prms.ToString(Formatting.None));
            var entityRsp = JsonConvert.DeserializeObject <YRespuesta <YPagina <YError> > >(rsp);

            Pagina <Error> datos = null;

            if (entityRsp.Datos != null)
            {
                datos = EntitiesMapper.GetPaginaFromEntity <Error, YError>(entityRsp.Datos, EntitiesMapper.GetModelListFromEntity <Error, YError>(entityRsp.Datos.Elementos));
            }

            return(EntitiesMapper.GetRespuestaFromEntity <Pagina <Error>, YPagina <YError> >(entityRsp, datos));
        }
コード例 #13
0
ファイル: FanService.cs プロジェクト: DamyGenius/risk
        public Respuesta <Pagina <GrupoMensaje> > ListarMensajesGrupo(int idGrupo, long referenciaMensaje, PaginaParametros paginaParametros = null)
        {
            JObject prms = new JObject();

            prms.Add("id_grupo", idGrupo);
            if (paginaParametros != null)
            {
                prms.Add("pagina_parametros", JToken.FromObject(ModelsMapper.GetEntityFromModel <PaginaParametros, YPaginaParametros>(paginaParametros)));
            }

            string rsp = base.ProcesarOperacion(TipoOperacion.Servicio.GetStringValue(),
                                                NOMBRE_LISTAR_MENSAJES_GRUPO,
                                                DOMINIO_OPERACION,
                                                prms.ToString(Formatting.None));
            var entityRsp = JsonConvert.DeserializeObject <YRespuesta <YPagina <YGrupoMensaje> > >(rsp);

            Pagina <GrupoMensaje> datos = null;

            if (entityRsp.Datos != null)
            {
                datos = EntitiesMapper.GetPaginaFromEntity <GrupoMensaje, YGrupoMensaje>(entityRsp.Datos, EntitiesMapper.GetModelListFromEntity <GrupoMensaje, YGrupoMensaje>(entityRsp.Datos.Elementos));
            }

            return(EntitiesMapper.GetRespuestaFromEntity <Pagina <GrupoMensaje>, YPagina <YGrupoMensaje> >(entityRsp, datos));
        }
コード例 #14
0
        public ActionResult AdvertisementList(DataSourceRequest command, AdvertisementListModel model)
        {
            var ads = _advertisementService.SearchAdvertisements(
                storeId: model.SearchStoreId,
                vendorId: model.SearchVendorId,
                keywords: model.SearchAdvertisementName,
                pageIndex: command.Page - 1,
                pageSize: command.PageSize);

            var gridModel = new DataSourceResult();
            gridModel.Data = ads.Select(x =>
            {
                var adModel = new ModelsMapper().CreateMap<Advertisement, AdvertisementModel>(x);
                //little hack here:
                //ensure that product full descriptions are not returned
                //otherwise, we can get the following error if products have too long descriptions:
                //"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. "
                //also it improves performance
                adModel.Description = string.Empty;

                //picture
                //var defaultProductPicture = _pictureService.GetPicturesByProductId(x.Id, 1).FirstOrDefault();
                //adModel.PictureThumbnailUrl = _pictureService.GetPictureUrl(defaultProductPicture, 75, true);
                ////product type
                //adModel.ProductTypeName = x.ProductType.GetLocalizedEnum(_localizationService, _workContext);
                ////friendly stock qantity
                ////if a simple product AND "manage inventory" is "Track inventory", then display
                //if (x.ProductType == ProductType.SimpleProduct && x.ManageInventoryMethod == ManageInventoryMethod.ManageStock)
                //    adModel.StockQuantityStr = x.GetTotalStockQuantity().ToString();
                return adModel;
            });
            gridModel.Total = ads.TotalCount;

            return Json(gridModel);
        }
コード例 #15
0
        public Respuesta <Pagina <Aplicacion> > ListarAplicaciones(string idAplicacion = null, string claveAplicacion = null, PaginaParametros paginaParametros = null)
        {
            JObject prms = new JObject();

            prms.Add("id_aplicacion", idAplicacion);
            prms.Add("clave", claveAplicacion);

            if (paginaParametros != null)
            {
                prms.Add("pagina_parametros", JToken.FromObject(ModelsMapper.GetEntityFromModel <PaginaParametros, YPaginaParametros>(paginaParametros)));
            }

            string rsp = base.ProcesarOperacion(TipoOperacion.Servicio.GetStringValue(),
                                                NOMBRE_LISTAR_APLICACIONES,
                                                DOMINIO_OPERACION,
                                                prms.ToString(Formatting.None));
            var entityRsp = JsonConvert.DeserializeObject <YRespuesta <YPagina <SqlAplicacion> > >(rsp);

            Pagina <Aplicacion> datos = null;

            if (entityRsp.Datos != null)
            {
                datos = EntitiesMapper.GetPaginaFromEntity <Aplicacion, SqlAplicacion>(entityRsp.Datos, EntitiesMapper.GetModelListFromEntity <Aplicacion, SqlAplicacion>(entityRsp.Datos.Elementos));
            }

            return(EntitiesMapper.GetRespuestaFromEntity <Pagina <Aplicacion>, YPagina <SqlAplicacion> >(entityRsp, datos));
        }
コード例 #16
0
ファイル: FanService.cs プロジェクト: DamyGenius/risk
        public Respuesta <Pagina <ReaccionPartido> > ListarReaccionesPartido(int idPartido, long referenciaComentario, PaginaParametros paginaParametros = null)
        {
            JObject prms = new JObject();

            prms.Add("tipo", TipoReaccion.Partido.GetStringValue());
            prms.Add("referencia", idPartido);
            if (paginaParametros != null)
            {
                prms.Add("pagina_parametros", JToken.FromObject(ModelsMapper.GetEntityFromModel <PaginaParametros, YPaginaParametros>(paginaParametros)));
            }

            string rsp = base.ProcesarOperacion(TipoOperacion.Servicio.GetStringValue(),
                                                NOMBRE_LISTAR_REACCIONES,
                                                DOMINIO_OPERACION,
                                                prms.ToString(Formatting.None));
            var entityRsp = JsonConvert.DeserializeObject <YRespuesta <YPagina <YReaccion> > >(rsp);

            Pagina <ReaccionPartido> datos = null;

            if (entityRsp.Datos != null)
            {
                datos = EntitiesMapper.GetPaginaFromEntity <ReaccionPartido, YReaccion>(entityRsp.Datos, EntitiesMapper.GetModelListFromEntity <ReaccionPartido, YReaccion>(entityRsp.Datos.Elementos));
            }

            return(EntitiesMapper.GetRespuestaFromEntity <Pagina <ReaccionPartido>, YPagina <YReaccion> >(entityRsp, datos));
        }
コード例 #17
0
        /// <summary>
        /// Saving user statistics both in the storage and in the json file database
        /// if user is identified by his/her authorization <paramref name="token"/>.
        /// </summary>
        /// <param name="token">User's authorization token.</param>
        /// <param name="outcome">Game outcome. One of <see cref="GameOutcome"/></param>
        /// <param name="move">Chosen move option. One of <see cref="MoveOptions"/></param>
        /// <returns>Returns true if user was found by token, else returns false.</returns>
        public async Task <bool> SaveAsync(string token, GameOutcome outcome, MoveOptions move)
        {
            // get user id
            var userWithToken = (await _tokens.GetAllAsync()).Where(tk => tk.Item == token).FirstOrDefault();

            // if user was not found
            if (userWithToken == null)
            {
                // only one logger message here so as not to litter the file with messages
                // about saving statistics, since this method will be called very often
                _logger.LogInformation($"{nameof(StatisticsService)}: User was not identified for saving statistics. The authorization token did not exist or expired.");
                return(false);
            }

            // get user id
            var userId = userWithToken.Id;

            // add user statistics to the storage if it doesn't exist
            await _statistics.AddAsync(new UserStatistics(userId), userId, new StatisticsEqualityComparer());

            // change state
            var record = await _statistics.GetAsync(userId);

            record.AddRoundInfo(DateTime.Now, outcome, move);

            // map with StatisticsDb
            var statisticsToSave = ModelsMapper.ToStatisticsDb(record);

            //save to file
            await _jsonDataService.WriteAsync(_options.StatisticsPath + $"{userId}.json", statisticsToSave);

            return(true);
        }
コード例 #18
0
        public Respuesta <Pagina <Barrio> > ListarBarrios(int?idBarrio = null, int?idPais = null, int?idDepartamento = null, int?idCiudad = null, PaginaParametros paginaParametros = null)
        {
            JObject prms = new JObject();

            prms.Add("id_barrio", idBarrio);
            prms.Add("id_pais", idPais);
            prms.Add("id_departamento", idDepartamento);
            prms.Add("id_ciudad", idCiudad);

            if (paginaParametros != null)
            {
                prms.Add("pagina_parametros", JToken.FromObject(ModelsMapper.GetEntityFromModel <PaginaParametros, YPaginaParametros>(paginaParametros)));
            }

            string rsp = base.ProcesarOperacion(TipoOperacion.Servicio.GetStringValue(),
                                                NOMBRE_LISTAR_BARRIOS,
                                                DOMINIO_OPERACION,
                                                prms.ToString(Formatting.None));
            var entityRsp = JsonConvert.DeserializeObject <YRespuesta <YPagina <YBarrio> > >(rsp);

            Pagina <Barrio> datos = null;

            if (entityRsp.Datos != null)
            {
                datos = EntitiesMapper.GetPaginaFromEntity <Barrio, YBarrio>(entityRsp.Datos, EntitiesMapper.GetModelListFromEntity <Barrio, YBarrio>(entityRsp.Datos.Elementos));
            }

            return(EntitiesMapper.GetRespuestaFromEntity <Pagina <Barrio>, YPagina <YBarrio> >(entityRsp, datos));
        }
コード例 #19
0
        public Respuesta <Pagina <Significado> > ListarSignificados(string dominio, PaginaParametros paginaParametros = null)
        {
            JObject prms = new JObject();

            prms.Add("dominio", dominio);

            if (paginaParametros != null)
            {
                prms.Add("pagina_parametros", JToken.FromObject(ModelsMapper.GetEntityFromModel <PaginaParametros, YPaginaParametros>(paginaParametros)));
            }

            string rsp = base.ProcesarOperacion(TipoOperacion.Servicio.GetStringValue(),
                                                NOMBRE_LISTAR_SIGNIFICADOS,
                                                DOMINIO_OPERACION,
                                                prms.ToString(Formatting.None));
            var entityRsp = JsonConvert.DeserializeObject <YRespuesta <YPagina <YSignificado> > >(rsp);

            Pagina <Significado> datos = null;

            if (entityRsp.Datos != null)
            {
                datos = EntitiesMapper.GetPaginaFromEntity <Significado, YSignificado>(entityRsp.Datos, EntitiesMapper.GetModelListFromEntity <Significado, YSignificado>(entityRsp.Datos.Elementos));
            }

            return(EntitiesMapper.GetRespuestaFromEntity <Pagina <Significado>, YPagina <YSignificado> >(entityRsp, datos));
        }
コード例 #20
0
        public ActionResult Edit(int Id)
        {
            var auction = _auctionService.GetAuctionById(Id);
            var model   = new ModelsMapper().CreateMap <Auction, AuctionModel>(auction);

            PrepareAuctionModel(model, null, true, true);
            return(View(model));
        }
コード例 #21
0
 /// <summary>
 /// </summary>
 /// <param name="id">
 /// The id.
 /// </param>
 /// <returns>
 /// </returns>
 public GenreDetailsViewModel GetGenreDetailsViewModel(int id)
 {
     using (var repository = Factory.GetGenreRepository())
     {
         var genre = repository.GetById(id);
         return(ModelsMapper.GetGenreDetailsViewModel(genre));
     }
 }
コード例 #22
0
        public async Task <HttpOperationResult <BuildDto> > GetLastAsync([FromRoute] Guid buildConfigId)
        {
            logger.LogInformation($"Start execution method '{nameof(GetLastAsync)}'");

            var build = await buildService.GetLastBuildAsync(buildConfigId);

            return(HttpOperationResult <BuildDto> .Ok(ModelsMapper.ConvertBuildServiceModelToDto(build)));
        }
コード例 #23
0
ファイル: UserRepository.cs プロジェクト: vanmxpx/ISDPlatform
        public UserRepository(IJwtHandlerService jwtService, IConfigProvider configProvider)
        {
            userDAO   = new UserDAO(configProvider);
            verifyDAO = new VerificationDAO(configProvider);
            mapper    = new ModelsMapper();

            this.jwtService = jwtService;
        }
コード例 #24
0
ファイル: PaginaParametros.cs プロジェクト: DamyGenius/risk
 public IEntity ConvertToEntity()
 {
     return(new YPaginaParametros
     {
         Pagina = this.Pagina,
         PorPagina = this.PorPagina,
         NoPaginar = ModelsMapper.GetValueFromBool(this.NoPaginar)
     });
 }
コード例 #25
0
ファイル: Index.cshtml.cs プロジェクト: cosminf98/TSP-NET
        public async Task OnGetAsync()
        {
            var posts = await pcc.GetPostsAsync();

            foreach (var post in posts)
            {
                Posts.Add(ModelsMapper.GetPostDTO(post));
            }
        }
コード例 #26
0
 public List <CategoriesApiResponce> Get()
 {
     return(SimpleRepository.Get <Category>().Select(t =>
     {
         var category = ModelsMapper.Map <CategoriesApiResponce>(t);
         category.Image = Path.Combine(ProductsImagesFolderPath, t.Image ?? "");
         return category;
     }).ToList());
 }
コード例 #27
0
        /// <summary>
        /// Adds a new feedback or updates existent feedback for the specified track.
        /// </summary>
        /// <param name="feedbackViewModel">
        /// The user feedback.
        /// </param>
        public void AddOrUpdateFeedback(FeedbackViewModel feedbackViewModel)
        {
            if (feedbackViewModel == null)
            {
                throw new ArgumentNullException(nameof(feedbackViewModel));
            }

            using (var repository = Factory.GetFeedbackRepository())
            {
                var feedback = repository.FirstOrDefault(f => f.TrackId == feedbackViewModel.TrackId && f.UserId == feedbackViewModel.UserDataId);

                if (feedback == null)
                {
                    if (!string.IsNullOrWhiteSpace(feedbackViewModel.Comments))
                    {
                        feedback = ModelsMapper.GetFeedback(feedbackViewModel);
                    }
                }
                else
                {
                    feedback.Comments = feedbackViewModel.Comments;
                }

                if (feedback != null)
                {
                    if (!string.IsNullOrWhiteSpace(feedback.Comments))
                    {
                        repository.AddOrUpdate(feedback);
                    }
                    else
                    {
                        repository.Delete(feedback);
                    }
                    repository.SaveChanges();
                }
            }

            if (feedbackViewModel.Mark > 0)
            {
                using (var repository = Factory.GetVoteRepository())
                {
                    var vote = repository.FirstOrDefault(v => v.TrackId == feedbackViewModel.TrackId && v.UserId == feedbackViewModel.UserDataId);

                    if (vote == null)
                    {
                        vote = ModelsMapper.GetVote(feedbackViewModel);
                    }
                    else
                    {
                        vote.Mark = feedbackViewModel.Mark;
                    }

                    repository.AddOrUpdate(vote);
                    repository.SaveChanges();
                }
            }
        }
コード例 #28
0
        public void GetGenreViewModelTest()
        {
            var genreDto = CreateGenre();
            var genre    = ModelsMapper.GetGenreViewModel(genreDto);

            Assert.IsNotNull(genre);
            Assert.IsTrue(genre.Id == genreDto.Id);
            Assert.IsTrue(genre.Name.Equals(genreDto.Name, StringComparison.OrdinalIgnoreCase));
        }
コード例 #29
0
        public async Task <HttpOperationResult <ProjectDto> > GetAsync([FromRoute] Guid id)
        {
            logger.LogInformation($"Start execution method '{nameof(GetAsync)}'. Id = '{id}'");
            var project = await projectService.GetByIdAsync(id, CurrentUser);

            var dtoModel = ModelsMapper.ConvertProjectServiceModelToDtoModel(project);

            return(HttpOperationResult <ProjectDto> .Ok(dtoModel));
        }
コード例 #30
0
        public async Task <List <Project> > GetAllAsync(AuthenticatedUser currentUser)
        {
            var user       = ModelsMapper.ConvertUserDatabaseModelToService(await userRepository.FindByIdAsync(currentUser.Id));
            var dbProjects = await projectRepository.GetAllAsync();

            return(dbProjects
                   .Where(x => user.ProjectAccesses.User.Contains(x.Id.ToString()))
                   .Select(ModelsMapper.ConvertProjectDbModelToServiceModel)
                   .ToList());
        }
コード例 #31
0
        public void GetArtistViewModelTest()
        {
            var artistDto       = CreateArtist();
            var artistViewModel = ModelsMapper.GetArtistViewModel(artistDto);

            Assert.IsNotNull(artistViewModel);

            Assert.IsTrue(artistViewModel.Id == artistDto.Id);
            Assert.IsTrue(artistViewModel.Name.Equals(artistDto.Name, StringComparison.OrdinalIgnoreCase));
        }
コード例 #32
0
        public ActionResult Create(ReplyModel model)
        {
            if (ModelState.IsValid)
            {
                var reply = new ModelsMapper().CreateMap<ReplyModel, Reply>(model);
                reply.VendorId = _workContext.CurrentVendor.Id;
                reply.CreatedOnUtc = DateTime.Now;
                _ticketService.InsertReply(reply);
                return RedirectToAction("Details", "Tickets", new { Id = model.TicketId });
            }

            return View("Create");
        }
コード例 #33
0
        public ActionResult Details(int Id)
        {
            var ticket = _ticketService.GetTicketById(Id);
            var ticketModel = new ModelsMapper().CreateMap<Ticket, TicketModel>(ticket);
            var replies = _ticketService.GetRepliesByTicketId(ticket.Id);
            
            var model = new TicketDetailsModel
            {
                TicketModel = ticketModel,
                Replies = replies,
                TicketId = ticket.Id
            };

            return View(model);
        }
コード例 #34
0
        public ActionResult Edit(AdvertisementModel model)
        {
            if (model == null)
                throw new ArgumentNullException("model");
            try
            {
                //Update
                if (ModelState.IsValid)
                {
                    var advertisement = _advertisementService.GetAdvertisementById(model.Id);
                    advertisement = new ModelsMapper().CreateMap<AdvertisementModel, Advertisement>(model, advertisement);
                    advertisement.UpdatedOnUtc = DateTime.UtcNow;
                    _advertisementService.UpdateAdvertisement(advertisement);
                    return RedirectToAction("Index");
                }
            }
            catch (Exception exc)
            {
                ModelState.AddModelError("", exc.Message + "<br />" + exc.InnerException.InnerException.Message);
            }

            PrepareAdvertisementModel(model, null, false, true);
            //AddLocales(_languageService, model.Locales);
            //PrepareAclModel(model, null, false);
            PrepareStoresMappingModel(model, null, false);
            return View();
        }
コード例 #35
0
        public ActionResult Edit(int Id)
        {
            var auction = _auctionService.GetAuctionById(Id);
            var model = new ModelsMapper().CreateMap<Auction, AuctionModel>(auction);

            PrepareAuctionModel(model, null, true, true);
            return View(model);
        }
コード例 #36
0
        public ActionResult Edit(AuctionModel model)
        {
            if (model == null)
                throw new ArgumentNullException("model");

            if (ModelState.IsValid)
            {
                var auction = new ModelsMapper().CreateMap<AuctionModel, Auction>(model);
                auction.UpdatedOnUtc = DateTime.UtcNow;
                auction.StartingDate = DateTime.UtcNow;
                _auctionService.UpdateAuction(auction);
                return RedirectToAction("Index");
            }

            PrepareAuctionModel(model, null, true, true);
            return View();
        }
コード例 #37
0
        public ActionResult Create(AdvertisementModel model, HttpPostedFileBase Banner)
        {
            if (model == null)
                throw new ArgumentNullException("advertisement");

            string requestUrl = string.Format(Request.Url.Scheme + "://" + Request.Url.Authority + "/Admin/Picture/AsyncUpload");
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "application/json; charset=UTF-8";

            var email = "*****@*****.**";
            var password = "******";
            string credentials = String.Format("{0}:{1}", email, password);
            byte[] bytes = Encoding.ASCII.GetBytes(credentials);
            string base64 = Convert.ToBase64String(bytes);
            string authorization = String.Concat("Basic ", base64);
            request.Headers.Add("Authorization", authorization);

            //byte[] fileBytes = System.IO.File.ReadAllBytes(Banner.FileName);
            //StringBuilder serializedBytes = new StringBuilder();

            ////Let's serialize the bytes of your file
            //fileBytes.ToList<byte>().ForEach(x => serializedBytes.AppendFormat("{0}.", Convert.ToUInt32(x)));
            //string postParameters = String.Format("{0}", serializedBytes.ToString());
            //byte[] postData = Encoding.UTF8.GetBytes(postParameters);
            //////////////

            byte[] data;
            using (Stream inputStream = Banner.InputStream)
            {
                MemoryStream memoryStream = inputStream as MemoryStream;
                //whether the stream returned is already a MemoryStream
                if (memoryStream == null)
                {
                    memoryStream = new MemoryStream();
                    inputStream.CopyTo(memoryStream);
                }
                data = memoryStream.ToArray();
            }

            byte[] buffer = new byte[0x1000];
            Banner.InputStream.Read(buffer, 0, buffer.Length);
            //////////////////////////////////
            using (var streamWriter = request.GetRequestStream())
            {
                streamWriter.Write(data, 0, data.Length);
                streamWriter.Flush();
                streamWriter.Close();
            }

            var httpResponse = (HttpWebResponse)request.GetResponse();
            //Receipt Receipt = null;
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                var responstText = streamReader.ReadToEnd();
                //Receipt = serializer.Deserialize<Receipt>(responstText);
            }

            try
            {
                if (ModelState.IsValid)
                {
                    //a vendor should have access only to his products
                    if (_workContext.CurrentVendor != null)
                    {
                        model.VendorId = _workContext.CurrentVendor.Id;
                    }

                    var advertise = new ModelsMapper().CreateMap<AdvertisementModel, Advertisement>(model);
                    advertise.CreatedOnUtc = DateTime.UtcNow;
                    advertise.UpdatedOnUtc = DateTime.UtcNow;

                    _advertisementService.InsertAdvertisement(advertise);

                    return RedirectToAction("Edit", new { Id = model.Id });
                }
            }
            catch (Exception exc)
            {
                ModelState.AddModelError("", exc.Message + "<br />" + exc.InnerException.InnerException.Message);
            }

            PrepareAdvertisementModel(model, null, true, true);
            //AddLocales(_languageService, model.Locales);
            //PrepareAclModel(model, null, false);
            PrepareStoresMappingModel(model, null, false);
            return View(model);
        }
コード例 #38
0
        public ActionResult Edit(int id)
        {
            var advertisement = _advertisementService.GetAdvertisementById(id);
            if (advertisement == null || advertisement.Deleted)
                //No advertisement found with the specified id
                return RedirectToAction("List");

            var model = new ModelsMapper().CreateMap<Advertisement, AdvertisementModel>(advertisement);

            PrepareAdvertisementModel(model, null, false, true);
            //AddLocales(_languageService, model.Locales);
            //PrepareAclModel(model, null, false);
            PrepareStoresMappingModel(model, null, false);

            return View(model);
        }
コード例 #39
0
        public ActionResult GroupDealList(DataSourceRequest command, GroupDealListModel model)
        {
            //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
            //    return AccessDeniedView();

            //a vendor should have access only to his products
            if (_workContext.CurrentVendor != null)
            {
                //model.SearchVendorId = _workContext.CurrentVendor.Id;
            }

            var categoryIds = new List<int> { model.SearchCategoryId };
            //include subcategories
            if (model.SearchIncludeSubCategories && model.SearchCategoryId > 0)
                categoryIds.AddRange(GetChildCategoryIds(model.SearchCategoryId));

            //0 - all (according to "ShowHidden" parameter)
            //1 - published only
            //2 - unpublished only
            bool? overridePublished = null;
            if (model.SearchPublishedId == 1)
                overridePublished = true;
            else if (model.SearchPublishedId == 2)
                overridePublished = false;

            var groupDeals = _groupdealService.SearchGroupDeals(
                categoryIds: categoryIds,
                manufacturerId: model.SearchManufacturerId,
                storeId: model.SearchStoreId,
                vendorId: model.SearchVendorId,
                warehouseId: model.SearchWarehouseId,
                productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null,
                keywords: model.SearchProductName,
                pageIndex: command.Page - 1,
                pageSize: command.PageSize,
                showHidden: true,
                overridePublished: overridePublished
            );
            var gridModel = new DataSourceResult();
            gridModel.Data = groupDeals.Select(x =>
            {
                //var productModel = x.ToModel();
                var groupDealModel = new ModelsMapper().CreateMap<Product, GroupDealViewModel>(x);
                //little hack here:
                //ensure that product full descriptions are not returned
                //otherwise, we can get the following error if products have too long descriptions:
                //"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. "
                //also it improves performance
                groupDealModel.FullDescription = "";

                //picture
                var defaultProductPicture = _pictureService.GetPicturesByProductId(x.Id, 1).FirstOrDefault();
                groupDealModel.PictureThumbnailUrl = _pictureService.GetPictureUrl(defaultProductPicture, 75, true);
                //product type
                groupDealModel.ProductTypeName = x.ProductType.GetLocalizedEnum(_localizationService, _workContext);
                //friendly stock qantity
                //if a simple product AND "manage inventory" is "Track inventory", then display
                if (x.ProductType == ProductType.SimpleProduct && x.ManageInventoryMethod == ManageInventoryMethod.ManageStock)
                    groupDealModel.StockQuantityStr = x.GetTotalStockQuantity().ToString();
                if (x.AvailableStartDateTimeUtc < x.AvailableEndDateTimeUtc)
                {
                    groupDealModel.GroupdealStatusName = PluginHelper.GetAttribute<DisplayAttribute>(GroupdealStatus.Running).Name;
                }
                else
                {
                    groupDealModel.GroupdealStatusName = PluginHelper.GetAttribute<DisplayAttribute>(GroupdealStatus.Ended).Name;
                }
                return groupDealModel;
            });
            gridModel.Total = groupDeals.TotalCount;

            return Json(gridModel);
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////
            //var groupDeals = _groupdealService.GetAllGroupdeals().ToList();
            //var groupDeals = _groupdealService.GetAllGroupDealProducts().ToList();

            //var groupDealViewModels = new List<GroupDealViewModel>();
            //foreach (var gd in groupDeals)
            //{
            //    //var gdvm = new ModelsMapper().CreateMap<GroupDeal, GroupDealViewModel>(gd);
            //    var gdvm = new ModelsMapper().CreateMap<Product, GroupDealViewModel>(gd);
            //    if (gd.AvailableStartDateTimeUtc < gd.AvailableEndDateTimeUtc)
            //    {
            //        gdvm.GroupdealStatusName = PluginHelper.GetAttribute<DisplayAttribute>(GroupdealStatus.Running).Name;
            //    }
            //    else
            //    {
            //        gdvm.GroupdealStatusName = PluginHelper.GetAttribute<DisplayAttribute>(GroupdealStatus.Ended).Name;
            //    }
            //    groupDealViewModels.Add(gdvm);
            //}

            //var gridModel = new DataSourceResult
            //{
            //    Data = groupDealViewModels,
            //    Total = groupDealViewModels.Count
            //};

            //return Json(gridModel);
        }
コード例 #40
0
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }
            var groupdeal = _productService.GetProductById((int)id);
            var model = new ModelsMapper().CreateMap<Product, GroupDealViewModel>(groupdeal);

            var vendors = _vendorService.GetAllVendors();
            model.AvailableVendors = new List<SelectListItem>();
            foreach (var vendor in vendors)
            {
                model.AvailableVendors.Add(new SelectListItem
                {
                    Text = vendor.Name,
                    Value = vendor.Id.ToString()
                });
            }
            PrepareGroupdealViewModel(model, groupdeal, false, false);

            return View("EditGroupDeal", model);
        }
コード例 #41
0
        public ActionResult Edit(GroupDealViewModel model, bool continueEditing)
        {
            var groupDeal = _productService.GetProductById(model.Id);
            if (groupDeal == null || groupDeal.Deleted)
                //No product found with the specified id
                return RedirectToAction("Index", new { area = "Admin" });

            //a vendor should have access only to his products
            if (_workContext.CurrentVendor != null && groupDeal.VendorId != _workContext.CurrentVendor.Id)
                return RedirectToAction("Index", new { area = "Admin" });

            if (ModelState.IsValid)
            {
                //a vendor should have access only to his products
                if (_workContext.CurrentVendor != null)
                {
                    model.VendorId = _workContext.CurrentVendor.Id;
                }
                //vendors cannot edit "Show on home page" property
                if (_workContext.CurrentVendor != null && model.ShowOnHomePage != groupDeal.ShowOnHomePage)
                {
                    model.ShowOnHomePage = groupDeal.ShowOnHomePage;
                }
                var prevStockQuantity = groupDeal.GetTotalStockQuantity();

                //groupdeal
                //groupdeal = model.ToEntity(groupdeal);
                model.CreatedOn = groupDeal.CreatedOnUtc;
                groupDeal = new ModelsMapper().CreateMap<GroupDealViewModel, Product>(model, groupDeal);
                groupDeal.UpdatedOnUtc = DateTime.UtcNow;
                _productService.UpdateProduct(groupDeal);
                //search engine name
                model.SeName = groupDeal.ValidateSeName(model.SeName, "groupdeal.Name", true);
                _urlRecordService.SaveSlug(groupDeal, model.SeName, 0);
                ////locales
                //UpdateLocales(groupdeal, model);
                ////tags
                //SaveProductTags(groupdeal, ParseProductTags(model.ProductTags));
                ////warehouses
                //SaveProductWarehouseInventory(groupdeal, model);
                ////ACL (customer roles)
                //SaveProductAcl(groupdeal, model);
                ////Stores
                //SaveStoreMappings(groupdeal, model);
                ////picture seo names
                //UpdatePictureSeoNames(groupdeal);
                ////discounts
                //var allDiscounts = _discountService.GetAllDiscounts(DiscountType.AssignedToSkus, showHidden: true);
                //foreach (var discount in allDiscounts)
                //{
                //    if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id))
                //    {
                //        //new discount
                //        if (groupdeal.AppliedDiscounts.Count(d => d.Id == discount.Id) == 0)
                //            groupdeal.AppliedDiscounts.Add(discount);
                //    }
                //    else
                //    {
                //        //remove discount
                //        if (groupdeal.AppliedDiscounts.Count(d => d.Id == discount.Id) > 0)
                //            groupdeal.AppliedDiscounts.Remove(discount);
                //    }
                //}
                //_productService.UpdateProduct(groupdeal);
                //_productService.UpdateHasDiscountsApplied(groupdeal);
                ////back in stock notifications
                //if (groupdeal.ManageInventoryMethod == ManageInventoryMethod.ManageStock &&
                //    groupdeal.BackorderMode == BackorderMode.NoBackorders &&
                //    groupdeal.AllowBackInStockSubscriptions &&
                //    groupdeal.GetTotalStockQuantity() > 0 &&
                //    prevStockQuantity <= 0 &&
                //    groupdeal.Published &&
                //    !groupdeal.Deleted)
                //{
                //    _backInStockSubscriptionService.SendNotificationsToSubscribers(groupdeal);
                //}

                ////activity log
                //_customerActivityService.InsertActivity("EditProduct", _localizationService.GetResource("ActivityLog.EditProduct"), groupdeal.Name);

                //SuccessNotification(_localizationService.GetResource("Admin.Catalog.Products.Updated"));

                if (continueEditing)
                {
                    //selected tab
                    //SaveSelectedTabIndex();

                    return RedirectToAction("Edit", new { id = groupDeal.Id, area = "Admin" });
                }
                return RedirectToAction("Index", new { area = "Admin" });
            }

            //If we got this far, something failed, redisplay form
            //PrepareProductModel(model, groupdeal, false, true);
            //PrepareAclModel(model, groupdeal, true);
            //PrepareStoresMappingModel(model, groupdeal, true);
            return View("EditGroupDeal", model);
        }
コード例 #42
0
        public ActionResult Create(GroupDealViewModel model)
        {
            //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
            //    return AccessDeniedView();

            if (ModelState.IsValid)
            {
                //a vendor should have access only to his products
                if (_workContext.CurrentVendor != null)
                {
                    model.VendorId = _workContext.CurrentVendor.Id;
                }
                //vendors cannot edit "Show on home page" property
                if (_workContext.CurrentVendor != null && model.ShowOnHomePage)
                {
                    model.ShowOnHomePage = false;
                }

                //var groupDeal = new ModelsMapper().CreateMap<GroupDealViewModel, GroupDeal>(model);
                var groupDealProduct = new ModelsMapper().CreateMap<GroupDealViewModel, Product>(model);
                groupDealProduct.DisplayOrder = 1;
                groupDealProduct.ProductType = ProductType.SimpleProduct;
                groupDealProduct.OrderMaximumQuantity = 10;
                groupDealProduct.OrderMinimumQuantity = 1;
                groupDealProduct.Published = true;

                // datetime fields
                groupDealProduct.CreatedOnUtc = DateTime.UtcNow;
                groupDealProduct.UpdatedOnUtc = DateTime.UtcNow;
                groupDealProduct.AvailableEndDateTimeUtc = DateTime.Parse("01/01/2016");
                groupDealProduct.AvailableStartDateTimeUtc = DateTime.UtcNow;
                groupDealProduct.PreOrderAvailabilityStartDateTimeUtc = DateTime.UtcNow;
                groupDealProduct.SpecialPriceStartDateTimeUtc = DateTime.UtcNow;
                groupDealProduct.SpecialPriceEndDateTimeUtc = DateTime.Parse("01/01/2016");
                //_groupdealService.InsertGroupDeal(groupDeal);
                _productService.InsertProduct(groupDealProduct);

                //search engine name
                model.SeName = groupDealProduct.ValidateSeName(model.SeName, groupDealProduct.Name, true);
                _urlRecordService.SaveSlug(groupDealProduct, model.SeName, 0);

                groupDealProduct.SetIsGroupDeal(true);
                _genericAttributeService.SaveAttribute(groupDealProduct, GroupDealAttributes.Active, true);
                _genericAttributeService.SaveAttribute(groupDealProduct, GroupDealAttributes.FinePrint, model.FinePrint);
                
                return RedirectToAction("Index", new { area = "Admin" });
            }

            return View("CreateGroupdeal", model);
        }
コード例 #43
0
        public ActionResult ProductList(DataSourceRequest command, Nop.Admin.Models.Catalog.ProductListModel model)
        {
            //if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts))
            //    return AccessDeniedView();

            //a vendor should have access only to his products
            if (_workContext.CurrentVendor != null)
            {
                model.SearchVendorId = _workContext.CurrentVendor.Id;
            }

            var categoryIds = new List<int> { model.SearchCategoryId };
            //include subcategories
            if (model.SearchIncludeSubCategories && model.SearchCategoryId > 0)
                categoryIds.AddRange(GetChildCategoryIds(model.SearchCategoryId));

            //0 - all (according to "ShowHidden" parameter)
            //1 - published only
            //2 - unpublished only
            bool? overridePublished = null;
            if (model.SearchPublishedId == 1)
                overridePublished = true;
            else if (model.SearchPublishedId == 2)
                overridePublished = false;

            var products = _productService.SearchProducts(
                categoryIds: categoryIds,
                manufacturerId: model.SearchManufacturerId,
                storeId: model.SearchStoreId,
                //vendorId: model.SearchVendorId,
                warehouseId: model.SearchWarehouseId,
                productType: model.SearchProductTypeId > 0 ? (ProductType?)model.SearchProductTypeId : null,
                keywords: model.SearchProductName,
                pageIndex: command.Page - 1,
                pageSize: command.PageSize,
                showHidden: true,
                overridePublished: overridePublished
            );
            var gridModel = new DataSourceResult();

            gridModel.Data = products.Select(x =>
            {
                var productModel = new ModelsMapper().CreateMap<Product, ProducttModel>(x);
                //little hack here:
                //ensure that product full descriptions are not returned
                //otherwise, we can get the following error if products have too long descriptions:
                //"Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. "
                //also it improves performance
                
                var myStore = x.getStores().SingleOrDefault(s => s.Id == _workContext.CurrentVendor.getStore().Id);
                if (productModel.LimitedToStores && myStore != null)
                {
                    productModel.AddToMyStore = true;
                }
                else
                {
                    productModel.AddToMyStore = false;
                }

                //picture
                var defaultProductPicture = _pictureService.GetPicturesByProductId(x.Id, 1).FirstOrDefault();
                productModel.PictureThumbnailUrl = _pictureService.GetPictureUrl(defaultProductPicture, 75, true);
                    //product type
                    productModel.ProductTypeName = x.ProductType.GetLocalizedEnum(_localizationService, _workContext);
                    
                return productModel;
            });
            gridModel.Total = products.TotalCount;
            
            return Json(gridModel);
        }