示例#1
0
        public ActionResult ViewContent(int contentId)
        {
            var content = _entities.Contents
                          .FirstOrDefault(c => c.Id == contentId);

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

            var allNews = _entities.Contents
                          .Where(c => c.Type == ContentType.News)
                          .Where(c => c.Status == ContentStatus.Published)
                          .Where(c => c.Category.AreaName != "sfc") //TODO: Consider adding a Code Handle to the data class for this. Referring to the Name feels kinda hacky
                          .OrderByDescending(c => c.Published);

            // TODO: The LINQs here use .ToList() because otherwise MySQL would throw an exception, which I couldn't find a solution for.
            // [MySqlException (0x80004005): There is already an open DataReader associated with this Connection which must be closed first.]
            var model = new ContentViewModel
            {
                Content     = content,
                News        = allNews.Take(8).ToList(),
                RelatedNews = allNews
                              .Where(c => c.CategoryId == content.CategoryId)
                              .Take(8)
                              .ToList()
            };

            content.TrackView(Request, _entities);

            return(View("~/Views/Home/ViewContent.cshtml", model));
        }
示例#2
0
        public ActionResult New(string tabId, int parentId, int?groupId)
        {
            var content = ContentService.New(parentId, groupId);
            var model   = ContentViewModel.Create(content, tabId, parentId);

            return(JsonHtml("Properties", model));
        }
        //sobre cargamos el metodo AddContent para guardar pero le agregamos el modelo ContentViewModel
        public async Task <IActionResult> AddContent(ContentViewModel model)
        {
            if (!ModelState.IsValid)
            {
                if (model.ContentTypeId == 0)
                {
                    model.ContentTypes = _combosHelper.GetComboContentTypes();
                    model.Parks        = _combosHelper.GetComboParks();
                    return(View(model));
                }
                var path = string.Empty;

                if (model.ImageFile != null)
                {
                    //invocamos el metodo UploadImageAsync de IImageHelper
                    path = await _imageHelper.UploadImageAsync(model.ImageFile);
                }
                //creamos una instancia del objeto content y en el metodo ToContect nos devuelve el objeto Content
                //true porque es un nuevo contenido
                var content = await _converterHelper.ToContentAsync(model, path, true);

                _dataContext.Contents.Add(content);
                await _dataContext.SaveChangesAsync();

                return(RedirectToAction($"Details/{model.UserId}"));
            }
            model.ContentTypes = _combosHelper.GetComboContentTypes();
            model.Parks        = _combosHelper.GetComboParks();
            return(View(model));
        }
示例#4
0
        private Models.Content ConvertToModel(ContentViewModel content)
        {
            Content contentModel;

            if (content.ContentId != 0)
            {
                contentModel = db.Contents.Find(content.ContentId);
            }
            else
            {
                contentModel = new Content
                {
                    ContentId  = content.ContentId == 0 ? GetNewContentId() : content.ContentId,
                    CategoryId = content.SelectedCategoryId != null ? content.SelectedCategoryId : content.CategoryId,
                };
            }

            contentModel.Path          = content.Path;
            contentModel.CategoryId    = content.CategoryId;
            contentModel.Comments      = content.Comments;
            contentModel.Year          = content.Year;
            contentModel.Month         = content.Month;
            contentModel.ContentTypeId = content.ContentTypeId;
            contentModel.UploadDate    = DateTime.Now;

            return(contentModel);
        }
示例#5
0
        public ActionResult Detail(int id)
        {
            if (IsExpire)
            {
                return(RedirectToAction("SignIn", "Auth"));
            }

            var model = new ContentViewModel();

            //set user information
            model.Email       = Me.Email;
            model.DisplayName = Me.DisplayName;

            //set post
            using (var postRepo = new PostRepository())
            {
                model.Post = postRepo.FindById(id);
            }

            //set comments
            using (var commentRepo = new CommentRepository())
            {
                model.Comments = commentRepo.GetFindByPostId(model.Post.Id);
            }

            return(View(model));
        }
        //detalles del usuario tener encuenta la consulta a la bd
        public async Task <IActionResult> AddContent(string id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var user = await _dataContext.Users.FindAsync(id.ToString());

            if (user == null)
            {
                return(NotFound());
            }

            //var userInDB = await _userHelper.GetUserByEmailAsync(user.ToString());
            //instanciamos la clase ContentViewModel que creamos en la carpeta models, para el modelo del contenido
            var model = new ContentViewModel
            {
                Date   = DateTime.Now,
                UserId = user.Id,
                //creamos una clase ICombosHelps para poder traer la lista de ContentTypes
                ContentTypes = _combosHelper.GetComboContentTypes(),
                Parks        = _combosHelper.GetComboParks()
            };

            return(View(model));
        }
