Beispiel #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, CityInfoContext cityInfoContext)
        {
            //loggerFactory.AddConsole();

            //loggerFactory.AddDebug();
            loggerFactory.AddProvider(new NLog.Extensions.Logging.NLogLoggerProvider());
            //loggerFactory.AddNLog();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStatusCodePages();

            cityInfoContext.EnsureSeedDataForDB();
            AutoMapperExtensions.ConfigureAutomapper();
            app.UseMvc();


            app.Run(async(context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
Beispiel #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddMvc(options =>
            //{
            //    options.Filters.Add(typeof(ValidateModelStateAttribute));
            //}).AddJsonOptions(o => o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore)
            //    .ConfigureApiBehaviorOptions(options =>
            //    {
            //        options.SuppressMapClientErrors = true;
            //        options.SuppressModelStateInvalidFilter = true;
            //    });

            services.AddControllersWithViews();

            /*
             * Transient : Her istendiğinde oluşturulur.
             * Scoped    : istemci isteği (bağlantı) başına bir kez oluşturulur.
             * Singleton : Sonraki her istek aynı örneği kullanır.
             *
             *
             * dotnet tool install --global dotnet-ef --version 3.1.3
             * dotnet ef migrations remove
             * dotnet ef database update
             * dotnet ef migrations add InitialCreate
             */

            services.AddDbContext <DbContext, TodoContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddScoped <ITodoProvider, TodoProvider>();
            services.AddScoped <ITodoService, TodoService>();


            AutoMapperExtensions.Init(MappingConfiguration.InitializeAutoMapper().CreateMapper());
        }
Beispiel #3
0
        public PagedResult <MemberListItem> GetMembers(
            int pageNumber           = 1,
            int pageSize             = 100,
            string orderBy           = "email",
            Direction orderDirection = Direction.Ascending,
            string filter            = "")
        {
            if (pageNumber <= 0 || pageSize <= 0)
            {
                throw new NotSupportedException("Both pageNumber and pageSize must be greater than zero");
            }

            var queryString     = Request.GetQueryNameValuePairs();
            var memberTypeAlias = GetMemberType(queryString);
            var filters         = GetFilters(queryString);

            var members = MemberSearch.PerformMemberSearch(filter, filters, out int totalRecords,
                                                           memberTypeAlias, pageNumber, pageSize,
                                                           orderBy, orderDirection);

            if (totalRecords == 0)
            {
                return(new PagedResult <MemberListItem>(0, 0, 0));
            }

            var pagedResult = new PagedResult <MemberListItem>(totalRecords, pageNumber, pageSize)
            {
                Items = members
                        .Select(x => AutoMapperExtensions.MapWithUmbracoContext <SearchResult, MemberListItem>(x, UmbracoContext))
            };

            return(pagedResult);
        }
        public void RenderAutoMapperExtensionClass(bool useWebService)
        {
            _hdrUtil.WriteClassHeader(_output);

            _output.autoTabLn("using System.Collections.Generic;");
            _output.autoTabLn("");
            if (useWebService)
            {
                _output.autoTabLn("using " + _script.Settings.UI.UIWcfServiceNamespace + ";");
            }
            else
            {
                _output.autoTabLn("using " + _script.Settings.BusinessObjects.BusinessObjectsNamespace + ";");
            }
            _output.autoTabLn("");
            _output.autoTabLn("namespace " + _script.Settings.UI.UINamespace + ".Models");
            _output.autoTabLn("{");
            _output.tabLevel++;
            _output.autoTabLn("public static class MapperExtensions");
            _output.autoTabLn("{");
            _output.autoTabLn("");

            IMapperExtensions mapper = new AutoMapperExtensions(_context);

            mapper.Render();

            _output.autoTabLn("}");
            _output.tabLevel--;
            _output.autoTabLn("}	");

            _context.FileList.Add("    MapperExtensions.cs");
            SaveOutput(CreateFullPath(_script.Settings.UI.UINamespace + "\\Models", "_MapperExtensions.cs"), SaveActions.Overwrite);
        }
Beispiel #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="roleUpdateDto"></param>
        /// <returns></returns>
        public int UpdateRole(RoleUpdateDto roleUpdateDto)
        {
            TRoleUpdate roleUpdate = AutoMapperExtensions.MapTo <TRoleUpdate>(roleUpdateDto);

            if (string.IsNullOrEmpty(roleUpdate.JsonItem))
            {
                roleUpdate.JsonItem = "[]";
            }
            roleUpdate.UpdateTime = DateTime.Now;
            var SystemCode = IocUnity.Get <RepositoryRole>().GetSystemCode(roleUpdate.Id);

            if (!string.IsNullOrEmpty(roleUpdateDto.Code))
            {
                roleUpdate.OriginalCode = roleUpdateDto.Code;
                roleUpdate.Code         = $"{SystemCode}-{roleUpdate.OriginalCode}";
            }
            else
            {
                roleUpdate.Code = null;
            }

            int count = 0;

            IocUnity.Get <RepositoryRole>().DapperRepository.ExcuteTransaction(r =>
            {
                count = IocUnity.Get <RepositoryRole>().Update(roleUpdate);
                IocUnity.Get <RepositoryRole>().UpdateCode(roleUpdate.Id, roleUpdate.Code);
            });
            return(count);
        }
        /// <summary>
        /// 注册应用服务所需组件
        /// </summary>
        /// <param name="services"></param>
        /// <param name="builderAction"></param>
        public static void AddErechtheionServices(this IErechtheionBuilder builder)
        {
            AutoMapperExtensions.Initialize();

            builder.Services.AddTransient <ITopicAppService, TopicAppService>();
            builder.Services.AddTransient <IChannelAppService, ChannelAppService>();
        }
        public void AutoMapperConversionTest()
        {
            var config = AutoMapperExtensions.CreateConfig();
            var mapper = config.CreateMapper();

            var entityA = new TestEntityA {
                Id = 7, Name = "Testing...", ComplexProp = new TestEntityC {
                    Code = Guid.NewGuid(), Item = "Something", Value = 54.36m
                }
            };
            var entityB = mapper.Map <TestEntityB>(entityA);

            Assert.IsTrue(entityA?.Id == entityB?.Number);
            Assert.IsTrue(entityA?.Name == entityB?.Username);
            Assert.IsTrue(entityA?.ComplexProp.Code == entityB?.Code);
            Assert.IsTrue(entityA?.ComplexProp.Value == (decimal)entityB?.CodePrice);

            entityB = new TestEntityB {
                Number = 15, Username = "******", Code = Guid.NewGuid(), CodePrice = 45.66f
            };
            entityA = mapper.Map <TestEntityA>(entityB);

            Assert.IsTrue(entityA?.Id == entityB?.Number);
            Assert.IsTrue(entityA?.Name == entityB?.Username);
            Assert.IsTrue(entityA?.ComplexProp.Code == entityB?.Code);
            Assert.IsTrue(entityA?.ComplexProp.Value == (decimal)entityB?.CodePrice);
        }
        /// <summary>
        /// 更新系统信息
        /// </summary>
        /// <param name="systemUpdateDto"></param>
        /// <returns></returns>
        public int UpdateSystem(SystemUpdateDto systemUpdateDto)
        {
            TSystemUpdate system = AutoMapperExtensions.MapTo <TSystemUpdate>(systemUpdateDto);

            system.UpdateTime = DateTime.Now;
            return(IocUnity.Get <RepositorySystem>().Update(system));
        }
        public MemberDisplay GetEmpty(string contentTypeAlias = null)
        {
            IMember emptyContent;

            switch (MembershipScenario)
            {
            case MembershipScenario.NativeUmbraco:
                if (contentTypeAlias == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }

                var contentType = Services.MemberTypeService.Get(contentTypeAlias);
                if (contentType == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }

                var provider = Core.Security.MembershipProviderExtensions.GetMembersMembershipProvider();

                emptyContent = new Member(contentType);
                emptyContent.AdditionalData["NewPassword"] = Membership.GeneratePassword(provider.MinRequiredPasswordLength, provider.MinRequiredNonAlphanumericCharacters);
                return(AutoMapperExtensions.MapWithUmbracoContext <IMember, MemberDisplay>(emptyContent, UmbracoContext));

            case MembershipScenario.CustomProviderWithUmbracoLink:
            //TODO: Support editing custom properties for members with a custom membership provider here.

            case MembershipScenario.StandaloneCustomProvider:
            default:
                //we need to return a scaffold of a 'simple' member - basically just what a membership provider can edit
                emptyContent = MemberService.CreateGenericMembershipProviderMember("", "", "", "");
                emptyContent.AdditionalData["NewPassword"] = Membership.GeneratePassword(Membership.MinRequiredPasswordLength, Membership.MinRequiredNonAlphanumericCharacters);
                return(AutoMapperExtensions.MapWithUmbracoContext <IMember, MemberDisplay>(emptyContent, UmbracoContext));
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="groupUpdateDto"></param>
        /// <returns></returns>
        public int UpdatePrivilegeGroupUpdate(PrivilegeGroupUpdateDto groupUpdateDto)
        {
            TPrivilegeGroupUpdate privilegeGroup = AutoMapperExtensions.MapTo <TPrivilegeGroupUpdate>(groupUpdateDto);

            privilegeGroup.UpdateTime = DateTime.Now;
            return(IocUnity.Get <RepositoryPrivilegeGroup>().Update(privilegeGroup));
        }
Beispiel #11
0
        /// <summary>
        /// Generic method for getting all the rows in the table which will match the filter.
        /// </summary>
        /// <typeparam name="TInput">Object type of the input data.</typeparam>
        /// <typeparam name="TOuput">Object type of the output data.</typeparam>
        /// <param name="filter">A lambda expression that will filter the list.</param>
        /// <returns>List of the output object type.</returns>
        public List <TOuput> GetAll <TInput, TOuput>(Expression <Func <TInput, bool> > filter)
        {
            var where = AutoMapperExtensions.GetMappedSelector <TInput, TObject>(filter);
            var entity = _context.Set <TObject>().Where(where);
            var result = MappingConfiguration.MapObjectsList <TObject, TOuput>(entity.ToList());

            return(result);
        }
 protected override void RegisterInterfaces()
 {
     Container.RegisterType <IConfigurationManager, ConfigurationManager>(new InjectionConstructor("appsettings.json"));
     Container.RegisterType <IClementineRepository, ClementineNHibernateRepository>();
     Container.RegisterInstance(typeof(ILogger), Log4NetLogger.Instance);
     Container.RegisterType <IHashInfoHandler, HashInfoHandlerSFV>();
     Container.RegisterType <IHashCheck, HashCheckCRC>();
     Container.RegisterType <IManager, CollectionManager>();
     Container.RegisterFactory <IMapper>(f => AutoMapperExtensions.CreateConfig().CreateMapper(), new SingletonLifetimeManager());
 }
        public IEnumerable <ContentDTO> GetAll(Guid UserID)
        {
            List <GenreEntity>   Genres  = AutoMapperExtensions.MapList <GenreDTO, GenreEntity>(_GenreRepository.GetAll().ToList());
            List <PersonEntity>  Person  = AutoMapperExtensions.MapList <PersonDTO, PersonEntity>(_PersonRepository.GetAll().ToList());
            List <ContentEntity> Content = AutoMapperExtensions.MapList <ContentDTO, ContentEntity>(_ContentRepository.GetAll(UserID).ToList());

            ContentAggregate ContentAgg = new ContentAggregate(Content, Genres, Person);

            return(ContentAgg.GetContentList());
        }
        /// <summary>
        /// 使用已有模块添加权限
        /// </summary>
        /// <param name="privilegeAddDto"></param>
        /// <returns></returns>
        public int AddPrivilege(PrivilegeAddDto privilegeAddDto)
        {
            TPrivilege privilege = AutoMapperExtensions.MapTo <TPrivilege>(privilegeAddDto);

            privilege.OriginalCode = privilegeAddDto.Code;
            string SystemCode = IocUnity.Get <RepositoryPrivilegeGroup>().GetSystemCode(privilegeAddDto.GroupId);

            privilege.Code = $"{SystemCode}-{privilege.OriginalCode}";
            privilege.Id   = IdentityHelper.NewSequentialGuid().ToString("N");
            return(IocUnity.Get <RepositoryPrivilege>().Insert(privilege));
        }
        public ContentDTO GetByID(Guid ID, Guid UserID)
        {
            List <GenreEntity>  Genres  = AutoMapperExtensions.MapList <GenreDTO, GenreEntity>(_GenreRepository.GetByContentID(ID).ToList());
            List <PersonEntity> Person  = AutoMapperExtensions.MapList <PersonDTO, PersonEntity>(_PersonRepository.GetByContentID(ID).ToList());
            ContentEntity       Content = AutoMapperExtensions.MapObject <ContentDTO, ContentEntity>(_ContentRepository.GetByID(ID, UserID));

            Content.Video = _AwsVideoRepository.GetVideoUrl(Content.Video);
            ContentAggregate ContentAgg = new ContentAggregate(Content, Genres, Person);

            return(ContentAgg.GetContent());
        }
Beispiel #16
0
        public MediaItemDisplay GetById(Guid id)
        {
            var foundContent = GetObjectFromRequest(() => Services.MediaService.GetById(id));

            if (foundContent == null)
            {
                HandleContentNotFound(id);
                //HandleContentNotFound will throw an exception
                return(null);
            }
            return(AutoMapperExtensions.MapWithUmbracoContext <IMedia, MediaItemDisplay>(foundContent, UmbracoContext));
        }
Beispiel #17
0
        public MediaItemDisplay PostAddFolder(PostedFolder folder)
        {
            var intParentId = GetParentIdAsInt(folder.ParentId, validatePermissions: true);

            var mediaService = ApplicationContext.Services.MediaService;

            var f = mediaService.CreateMedia(folder.Name, intParentId, Constants.Conventions.MediaTypes.Folder);

            mediaService.Save(f, Security.CurrentUser.Id);

            return(AutoMapperExtensions.MapWithUmbracoContext <IMedia, MediaItemDisplay>(f, UmbracoContext));
        }
Beispiel #18
0
        /// <summary>
        /// Generic asynchronous method for getting a single row in the table which will match the filter.
        /// </summary>
        /// <typeparam name="TOuput">Object type of the output data.</typeparam>
        /// <param name="filter">A lambda expression that will filter the list.</param>
        /// <returns>Output object</returns>
        public async Task <TOuput> GetAsync <TInput, TOuput>(Expression <Func <TInput, bool> > filter)
        {
            var where = AutoMapperExtensions.GetMappedSelector <TInput, TObject>(filter);
            var entity = await _context.Set <TObject>().FirstOrDefaultAsync(where);

            var result = MappingConfiguration.MapObjects <TObject, TOuput>(entity);

            if (entity != null)
            {
                _context.Entry(entity).State = EntityState.Detached;
            }
            return(result);
        }
Beispiel #19
0
        public ActionResult List()
        {
            DataServiceMessage <IEnumerable <CategoryListDTO> > serviceMessage = service.GetAll();

            if (serviceMessage.Succeeded)
            {
                IEnumerable <CategoryListViewModel> model = AutoMapperExtensions.Map <CategoryListDTO, CategoryListViewModel>(serviceMessage.Data);
                return(ActionResultDependingOnGetRequest(model));
            }
            else
            {
                return(Error(serviceMessage.Errors));
            }
        }
        public ActionResult ListAuthors()
        {
            DataServiceMessage <IEnumerable <ArticleAuthorListDTO> > serviceMessage = articleService.GetAllWithAuthors();

            if (serviceMessage.Succeeded)
            {
                IEnumerable <ArticleAuthorListViewModel> model = AutoMapperExtensions.Map <ArticleAuthorListDTO, ArticleAuthorListViewModel>(serviceMessage.Data);
                return(ActionResultDependingOnGetRequest(model));
            }
            else
            {
                return(Error(serviceMessage.Errors));
            }
        }
        /// <summary>
        /// 更新权限
        /// </summary>
        /// <param name="privilegeUpdateDto"></param>
        /// <returns></returns>
        public int UpdatePrivilege(PrivilegeUpdateDto privilegeUpdateDto)
        {
            TPrivilegeUpdate update = AutoMapperExtensions.MapTo <TPrivilegeUpdate>(privilegeUpdateDto);

            update.OriginalCode = privilegeUpdateDto.Code;
            string SystemCode = IocUnity.Get <RepositoryPrivilege>().GetSystemCode(privilegeUpdateDto.Id);

            update.Code = $"{SystemCode}-{update.OriginalCode}";
            int count = 0;

            IocUnity.Get <RepositoryPrivilege>().DapperRepository.ExcuteTransaction(tranc => {
                count = IocUnity.Get <RepositoryPrivilege>().Update(update);
                IocUnity.Get <RepositoryPrivilege>().UpdateCode(update.Id, update.Code);
            });
            return(count);
        }
        public ActionResult List()
        {
            DataServiceMessage <IEnumerable <BanReasonListDTO> > serviceMessage = GetBanReasons(false);

            if (serviceMessage.Succeeded)
            {
                IEnumerable <BanReasonListViewModel> model = AutoMapperExtensions.Map <BanReasonListDTO, BanReasonListViewModel>(serviceMessage.Data);
                return(ActionResultDependingOnGetRequest(model));
            }
            else
            {
                return(Request.IsAjaxRequest()
                    ? Error(serviceMessage.Errors)
                    : Error(serviceMessage.Errors));
            }
        }
        public MemberDisplay GetByKey(Guid key)
        {
            MembershipUser foundMembershipMember;
            MemberDisplay  display;
            IMember        foundMember;

            switch (MembershipScenario)
            {
            case MembershipScenario.NativeUmbraco:
                foundMember = Services.MemberService.GetByKey(key);
                if (foundMember == null)
                {
                    HandleContentNotFound(key);
                }
                return(AutoMapperExtensions.MapWithUmbracoContext <IMember, MemberDisplay>(foundMember, UmbracoContext));

            case MembershipScenario.CustomProviderWithUmbracoLink:

            //TODO: Support editing custom properties for members with a custom membership provider here.

            //foundMember = Services.MemberService.GetByKey(key);
            //if (foundMember == null)
            //{
            //    HandleContentNotFound(key);
            //}
            //foundMembershipMember = Membership.GetUser(key, false);
            //if (foundMembershipMember == null)
            //{
            //    HandleContentNotFound(key);
            //}

            //display = Mapper.Map<MembershipUser, MemberDisplay>(foundMembershipMember);
            ////map the name over
            //display.Name = foundMember.Name;
            //return display;

            case MembershipScenario.StandaloneCustomProvider:
            default:
                foundMembershipMember = _provider.GetUser(key, false);
                if (foundMembershipMember == null)
                {
                    HandleContentNotFound(key);
                }
                display = Mapper.Map <MembershipUser, MemberDisplay>(foundMembershipMember);
                return(display);
            }
        }
Beispiel #24
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }


            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseAuthentication();

            app.UseExceptionHandler(new ExceptionHandlerOptions
            {
                ExceptionHandler = new JsonExceptionMiddleware().Invoke
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "Content")),
                RequestPath = "/content"
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";
            });

            AutoMapperExtensions.Configure();
        }
