Exemplo n.º 1
0
        private object CreateInstance()
        {
            if (HasPageModel)
            {
                // Since this is a PageModel, we need to activate it, and then run a handler method on the model.
                _pageModel = CacheEntry.ModelFactory(_pageContext);
                _pageContext.ViewData.Model = _pageModel;

                return(_pageModel);
            }
            else
            {
                // Since this is a Page without a PageModel, we need to create the Page before running a handler method.
                _viewContext = new ViewContext(
                    _pageContext,
                    NullView.Instance,
                    _pageContext.ViewData,
                    _tempDataFactory.GetTempData(_pageContext.HttpContext),
                    TextWriter.Null,
                    _htmlHelperOptions);
                _viewContext.ExecutingFilePath = _pageContext.ActionDescriptor.RelativePath;

                _page = (Page)CacheEntry.PageFactory(_pageContext, _viewContext);

                if (_actionDescriptor.ModelTypeInfo == _actionDescriptor.PageTypeInfo)
                {
                    _pageContext.ViewData.Model = _page;
                }

                return(_page);
            }
        }
Exemplo n.º 2
0
        protected override Task InvokeResultAsync(IActionResult result)
        {
            // We also have some special initialization we need to do for PageResult.
            if (result is PageResult pageResult)
            {
                // If we used a PageModel then the Page isn't initialized yet.
                if (_viewContext == null)
                {
                    _viewContext = new ViewContext(
                        _pageContext,
                        NullView.Instance,
                        _pageContext.ViewData,
                        _tempDataFactory.GetTempData(_pageContext.HttpContext),
                        TextWriter.Null,
                        _htmlHelperOptions);
                    _viewContext.ExecutingFilePath = _pageContext.ActionDescriptor.RelativePath;
                }

                if (_page == null)
                {
                    _page = (PageBase)CacheEntry.PageFactory(_pageContext, _viewContext);
                }
                pageResult.Page = _page;
                pageResult.ViewData = pageResult.ViewData ?? _pageContext.ViewData;
            }

            return base.InvokeResultAsync(result);
        }
Exemplo n.º 3
0
        public async Task <string> InvokeViewAsync(string viewName, object model, bool isPartial = true)
        {
            Guard.NotNull(viewName, nameof(viewName));

            var actionContext = GetActionContext();
            var view          = FindView(actionContext, viewName, isPartial);

            var viewData = new ViewDataDictionary(_metadataProvider, actionContext.ModelState)
            {
                Model = model
            };

            using var psb = StringBuilderPool.Instance.Get(out var sb);
            using (var output = new StringWriter(sb))
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    _tempDataFactory.GetTempData(actionContext.HttpContext),
                    output,
                    _mvcViewOptions.Value.HtmlHelperOptions
                    );

                await view.RenderAsync(viewContext);

                return(output.ToString());
            }
        }
Exemplo n.º 4
0
        protected virtual async Task <string> InvokeViewAsync(string viewName, ActionContext actionContext, ViewDataDictionary viewData, bool isPartial = true)
        {
            Guard.NotEmpty(viewName, nameof(viewName));
            Guard.NotNull(actionContext, nameof(actionContext));
            Guard.NotNull(viewData, nameof(viewData));

            var view = FindView(actionContext, viewName, isPartial);

            using var psb = StringBuilderPool.Instance.Get(out var sb);
            using (var output = new StringWriter(sb))
            {
                var viewContext = new ViewContext(
                    actionContext,
                    view,
                    viewData,
                    _tempDataFactory.GetTempData(actionContext.HttpContext),
                    output,
                    _mvcViewOptions.Value.HtmlHelperOptions
                    );

                await view.RenderAsync(viewContext);

                return(output.ToString());
            }
        }
 private static void SaveTempData(IActionResult result, ITempDataDictionaryFactory factory, HttpContext httpContext)
 {
     if (result is IKeepTempDataResult)
     {
         factory.GetTempData(httpContext).Keep();
     }
     factory.GetTempData(httpContext).Save();
 }
Exemplo n.º 6
0
        public void ClearState()
        {
            var httpContext = _httpContextAccessor.HttpContext;
            var tempData    = _tempDataDictionaryFactory.GetTempData(httpContext);

            tempData.Clear();
            _httpContextAccessor.HttpContext.Session.Clear();
            _httpContextAccessor.HttpContext.Response.Cookies.Delete("StateData");
        }
 public ModalNotification(IHttpContextAccessor httpContextAccessor)
 {
     this.httpContextAccessor = httpContextAccessor;
     httpContext = httpContextAccessor.HttpContext;
     factory     = httpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
     tempData    = factory.GetTempData(httpContext);
 }