示例#7
0
        public async Task <JsonResult> GetCommunityContents(long communityId)
        {
            if (CurrentUserId == 0)
            {
                await TryAuthenticateFromHttpContext();
            }
            var contents = await _communityService.GetCommunityContents(communityId, CurrentUserId);

            var entities = new List <EntityViewModel>();

            foreach (var item in contents)
            {
                var contentViewModel = new ContentViewModel();
                contentViewModel.SetValuesFrom(item);
                entities.Add(contentViewModel);
            }
            var children = await _communityService.GetChildCommunities(communityId, CurrentUserId);

            var childCommunities = new List <CommunityViewModel>();

            foreach (var child in children)
            {
                var communityViewModel = new CommunityViewModel();
                Mapper.Map(child, communityViewModel);
                childCommunities.Add(communityViewModel);
            }
            return(Json(new{ entities, childCommunities }, JsonRequestBehavior.AllowGet));
        }
示例#8
0
        public ActionResult Create(ContentViewModel contentView)
        {
            if (ModelState.IsValid)
            {
                Content content = new Content();
                content.Name        = contentView.Name.Trim();
                content.MetaTitle   = contentView.MetaTitle;
                content.Image       = contentView.Image;
                content.Description = contentView.Description;
                content.Detail      = contentView.Detail;
                content.CategoryID  = contentView.CategoryID;
                content.Status      = contentView.Status;

                var contentDao  = new ContentDao();
                var categoryDao = new CategoryDao();

                long result = contentDao.Insert(content);
                if (result > 0)
                {
                    ShowNotify("Add successfully", "success");
                    return(RedirectToAction("Index", "Content"));
                }
                else if (result == -1)
                {
                    ShowNotify("This '" + categoryDao.GetByID(content.CategoryID).Name + "' category is locked", "error");
                }
                else
                {
                    ShowNotify("System error", "error");
                }
            }

            SetViewBagCategory(null, false);
            return(View("Create"));
        }
        /// <summary>
        /// Gets the entities for the given community.
        /// </summary>
        /// <param name="entityId">Entity Id (Community/Content)</param>
        /// <param name="entityType">Entity type (Community/Content)</param>
        /// <param name="pageDetails">Details about the pagination</param>
        /// <param name="onlyItemCount">To get only item count, not the entities. When community details page is loaded first time,
        /// no need to get the communities, only count is enough.</param>
        /// <returns>Collection of entities</returns>
        private List <EntityViewModel> GetCommunityEntities(long entityId, EntityType entityType, PageDetails pageDetails, bool onlyItemCount)
        {
            var entities = new List <EntityViewModel>();

            // Default value is 20 if the value is not specified or wrong in the configuration file.
            // Total pages will be set by the service.
            pageDetails.ItemsPerPage = Constants.HighlightEntitiesPerPage;

            // Do not hit the database if the entity is not valid. This will happen for private communities.
            if (entityId > 0)
            {
                if (entityType == EntityType.Community || entityType == EntityType.Folder)
                {
                    var subCommunities = _entityService.GetSubCommunities(entityId, CurrentUserId, pageDetails, onlyItemCount);
                    foreach (var item in subCommunities)
                    {
                        var subCommunityViewModel = new CommunityViewModel();
                        Mapper.Map(item, subCommunityViewModel);
                        entities.Add(subCommunityViewModel);
                    }
                }
                else
                {
                    var contents = _entityService.GetContents(entityId, CurrentUserId, pageDetails);
                    foreach (var item in contents)
                    {
                        var contentViewModel = new ContentViewModel();
                        contentViewModel.SetValuesFrom(item);
                        entities.Add(contentViewModel);
                    }
                }
            }

            return(entities);
        }
        public async Task <IActionResult> List(string url = null)
        {
            SpeedWagonContent contentRoot = await this._speedWagon.WebContentService.GetContent(url);

            IEnumerable <SpeedWagonContent> contents = await this._speedWagon.ContentService.Children(contentRoot);

            contents = contents.OrderBy(x => x.SortOrder);

            IEnumerable <SpeedWagonContent> contentTypes = null;


            if (string.IsNullOrEmpty(url) || url == "/content")
            {
                contentTypes = await this._speedWagon.ContentTypeService.ListRootTypes();
            }
            else
            {
                contentTypes = await this._speedWagon.ContentTypeService.ListAllowedChildren(contentRoot.Type);
            }

            IList <SelectListItem> contentTypeSelct = SelectListHelper.GetSelectList(contentTypes);

            ContentViewModel viewModel = new ContentViewModel();

            viewModel.AvailableContentTypes = contentTypeSelct;
            viewModel.Content        = contentRoot;
            viewModel.Contents       = contents;
            viewModel.ContentService = this._speedWagon.ContentService;

            return(View("~/Views/SpeedWagon/Content/List.cshtml", viewModel));
        }