Beispiel #25
0
        public MediaItemDisplay GetEmpty(string contentTypeAlias, int parentId)
        {
            var contentType = Services.ContentTypeService.GetMediaType(contentTypeAlias);

            if (contentType == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var emptyContent = Services.MediaService.CreateMedia("", parentId, contentType.Alias, UmbracoUser.Id);
            var mapped       = AutoMapperExtensions.MapWithUmbracoContext <IMedia, MediaItemDisplay>(emptyContent, UmbracoContext);

            //remove this tab if it exists: umbContainerView
            var containerTab = mapped.Tabs.FirstOrDefault(x => x.Alias == Constants.Conventions.PropertyGroups.ListViewGroupName);

            mapped.Tabs = mapped.Tabs.Except(new[] { containerTab });
            return(mapped);
        }
        public ActionResult List(int?pageNumber, string categoryName)
        {
            int currentPage = pageNumber ?? 1;
            DataServiceMessage <IEnumerable <ArticleListDTO> > serviceMessage = GetArticles(currentPage, ItemsPerPage, categoryName);

            if (serviceMessage.Succeeded)
            {
                ArticleOfCategoryListViewModel model = new ArticleOfCategoryListViewModel
                {
                    Articles     = AutoMapperExtensions.Map <ArticleListDTO, ArticleListViewModel>(serviceMessage.Data),
                    CategoryName = categoryName,
                    PagesCount   = GetPagesCount(ItemsPerPage, categoryName),
                    CurrentPage  = currentPage
                };

                return(ActionResultDependingOnGetRequest(model));
            }
            else
            {
                return(Error(serviceMessage.Errors));
            }
        }
        public PagedResult <MemberBasic> GetPagedResults(
            int pageNumber           = 1,
            int pageSize             = 100,
            string orderBy           = "username",
            Direction orderDirection = Direction.Ascending,
            bool orderBySystemField  = true,
            string filter            = "",
            string memberTypeAlias   = null)
        {
            if (pageNumber <= 0 || pageSize <= 0)
            {
                throw new NotSupportedException("Both pageNumber and pageSize must be greater than zero");
            }

            if (MembershipScenario == MembershipScenario.NativeUmbraco)
            {
                var members = Services.MemberService
                              .GetAll((pageNumber - 1), pageSize, out var totalRecords, orderBy, orderDirection, orderBySystemField, memberTypeAlias, filter).ToArray();
                if (totalRecords == 0)
                {
                    return(new PagedResult <MemberBasic>(0, 0, 0));
                }

                var pagedResult = new PagedResult <MemberBasic>(totalRecords, pageNumber, pageSize)
                {
                    Items = members
                            .Select(x => AutoMapperExtensions.MapWithUmbracoContext <IMember, MemberBasic>(x, UmbracoContext))
                };
                return(pagedResult);
            }
            else
            {
                int totalRecords;

                MembershipUserCollection members;
                if (filter.IsNullOrWhiteSpace())
                {
                    members = _provider.GetAllUsers((pageNumber - 1), pageSize, out totalRecords);
                }
                else
                {
                    //we need to search!

                    //try by name first
                    members = _provider.FindUsersByName(filter, (pageNumber - 1), pageSize, out totalRecords);
                    if (totalRecords == 0)
                    {
                        //try by email then
                        members = _provider.FindUsersByEmail(filter, (pageNumber - 1), pageSize, out totalRecords);
                    }
                }
                if (totalRecords == 0)
                {
                    return(new PagedResult <MemberBasic>(0, 0, 0));
                }

                var pagedResult = new PagedResult <MemberBasic>(totalRecords, pageNumber, pageSize)
                {
                    Items = members
                            .Cast <MembershipUser>()
                            .Select(Mapper.Map <MembershipUser, MemberBasic>)
                };
                return(pagedResult);
            }
        }
        /// <summary>
        /// 获取所有系统信息
        /// </summary>
        /// <returns></returns>
        public IList <SystemDto> GetSystemInfoAll()
        {
            var systems = IocUnity.Get <RepositorySystem>().GetAll();

            return(AutoMapperExtensions.MapTo <SystemDto>(systems));
        }
Beispiel #29
0
        public MediaItemDisplay PostSave(
            [ModelBinder(typeof(MediaItemBinder))]
            MediaItemSave contentItem)
        {
            //If we've reached here it means:
            // * Our model has been bound
            // * and validated
            // * any file attachments have been saved to their temporary location for us to use
            // * we have a reference to the DTO object and the persisted object
            // * Permissions are valid

            MapPropertyValues(contentItem);

            //We need to manually check the validation results here because:
            // * We still need to save the entity even if there are validation value errors
            // * Depending on if the entity is new, and if there are non property validation errors (i.e. the name is null)
            //      then we cannot continue saving, we can only display errors
            // * If there are validation errors and they were attempting to publish, we can only save, NOT publish and display
            //      a message indicating this
            if (ModelState.IsValid == false)
            {
                if (ValidationHelper.ModelHasRequiredForPersistenceErrors(contentItem) &&
                    (contentItem.Action == ContentSaveAction.SaveNew))
                {
                    //ok, so the absolute mandatory data is invalid and it's new, we cannot actually continue!
                    // add the modelstate to the outgoing object and throw validation response
                    var forDisplay = AutoMapperExtensions.MapWithUmbracoContext <IMedia, MediaItemDisplay>(contentItem.PersistedContent, UmbracoContext);
                    forDisplay.Errors = ModelState.ToErrorDictionary();
                    throw new HttpResponseException(Request.CreateValidationErrorResponse(forDisplay));
                }
            }

            //save the item
            var saveStatus = Services.MediaService.WithResult().Save(contentItem.PersistedContent, (int)Security.CurrentUser.Id);

            //return the updated model
            var display = AutoMapperExtensions.MapWithUmbracoContext <IMedia, MediaItemDisplay>(contentItem.PersistedContent, UmbracoContext);

            //lasty, if it is not valid, add the modelstate to the outgoing object and throw a 403
            HandleInvalidModelState(display);

            //put the correct msgs in
            switch (contentItem.Action)
            {
            case ContentSaveAction.Save:
            case ContentSaveAction.SaveNew:
                if (saveStatus.Success)
                {
                    display.AddSuccessNotification(
                        Services.TextService.Localize("speechBubbles/editMediaSaved"),
                        Services.TextService.Localize("speechBubbles/editMediaSavedText"));
                }
                else
                {
                    AddCancelMessage(display);

                    //If the item is new and the operation was cancelled, we need to return a different
                    // status code so the UI can handle it since it won't be able to redirect since there
                    // is no Id to redirect to!
                    if (saveStatus.Result.StatusType == OperationStatusType.FailedCancelledByEvent && IsCreatingAction(contentItem.Action))
                    {
                        throw new HttpResponseException(Request.CreateValidationErrorResponse(display));
                    }
                }

                break;
            }

            return(display);
        }
Beispiel #30
0
        public IEnumerable <MediaItemDisplay> GetByIds([FromUri] int[] ids)
        {
            var foundMedia = Services.MediaService.GetByIds(ids);

            return(foundMedia.Select(media => AutoMapperExtensions.MapWithUmbracoContext <IMedia, MediaItemDisplay>(media, UmbracoContext)));
        }