Exemplo n.º 8
0
        public static IActionResult HandleError(MovieMindException e)
        {
            ITempDataDictionary tempData = _tempDataDictionaryFactory.GetTempData(_httpContextAccessor.HttpContext);

            tempData["ApiError"] = helper.LocalizeString(e.Message);

            if (e.MovieMindError.Status == "401")
            {
                return(new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Authentication" })));
            }
            ;

            var routeValue = new RouteValueDictionary(new { action = "Index", controller = "Home" });

            return(new RedirectToRouteResult(routeValue));
        }
        private bool CreateNotification(ExceptionContext context, out ITempDataDictionary tempData)
        {
            tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
            CreateNotification(NotificationHelpers.AlertType.Error, tempData, context.Exception.Message);

            return(!tempData.ContainsKey(NotificationHelpers.NotificationKey));
        }
Exemplo n.º 10
0
 public Flasher(ITempDataDictionaryFactory factory, IHttpContextAccessor contextAccessor)
 {
     if (contextAccessor?.HttpContext != null)
     {
         tempData = factory.GetTempData(contextAccessor.HttpContext);
     }
 }
Exemplo n.º 11
0
        public async Task Invoke(HttpContext context)
        {
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

            var ex = context.Features.Get <IExceptionHandlerFeature>()?.Error;

            if (ex == null)
            {
                return;
            }

            var error = new
            {
                message = ex.Message
            };


            ITempDataDictionaryFactory factory  = context.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
            ITempDataDictionary        tempData = factory.GetTempData(context);

            tempData["Error"] = ex.Message;

            context.Response.ContentType = "application/json";

            using (var writer = new StreamWriter(context.Response.Body))
            {
                new JsonSerializer().Serialize(writer, error);
                await writer.FlushAsync().ConfigureAwait(false);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Method for handling Exception. This method should Handle exception and complete request
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            var tempData = tempDataDictionaryFactory.GetTempData(context.HttpContext);
            // read exception message
            string message = context.Exception.Message;

            // handle Exception
            context.ExceptionHandled = true;
            // go to view to display error messages
            var result = new ViewResult();
            // defining VeiwDataDictionary for Controller/action/errormessage
            var ViewData = new ViewDataDictionary(metadataProvider, context.ModelState);

            ViewData["controller"]   = context.RouteData.Values["controller"].ToString();
            ViewData["action"]       = context.RouteData.Values["action"].ToString();
            ViewData["errormessage"] = message;
            result.TempData          = tempData;
            // ViewName
            result.ViewName = "CustomError";
            // ViewData
            result.ViewData = ViewData;
            //	result.TempData.Keep();
            // setting result in HttpResponse
            context.Result = result;
        }
Exemplo n.º 13
0
 public ClientNotification(IHttpContextAccessor httpContextAccessor)
 {
     _httpContextAccessor = httpContextAccessor;
     _httpContext         = _httpContextAccessor.HttpContext;
     _factory             = _httpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
     _tempData            = _factory.GetTempData(_httpContext);
 }
Exemplo n.º 14
0
        private void ExecuteTemplateRendering(TextWriter sw, IPublishedRequest request)
        {
            var httpContext = _httpContextAccessor.GetRequiredHttpContext();

            // isMainPage is set to true here to ensure ViewStart(s) found in the view hierarchy are rendered
            var viewResult = _viewEngine.GetView(null, $"~/Views/{request.GetTemplateAlias()}.cshtml", isMainPage: true);

            if (viewResult.Success == false)
            {
                throw new InvalidOperationException($"A view with the name {request.GetTemplateAlias()} could not be found");
            }

            var viewData = new ViewDataDictionary(_modelMetadataProvider, new ModelStateDictionary())
            {
                Model = request.PublishedContent
            };

            var writer      = new StringWriter();
            var viewContext = new ViewContext(
                new ActionContext(httpContext, httpContext.GetRouteData(), new ControllerActionDescriptor()),
                viewResult.View,
                viewData,
                _tempDataDictionaryFactory.GetTempData(httpContext),
                writer,
                new HtmlHelperOptions()
                );


            viewResult.View.RenderAsync(viewContext).GetAwaiter().GetResult();

            var output = writer.GetStringBuilder().ToString();

            sw.Write(output);
        }
Exemplo n.º 15
0
        public void OnException(ExceptionContext context)
        {
            if (context.Exception is ClinicException clinicException)
            {
                var tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);


                var controller    = context.ActionDescriptor.RouteValues.FirstOrDefault(x => x.Key == "controller");
                var errorMessages = new ResourceManager(typeof(ErrorCodes));
                var errorMessage  = errorMessages.GetString(clinicException.ErrorCode.ToString());

                if (!tempData.ContainsKey(NotificationMessageType.error.ToString()))
                {
                    tempData.Add(NotificationMessageType.error.ToString(), errorMessage);
                }
                else
                {
                    tempData[NotificationMessageType.error.ToString()] = errorMessage;
                }

                var routeDictionary = new RouteValueDictionary {
                    { "action", "Index" }, { "controller", controller.Value }
                };


                context.Result = new RedirectToRouteResult(routeDictionary);
            }
        }
 public MessageViewService(IHttpContextAccessor contextAccessor)
 {
     //_controller = New Con;
     _contextAccessor = contextAccessor;
     _factory         = _contextAccessor.HttpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
     _tempData        = _factory.GetTempData(_contextAccessor.HttpContext);
 }
Exemplo n.º 17
0
        private ITempDataDictionary GetTempData()
        {
            var httpContext = _contextAccessor.HttpContext;
            var tempData    = _tempDataDictionaryFactory.GetTempData(httpContext);

            return(tempData);
        }
Exemplo n.º 18
0
 public NotificationService(IHttpContextAccessor httpContextAccessor,
                            //ILogger logger,
                            ITempDataDictionaryFactory tempData)
 {
     _httpContext = httpContextAccessor.HttpContext;
     //_logger = logger;
     TempData = tempData.GetTempData(_httpContext);
 }
Exemplo n.º 19
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            ITempDataDictionary tempData = factory.GetTempData(context.HttpContext);

            if (!IsLogged(context.HttpContext, "You must be logged in to do this!", tempData))
            {
                context.Result = new RedirectToActionResult("Login", "Account", null);
            }
        }
        public override void ExecuteResult(ActionContext context)
        {
            ITempDataDictionaryFactory factory  = context.HttpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
            ITempDataDictionary        tempData = factory.GetTempData(context.HttpContext);

            tempData.SetViewModel(_jsonModel);
            tempData.SetViewModelProp(_contextProp);
            _innerResult.ExecuteResult(context);
        }