示例#11
0
        /// <summary>
        /// It returns the entity list
        /// </summary>
        /// <param name="userId">User Id for whom page is rendered</param>
        /// <param name="entityType">Entity type (Community/Content)</param>
        /// <param name="pageDetails">Details about the pagination</param>
        /// <returns>List of entity objects</returns>
        private Task <List <EntityViewModel> > GetEntities(long userId, EntityType entityType, PageDetails pageDetails)
        {
            // TODO: Need to create a model for passing parameters to this controller
            var highlightEntities = new List <EntityViewModel>();

            if (entityType == EntityType.Community)
            {
                var communities = ProfileService.GetCommunities(userId, pageDetails, userId != CurrentUserId);
                foreach (var community in communities)
                {
                    var communityViewModel = new CommunityViewModel();
                    Mapper.Map(community, communityViewModel);
                    highlightEntities.Add(communityViewModel);
                }
            }
            else if (entityType == EntityType.Content)
            {
                var contents = ProfileService.GetContents(userId, pageDetails, userId != CurrentUserId);
                foreach (var content in contents)
                {
                    var contentViewModel = new ContentViewModel();
                    contentViewModel.SetValuesFrom(content);
                    highlightEntities.Add(contentViewModel);
                }
            }

            return(Task.FromResult(highlightEntities));
        }
示例#12
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            IUnityContainer container = new UnityContainer();

            var customXmlRW = new DataBase(@"C:\Users\stefan\Desktop\db.xml");

            // Register ViewModels
            var loginViewModel = new LoginViewModel(customXmlRW);

            container.RegisterInstance <LoginViewModel>(loginViewModel);
            var showImagesViewModel = new ImagesViewModel();

            container.RegisterType <ImagesViewModel>();
            var addImageViewModel = new AddImageViewModel();

            container.RegisterType <AddImageViewModel>();
            var accountDetailsViewModel = new AccountDetailsViewModel();

            container.RegisterType <AccountDetailsViewModel>();
            var contentViewModel = new ContentViewModel(container, customXmlRW);

            container.RegisterInstance <ContentViewModel>(contentViewModel);
            var mainWindowViewModel = new MainWindowViewModel(container);

            container.RegisterInstance <MainWindowViewModel>(mainWindowViewModel);

            var mainWindow = container.Resolve <MainWindow>();

            mainWindow.DataContext         = container.Resolve <MainWindowViewModel>();
            Application.Current.MainWindow = mainWindow;
            Application.Current.MainWindow.Show();
        }
示例#13
0
        public ContentView(int contentId)
        {
            InitializeComponent();

            this._viewModel  = new ContentViewModel(contentId);
            this.DataContext = this._viewModel;
        }