Exemplo n.º 21
0
        private ITempDataDictionary GetTempData()
        {
            if (_tempData == null)
            {
                _tempData = _tempaDataFactory.GetTempData(_contextAccessor.HttpContext);
            }

            return(_tempData);
        }
Exemplo n.º 22
0
        public async Task <ActionResult <UploadStartResponse> > BatchUploadAsync(
            [FromForm] UploadRequestForm model,
            CancellationToken token)
        {
            var tempDataProvider = _tempDataDictionaryFactory.GetTempData(HttpContext);
            var tempData         = tempDataProvider.Get <TempData>($"update-{model.SessionId}");

            if (tempData == null)
            {
                ModelState.AddModelError("error", "bad upload");
                return(BadRequest(ModelState));
            }
            var index = (int)(model.StartOffset / UploadInnerResponse.BlockSize);
            await BlobProvider.UploadBlockFileAsync(tempData.BlobName, model.Chunk.OpenReadStream(),
                                                    index, token);

            tempDataProvider.Put($"update-{model.SessionId}", tempData);
            return(new UploadStartResponse());
        }
Exemplo n.º 23
0
 public PageAdapter(
     IConfiguration configuration,
     IHttpContextAccessor httpContextAccessor,
     ITempDataDictionaryFactory tempDataDictionaryFactory)
 {
     _configuration             = configuration;
     _httpContextAccessor       = httpContextAccessor;
     _tempDataDictionaryFactory = tempDataDictionaryFactory;
     _httpContext = _httpContextAccessor.HttpContext;
     _tempData    = _tempDataDictionaryFactory.GetTempData(_httpContext);
 }
Exemplo n.º 24
0
        public void AddMessage(MessageType type, string message)
        {
            var httpContext = httpContextAccessor.HttpContext;
            var tempData    = tempDataDictionaryFactory.GetTempData(httpContext);

            tempData.Put("__Message", new MessageModel()
            {
                Type    = type,
                Message = message
            });
        }
Exemplo n.º 25
0
        public override void OnException(ExceptionContext context)
        {
            var exceptionType = context.Exception.GetType().Name;
            var message       = context.Exception.Message;
            var stackTrace    = context.Exception.StackTrace;

            var controllerName = string.Empty;
            var actionName     = string.Empty;
            var area           = string.Empty;
            var page           = string.Empty;

            var routeValues = context.RouteData.Values;

            if (routeValues.ContainsKey("controller"))
            {
                controllerName = routeValues["controller"].ToString();
                actionName     = routeValues["action"].ToString();
            }
            else if (routeValues.ContainsKey("area"))
            {
                area = routeValues["area"].ToString();
                page = routeValues["page"].ToString();
            }

            var user    = context.HttpContext.User.Identity.Name ?? GlobalConstants.AnonymousUser;
            var logTime = DateTime.UtcNow;

            var log = new DbExceptionLog
            {
                ExeptionType = exceptionType,
                Message      = message,
                StackTrace   = stackTrace,
                Area         = area,
                Page         = page,
                Controller   = controllerName,
                Action       = actionName,
                User         = user,
                LogTime      = logTime
            };

            this.dbContext.DbExceptionLogs.Add(log);
            this.dbContext.SaveChanges();

            var tempData = tempDataFactory.GetTempData(context.HttpContext);

            if (context.Exception is F1CafeBaseException)
            {
                tempData.Add(GlobalConstants.ErrorMessage, context.Exception.Message);
            }

            context.ExceptionHandled = true;

            context.Result = new RedirectResult(GlobalConstants.HomeErrorRoute);
        }
Exemplo n.º 26
0
        public void OnActionExecuted(ActionExecutedContext context)
        {
            var tempData = tempDataDictionaryFactory.GetTempData(context.HttpContext);

            if (tempData.ContainsKey(TempDataKey))
            {
                return;
            }

            tempData.Put(TempDataKey, notifier.Notifications);
        }
Exemplo n.º 27
0
        public void OnException(ExceptionContext context)
        {
            var tempData = tempDataFactory.GetTempData(context.HttpContext);

            if (context.Exception is HealthBlogBaseException)
            {
                tempData.Add("Message", context.Exception.Message);
            }

            context.Result = new RedirectResult("/Home/Error");
        }
Exemplo n.º 28
0
 public ViewContextGenerator(
     IRazorViewEngine viewEngine,
     IActionContextAccessor accessor,
     IModelMetadataProvider metadataProvider,
     ITempDataDictionaryFactory factory)
 {
     _viewEngine       = viewEngine;
     _metadataProvider = metadataProvider;
     _context          = accessor.ActionContext;
     _tempData         = factory.GetTempData(_context.HttpContext);
 }
        public async Task ExecuteAsync(ActionContext context, ViewComponentResult viewComponentResult)
        {
            var response = context.HttpContext.Response;

            var viewData = viewComponentResult.ViewData;

            if (viewData == null)
            {
                viewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState);
            }

            var tempData = viewComponentResult.TempData;

            if (tempData == null)
            {
                tempData = _tempDataDictionaryFactory.GetTempData(context.HttpContext);
            }

            string   resolvedContentType;
            Encoding resolvedContentTypeEncoding;

            ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
                viewComponentResult.ContentType,
                response.ContentType,
                ViewExecutor.DefaultContentType,
                out resolvedContentType,
                out resolvedContentTypeEncoding);

            response.ContentType = resolvedContentType;

            if (viewComponentResult.StatusCode != null)
            {
                response.StatusCode = viewComponentResult.StatusCode.Value;
            }

            using (var writer = new HttpResponseStreamWriter(response.Body, resolvedContentTypeEncoding))
            {
                var viewContext = new ViewContext(
                    context,
                    NullView.Instance,
                    viewData,
                    tempData,
                    writer,
                    _htmlHelperOptions);

                // IViewComponentHelper is stateful, we want to make sure to retrieve it every time we need it.
                var viewComponentHelper = context.HttpContext.RequestServices.GetRequiredService <IViewComponentHelper>();
                (viewComponentHelper as IViewContextAware)?.Contextualize(viewContext);

                var result = await GetViewComponentResult(viewComponentHelper, _logger, viewComponentResult);

                result.WriteTo(writer, _htmlEncoder);
            }
        }
Exemplo n.º 30
0
            public Task <bool> Handle(ThrowAlertCommand cmd, CancellationToken cancellationToken)
            {
                var httpContext = _httpContextAccessor.HttpContext;
                var tempData    = _tempDataDictionaryFactory.GetTempData(httpContext);

                tempData["_alert.type"]  = cmd.Type;
                tempData["_alert.title"] = cmd.Title;
                tempData["_alert.body"]  = cmd.Body;

                return(Task.FromResult(false));
            }
		/// <summary>
		///     Initialize a new service instance with required services.
		/// </summary>
		/// <param name="httpContextAccessor">The <see cref="IHttpContextAccessor" /> service.</param>
		/// <param name="tempDataFactory">The TempData dictionary factory in the context.</param>
		/// <param name="options">The <see cref="OperationMessageOptions" /> instance used to configure the accessor.</param>
		public DefaultOperationMessageAccessor(IHttpContextAccessor httpContextAccessor,
			ITempDataDictionaryFactory tempDataFactory, IOptions<OperationMessageOptions> options)
		{
			Options = options.Value;
			TempData = tempDataFactory.GetTempData(httpContextAccessor.HttpContext);
		}