示例#14
0
        public ContentViewModel GetByID(long Id = 0)
        {
            var model = new ContentViewModel();

            try
            {
                if (Id > 0)
                {
                    using (db)
                    {
                        var config = new MapperConfiguration(cfg =>
                        {
                            cfg.CreateMap <v_Content, ContentViewModel>()
                            .ForMember(o => o.Detail, i => i.MapFrom(src => src.Detail))
                            ;
                        });
                        IMapper mapper = config.CreateMapper();
                        var     result = db.v_Content.FirstOrDefault(w => w.ID == Id);
                        model = mapper.Map <v_Content, ContentViewModel>(result);
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                string subject = "Error " + SiteSetting.SiteName + " at GetByID at ContentDao at Model.Model";
                string message = StringHelper.Parameters2ErrorString(ex, Id);
                MailHelper.SendMail(SiteSetting.EmailAdmin, subject, message);
            }
            return(model);
        }
示例#15
0
        public ActionResult New(string tabId, int parentId, string backendActionCode, FormCollection collection)
        {
            var content = ContentService.New(parentId, null);
            var model   = ContentViewModel.Create(content, tabId, parentId);

            TryUpdateModel(model);
            model.Validate(ModelState);
            if (ModelState.IsValid)
            {
                try
                {
                    model.Data = ContentService.Save(model.Data);
                    PersistResultId(model.Data.Id);
                    PersistFieldIds(model.Data.GetFieldIds());
                    PersistLinkIds(model.Data.GetLinkIds());
                }
                catch (VirtualContentProcessingException vcpe)
                {
                    if (HttpContext.IsXmlDbUpdateReplayAction())
                    {
                        throw;
                    }

                    ModelState.AddModelError("VirtualContentProcessingException", vcpe.Message);
                    return(JsonHtml("Properties", model));
                }

                return(Redirect("Properties", new { tabId, parentId, id = model.Data.Id, successfulActionCode = backendActionCode }));
            }

            return(JsonHtml("Properties", model));
        }
        //agregar contenido al contents
        public async Task <IActionResult> AddContent()
        {
            var user = await _dataContext.Users
                       .Include(ct => ct.Contents)
                       .FirstOrDefaultAsync(u => u.UserName.ToLower().Equals(User.Identity.Name.ToLower()));

            /*var content = await _dataContext.Contents
             *                  .Include(c => c.User)
             *                  .Include(ct => ct.ContentType)
             *                  .FirstOrDefaultAsync();*/
            if (user == null)
            {
                return(NotFound());
            }

            //instanciamos la clase ContentViewModel que creamos en la carpeta models, para el modelo del contenido
            var model = new ContentViewModel
            {
                Date   = DateTime.Now,
                UserId = user.Id,
                //Id = content.Id,
                //creamos una clase ICombosHelps para poder traer la lista de ContentTypes
                ContentTypes = _combosHelper.GetComboContentTypes(),
                Parks        = _combosHelper.GetComboParks()
            };

            return(View(model));
        }
示例#17
0
        public virtual async Task <IViewComponentResult> InvokeAsync(
            string entityType,
            string entityId)
        {
            var content = string.Empty;

            try
            {
                var contentDto = await contentAppService.GetAsync(new GetContentInput
                {
                    EntityId   = entityId,
                    EntityType = entityType
                });

                content = contentDto.Value;
            }
            catch (EntityNotFoundException e)
            {
                // ContentDto can be null, we will render empty content.
            }

            var viewModel = new ContentViewModel
            {
                Value = await contentRenderer.RenderAsync(content)
            };

            return(View("~/Pages/CmsKit/Shared/Components/Contents/Default.cshtml", viewModel));
        }
示例#18
0
        public ActionResult ForgotPasswordConfirmation()
        {
            var homePage = _contentLoader.Get <PageData>(ContentReference.StartPage) as HomePage;
            var model    = ContentViewModel.Create(homePage);

            return(View("ForgotPasswordConfirmation", model));
        }
示例#19
0
        public void OpenSubChildWnd()
        {
            var _MyChildW = new ContentViewModel();

            myWm.ShowWindow(_MyChildW);
            // MessageBox.Show(string.Format("Hello {0}!", tbInputName)); //Don't do this in real life :)
        }
示例#20
0
        public async Task <ActionResult> Manage(Guid?token, string EmailAddress)
        { // Unsubscribe or Renew
            if (!token.HasValue)
            {
                return(await Renew(EmailAddress));
            }
            var model = new ContentViewModel()
            {
                Title    = "Unsubscribed",
                Subtitle = ""
            };

            bool?validGuid = await Repository.ApiClient.Subscribe.CheckEmailActivationTokenAsync(token.Value, Repository.APIVersion);

            if (validGuid != true)
            {
                model.Html = new HtmlString(
                    "<p>This link has expired, or an error occurred</p>"
                    );
            }
            else
            {
                bool?success = await Repository.ApiClient.Subscribe.UnsubscribeSubscriberAsync(token.Value, Repository.APIVersion);

                model.Html = new HtmlString(
                    success == true ? "<p>You have unsubscribed from BC News On Demand.</p>" : "<p>An error occurred.</p>"
                    );
            }

            await LoadAsync(model);

            return(View("ContentView", model));
        }
示例#21
0
        public async Task <JsonResult> CommunityDetail(long?id)
        {
            if (CurrentUserId == 0)
            {
                await TryAuthenticateFromHttpContext(_communityService, _notificationService);
            }
            if (!id.HasValue)
            {
                return(new JsonResult {
                    Data = "error: invalid content id",
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                });
            }
            var contentDetail = _contentService.GetContentDetails(id.Value, CurrentUserId);

            var contentViewModel = new ContentViewModel();

            contentViewModel.SetValuesFrom(contentDetail);


            // It creates the prefix for id of links
            SetSiteAnalyticsPrefix(HighlightType.None);

            return(new JsonResult {
                Data = contentViewModel,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        /// <summary>
        /// Accessibility.
        /// </summary>
        //[Menu("Accessibility")]
        public ActionResult Accessibility()
        {
            PageTitle = "Accessibility";

            var model = new ContentViewModel()
                        .AddTitle("Accessibility")
                        .AddParagraph("The Australian Government is committed to improving on-line services to make them more accessible and usable for all people in our society.")
                        .AddSubTitle("System Accessibility")
                        .BeginParagraph()
                        .AddText("The system is being built to conform to ")
                        .AddExternalLink("http://www.w3.org/tr/wcag20/", "Web Content Accessibility Guidelines 2.0")
                        .AddText(" (WCAG 2) Level AA.")
                        .EndParagraph()
                        .AddParagraph("ESS Web relies on:")
                        .BeginUnorderedList()
                        .AddListItem("CSS3")
                        .AddListItem("HTML5")
                        .AddListItem("jQuery (JavaScript)")
                        .AddListItem("IE 9 Browser")
                        .EndUnorderedList()
                        .AddParagraph("The ESS Web system does not yet meet WCAG 2 Level AA. In particular there are accessibility issues with functionality that rely on jQuery.")
                        .AddParagraph("We remain focused on achieving conformance with WCAG 2 Level AA and are working to resolve these issues.")
                        .AddSubTitle("Contact Us")
                        .BeginParagraph()
                        .AddText("We welcome your feedback. If you identify any issues or have trouble using this system, please contact us. You can call our Help Desk on 1300 305 520 or send your comments by email to ")
                        .AddEmailLink("*****@*****.**")
                        .AddText(".")
                        .EndParagraph();

            model.Hidden = new[] { LayoutType.LeftHandNavigation, LayoutType.RequiredFieldsMessage };

            return(View(model));
        }
示例#23
0
        public void Initialize()
        {
            //_regionManager.RegisterViewWithRegion(RegionNames.LeftSidebarRegion,
            //									   () => this.container.Resolve<EmployeeListView>());


            //_regionManager.RegisterViewWithRegion(RegionNames.LeftSidebarRegion, typeof(SidebarItemView));

            IRegion sidebarRegion = _regionManager.Regions[RegionNames.LeftSidebarRegion];
            IRegion contentRegion = _regionManager.Regions[RegionNames.ContentRegion];

            var items = GetItems();

            foreach (var item in items)
            {
                var contentSidebarItemModel = new ContentSidebarItemModel(item.Item1, item.Item2, item.Item3);
                var contentSidebarItemView  = new ContentSidebarItemView(contentSidebarItemModel);
                sidebarRegion.Add(contentSidebarItemView, contentSidebarItemModel.Label);

                var contentViewModel = new ContentViewModel();
                var contentView      = new ContentView(contentViewModel);
                contentRegion.Add(contentView, contentSidebarItemModel.Label + "Content");

                contentSidebarItemModel.ItemSelected += (sender, url) =>
                {
                    Contract.Requires(!string.IsNullOrEmpty(url));

                    contentViewModel.Url = url;
                };
            }
        }
示例#24
0
        public IActionResult Create(ContentViewModel contentViewModel, bool continueEditing)
        {
            if (ModelState.IsValid)
            {
                var content = _mapper.Map <Content>(contentViewModel);

                _newsService.AddContent(content);
                if (content.Id > 0)
                {
                    _toastNotification.AddSuccessToastMessage("عملیات  با موفقیت صورت پذیرفت");


                    if (continueEditing)
                    {
                        return(RedirectToAction("Edit", new { contentId = content.Id }));
                    }

                    return(RedirectToAction("List"));
                }

                _toastNotification.AddErrorToastMessage("خطا در انجام عملیات");
            }

            return(RedirectToAction("List"));
        }
示例#25
0
        public int AddUpdateConttentData(HttpPostedFileBase file, ContentViewModel contentViewModel)
        {
            byte[] imageData = ConvertToBytes(file);
            if (contentViewModel.ID == 0)
            {
                var Content = new Content
                {
                    Name        = contentViewModel.Name,
                    BrandId     = contentViewModel.BrandId,
                    CategoryId  = contentViewModel.CategoryId,
                    price       = contentViewModel.price,
                    Review      = contentViewModel.Review,
                    Description = contentViewModel.Description,
                    Image       = imageData
                };
                db.Contents.Add(Content);
            }
            else
            {
                Content updateContent = (from c in db.Contents where c.ID == contentViewModel.ID select c).FirstOrDefault();
                updateContent.Name        = contentViewModel.Name; updateContent.price = contentViewModel.price;
                updateContent.Description = contentViewModel.Description; updateContent.price = contentViewModel.price;
                updateContent.Review      = contentViewModel.Review; updateContent.Image = imageData == null ? updateContent.Image : imageData;
            }
            int i = db.SaveChanges();

            if (i == 1)
            {
                return(1);
            }
            else
            {
                return(0);
            }
        }
        public async Task <ActionResult> CreateAsync(ContentViewModel viewModel, IFormFile fileUpload)
        {
            if (ModelState.IsValid)
            {
                if (fileUpload == null || fileUpload.Length == 0)
                {
                    return(Content("file not selected"));
                }

                var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", fileUpload.FileName);
                if (!System.IO.File.Exists(path))
                {
                    using (var stream = new FileStream(path, FileMode.Create))
                    {
                        await fileUpload.CopyToAsync(stream);
                    }
                }
                var content = _mapper.Map <ContentViewModel, Content>(viewModel);
                var user    = await _userManager.GetUserAsync(HttpContext.User);

                content.BannerUrl     = "/images/" + viewModel.BannerUrl;
                content.CreatedUserId = content.UpdatedUserId = user.UserId;
                content.PostStatus    = (int)Common.ContentStatus.Writed;
                if (_contentService.Insert(content, user.UserId, viewModel.Tag))
                {
                    return(RedirectToAction("WritedContents"));
                }
            }

            ModelState.AddModelError(string.Empty, Constants.UnknowErrorMessage);
            return(RedirectToAction("Create"));
        }
        public ActionResult Index()
        {
            var model = new ContentViewModel()
                        .AddTitle("Debug Cache");

            return(View(model));
        }
示例#28
0
        public ActionResult Properties(string tabId, int parentId, int id, string backendActionCode, FormCollection collection)
        {
            var content    = ContentService.ReadForUpdate(id);
            var model      = ContentViewModel.Create(content, tabId, parentId);
            var oldGroupId = model.Data.GroupId;

            TryUpdateModel(model);
            model.Validate(ModelState);
            if (ModelState.IsValid)
            {
                try
                {
                    model.Data = ContentService.Update(model.Data);
                }
                catch (VirtualContentProcessingException vcpe)
                {
                    if (HttpContext.IsXmlDbUpdateReplayAction())
                    {
                        throw;
                    }

                    ModelState.AddModelError("VirtualContentProcessingException", vcpe.Message);
                    return(JsonHtml("Properties", model));
                }

                return(Redirect("Properties", new { tabId, parentId, id = model.Data.Id, successfulActionCode = backendActionCode, groupChanged = oldGroupId != model.Data.GroupId }));
            }

            return(JsonHtml("Properties", model));
        }
示例#29
0
 private async Task ClosedAsync()
 {
     if (ContentViewModel != null)
     {
         await ContentViewModel.OnWindowClosedAsync();
     }
 }
示例#30
0
        /// <summary>
        /// get content by Id và trả về ContentViewModel
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public ContentViewModel GetContentById(long Id = 0)
        {
            var model  = new ContentViewModel();
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap <v_Content, ContentViewModel>();
            });
            IMapper mapper = config.CreateMapper();

            try
            {
                if (Id > 0)
                {
                    var result = entities.v_Content.FirstOrDefault(w => w.ID == Id);
                    model = mapper.Map <ContentViewModel>(result);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                string subject = "Error " + SiteSetting.SiteName + " at getContentById at ContentRepo at Model.Repository ";
                string message = StringHelper.Parameters2ErrorString(ex, Id);
                MailHelper.SendMail(SiteSetting.EmailAdmin, subject, message);
            }
            return(model);
        }
 private void SaveAs(ContentViewModel cvm)
 {
     if (cvm != null)
     {
         this.Header = "Save " + cvm.Title + " as...";
     }
     else
     { this.Header = "Save as..."; }
 }
 public IHttpActionResult Insert(ContentViewModel model)
 {
     try
     {
         return Ok(repo.Add(model));
     }
     catch (Exception ex)
     {
         return BadRequest(ex.Message);
     }
 }
示例#33
0
 public ShellViewModel()
 {
     MenuViewModel = new MenuViewModel();
        ContentViewModel = new ContentViewModel();
 }
示例#34
0
        public TestModule()
        {
            // Generates the post from Markdown
            Get["/post/{file}"] = x => View[(string) x.file];

            // Generates any static page given all site content
            Post["/static"] = x =>
            {
                var siteContent = new ContentViewModel
                {
                    GeneratedUrl = GeneratedUrl,
                    PostsInCategory = PostsInCategory,
                    Categories = Categories,
                    Posts = Posts,
                    PostsPaged = PostsPaged,
                    PostsGroupedByYearThenMonth = PostsGroupedByYearThenMonth,
                    HasPreviousPage = HasPreviousPage,
                    HasNextPage = HasNextPage,
                    NextPage = PageNumber + 1,
                    PreviousPage = PageNumber - 1,
                    MonthYearList = MonthYear,
                    GeneratedDate = GeneratedDate,
                    Category = Category
                };

                return View[StaticFile, siteContent];
            };

            // Generates an actual post based on the Markdown content
            // with a SiteContent property for access to everything
            Post["/compose"] = x =>
            {
                var result = new PostViewModel
                {
                    GeneratedUrl = GeneratedUrl,
                    PostContent = Data.Content,
                    PostDate = Data.Date,
                    Layout = Data.Layout,
                    Title = Data.Title,
                    GeneratedDate = GeneratedDate,
                    Url = Data.Url,
                    Categories = Data.Categories.Select(c => new Category {Name = c}).ToList(),
                    MonthYearList = MonthYear,
                    Author = Data.Author,
                    Email = Data.Email,
                    Settings = Settings,
                    Series = Data.Series,
                    MetaDescription = Data.MetaDescription
                };

                return View[result.Layout, result];
            };

            Post["/rss"] = x =>
            {
                return this.Response.AsRSS(PostsPaged, Settings.BlogTitle, Settings.SiteUrl, StaticFile);
            };

            Post["/sitemap"] = x =>
            {
                return this.Response.AsSiteMap(Posts, Settings.SiteUrl);
            };
        }
示例#35
0
        public TestModule()
        {
            // Generates any static page given all site content
            Post["/static"] = x =>
            {
                var siteContent = new ContentViewModel
                {
                    GeneratedUrl = GeneratedUrl,
                    PostsInCategory = PostsInCategory,
                    AllCategories = Categories,
                    Posts = Posts,
                    PostsPaged = PostsPaged,
                    Pages = Pages,
                    PostsGroupedByYearThenMonth = PostsGroupedByYearThenMonth,
                    HasPreviousPage = HasPreviousPage,
                    HasNextPage = HasNextPage,
                    NextPage = PageNumber + 1,
                    PreviousPage = PageNumber - 1,
                    MonthYearList = MonthYear,
                    GeneratedDate = GeneratedDate,
                    Category = Category,
                    Drafts = Drafts,
                    Published = Published
                };

                return View[StaticFile, siteContent];
            };

            // Generates an actual post based on the Markdown content
            // with a SiteContent property for access to everything
            Post["/compose"] = x =>
            {
                dynamic result = new PostViewModel
                {
                    Drafts = Drafts,
                    Posts = Posts,
                    Pages = Pages,
                    GeneratedUrl = GeneratedUrl,
                    PostContent = Data.Content,
                    PostDate = Data.Date,
                    Layout = Data.Layout,
                    Title = Data.Title,
                    GeneratedDate = GeneratedDate,
                    Url = Data.Url,
                    AllCategories = Categories,
                    Categories = Data.Categories.Select(c => new Category { Name = c }).ToList(),
                    Keywords = Data.Keywords,
                    MonthYearList = MonthYear,
                    Author = Data.Author,
                    Email = Data.Email,
                    Settings = Settings,
                    Series = Data.Series,
                    MetaDescription = Data.MetaDescription,
                    Published = Data.Published,
                    ContentExcerpt = Data.ContentExcerpt,
                };

                result.Banana = "WOW!";

                return View[result.Layout, result];
            };

            Post["/rss"] = x => Response.AsRSS(Posts.Take(Settings.FeedSize), Settings.BlogTitle, Settings.SiteUrl, StaticFile);

            Post["/atom"] = x => Response.AsAtom(Posts.Take(Settings.FeedSize), Settings.BlogTitle, Settings.SiteUrl, Settings.Author, Settings.Email, StaticFile);

            Post["/sitemap"] = x =>
            {
                var publishedPosts = Posts.Where(post => post.Published == Published.True);
                
                return Response.AsSiteMap(publishedPosts, Settings.SiteUrl);
            };
        }
示例#36
0
 private void HandleContentViewModelAdded(ContentViewModel contentViewModel)
 {
     _contentViewModels.Add(contentViewModel);
 }
        public ActionResult Create(ContentViewModel model)
        {
            string[] paths = null;
            try
            {
                model.uploaded_images = FileHelpers.RemoveNullImages(model.uploaded_images);

                if (FileHelpers.ValidImage(model.uploaded_images) == false)
                {
                    ModelState.AddModelError("uploaded_images", "Please choose either a GIF, JPG or PNG image.");
                }

                if (ModelState.IsValid)
                {
                    paths = FileHelpers.UploadImage(model.uploaded_images);

                    for(int i = 0; i < paths.Length; i++)
                    {
                        model.images.Add(new ImageViewModel()
                        {
                            path = paths[i],
                            date_updated = new DateTime(),
                            alt_text = model.alt_text[i]
                        });
                    }

                    model.created_by = UserHelpers.GetUser().id;
                    model.updated_by = UserHelpers.GetUser().id;

                    model.uploaded_images = null;

                    SetRequestURL(APIURL.CONTENT_INSERT, Method.POST);
                    request.AddBody(model);

                    var response = rest.Execute(request);

                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        SetMessage(Message.SuccessfulCreate(model.title), MESSAGE_TYPE.SUCCESS);
                        long _id = JsonConvert.DeserializeObject<long>(response.Content);
                        return RedirectToAction("Details", new { id = _id });
                    }
                    else
                    {
                        FileHelpers.DeleteFile(paths);
                        ModelState.AddModelError("", response.Content);
                    }
                }
            }
            catch (Exception ex)
            {
                FileHelpers.DeleteFile(paths);
                ModelState.AddModelError("", ex.Message);
            }

            model.uploaded_images = null;
            model.alt_text = null;

            string[] exclude = { Constants.CONTACT_US };
            SetRequestURL(APIURL.CONTENT_TYPE_LIST, Method.GET);
            request.AddParameter("exclude", exclude);

            var res = rest.Execute(request);

            if (res.StatusCode == HttpStatusCode.OK)
            {
                List<ContentTypeViewModel> types = JsonConvert.DeserializeObject<List<ContentTypeViewModel>>(res.Content);

                ViewBag.type_id = new SelectList(types, "id", "name");

                SetTitle("Create Content");
                return View(model);
            }
            else
            {
                SetTitle();
                return CustomMessage(res.Content);
            }
        }