public IEnumerable<ICoroutineResult> Render(string itemPath, DateTime lastModification, MemoryStream source, IHttpContext context, object model, ModelStateDictionary modelStateDictionary, object viewBag) { if (_cacheEngine != null) { StreamResult streamResult = null; yield return _cacheEngine.Get( itemPath, (a) => { streamResult = (StreamResult)a; }, RAZOR_CACHE_ID); if (streamResult == null || streamResult.LastModification < lastModification) { yield return _cacheEngine.AddOrUpdateAndGet(new CacheDefinition { Id = itemPath, LoadData = () => RunAsTask(itemPath, source, lastModification, model), ExpireAfter = TimeSpan.FromSeconds(60) }, (a) => { streamResult = (StreamResult)a; }, RAZOR_CACHE_ID); } } else { yield return CoroutineResult.RunTask(Task.Run(() => LoadTransformedBytes(itemPath, source, model))) .WithTimeout(TimeSpan.FromSeconds(60)) .AndWait(); } context.Response.ContentType = MimeHelper.HTML_MIME; var newSoure = new MemoryStream(); foreach (ICoroutineResult result in _renderer.GenerateOutputString(model, itemPath, context, modelStateDictionary, viewBag)) { if (result.ResultType == ResultType.YieldReturn || result.ResultType == ResultType.Return) { var bytes = (byte[]) result.Result; newSoure.Write(bytes, 0, bytes.Length); } else { yield return result; } } newSoure.Seek(0, SeekOrigin.Begin); var target = context.Response.OutputStream; yield return CoroutineResult.RunTask(newSoure.CopyToAsync(target), string.Format("RazorRenderer::CopyStream '{0}'", context.Request.Url)) .AndWait(); }
public ExecuteRequestCoroutine(string virtualDir, IHttpContext context, object model, ModelStateDictionary modelStateDictionary, List<IPathProvider> pathProviders, List<IRenderer> renderers, List<string> defaulList, object viewBag) { _context = context; _model = model; _modelStateDictionary = modelStateDictionary; _virtualDir = virtualDir; _pathProviders = pathProviders; _renderers = renderers; _defaulList = defaulList; _viewBag = viewBag; }
public RenderizableItemCoroutine(IRenderer renderer, string relativePath, IPathProvider pathProvider, IHttpContext context, Func<Exception, IHttpContext, bool> specialHandler, object model, ModelStateDictionary modelStateDictionary, object viewBag) { InstanceName = "RenderItem(" + renderer.GetType().Namespace + "." + renderer.GetType().Name + "," + relativePath + ")"; _renderer = renderer; _relativePath = relativePath; _pathProvider = pathProvider; _context = context; _specialHandler = specialHandler; _model = model; _modelStateDictionary = modelStateDictionary; _viewBag = viewBag; }
public IEnumerable<ICoroutineResult> Render(string itemPath, DateTime lastModification, MemoryStream source, IHttpContext context, object model, ModelStateDictionary modelStateDictionary, object viewBag) { var bytes = new byte[] { }; if (_cacheEngine != null) { StreamResult streamResult = null; yield return _cacheEngine.Get( itemPath, (a) => { streamResult = (StreamResult)a; }, MARKDOWN_CACHE_ID); if (streamResult == null || streamResult.LastModification < lastModification) { yield return _cacheEngine.AddOrUpdateAndGet(new CacheDefinition { Id = itemPath, LoadData = () => LoadTransformedBytes(itemPath, source, lastModification), ExpireAfter = TimeSpan.FromSeconds(60) }, (a) => { streamResult = (StreamResult)a; }, MARKDOWN_CACHE_ID); } bytes = streamResult.Result; } else { yield return CoroutineResult.RunAndGetResult(LoadTransformedBytes(itemPath, source, lastModification)) .OnComplete((a) => { // ReSharper disable once SuspiciousTypeConversion.Global //bytes = ((StreamResult)a).Result; bytes = ((StreamResult)a.Result).Result; }) .WithTimeout(TimeSpan.FromSeconds(60)) .AndWait(); } context.Response.ContentType = MimeHelper.HTML_MIME; var newSoure = new MemoryStream(bytes); var target = context.Response.OutputStream; yield return CoroutineResult.RunTask(newSoure.CopyToAsync(target), string.Format("MarkdownRenderer::CopyStream '{0}'", context.Request.Url)) .AndWait(); }
private bool TryInvoke(MethodWrapperDescriptor method, Dictionary<string, object> allParams, ClassWrapper.ClassWrapper controllerWrapper, bool hasConverter, IHttpContext context, bool isChildRequest, out object methResult) { try { var request = context.Request; var parsValues = new List<object>(); methResult = null; var methPars = method.Parameters.ToList(); for (int index = 0; index < methPars.Count; index++) { bool parValueSet = false; var par = methPars[index]; object valueToAdd = null; if (allParams.ContainsKey(par.Name)) { var parValue = allParams[par.Name]; if (parValue.GetType() != par.ParameterType) { object convertedValue; if (UniversalTypeConverter.TryConvert(parValue, par.ParameterType, out convertedValue)) { valueToAdd = convertedValue; parValueSet = true; } else if (!par.HasDefault) { if (par.ParameterType.IsValueType) { return false; } parValueSet = true; } } else { valueToAdd = parValue; parValueSet = true; } } if (par.ParameterType == typeof(FormCollection)) { parValueSet = true; valueToAdd = new FormCollection(context.Request.Form); } if (parValueSet == false && request.ContentType != null) { var parType = par.ParameterType; if (!parType.IsValueType && !parType.IsArray && !(parType == typeof(string)) && !parType.IsEnum && !(parType == typeof(object))) { try { valueToAdd = _conversionService.Convert(parType, request.ContentType, request); parValueSet = true; } catch (Exception) { } } } if (par.HasDefault && !parValueSet) { parValueSet = true; valueToAdd = par.Default; } if (!parValueSet && string.Compare(par.Name, "returnUrl", StringComparison.OrdinalIgnoreCase) == 0) { if (request.UrlReferrer != null) { parValueSet = true; valueToAdd = request.UrlReferrer.ToString(); } } if (!par.GetType().IsValueType && !parValueSet) { parValueSet = true; valueToAdd = null; } if (!parValueSet) return false; parsValues.Add(valueToAdd); } var attributes = new List<Attribute>(method.Attributes); foreach (var attribute in attributes) { var filter = attribute as IFilter; if (filter != null) { if (!filter.OnPreExecute(context)) { methResult = NullResponse.Instance; return true; } } else if (attribute is ChildActionOnly && !isChildRequest) { throw new HttpException(404, string.Format("Url '{0}' not found.", _context.Request.Url)); } } var msd = new ModelStateDictionary(); foreach (var par in parsValues) { if (ValidationService.CanValidate(par)) { var validationResult = ValidationService.ValidateModel(par); foreach (var singleResult in validationResult) { msd.AddModelError(singleResult.Property, singleResult.Message); } } } controllerWrapper.Set("ModelState", msd); var result = controllerWrapper.TryInvoke(method, out methResult, parsValues.ToArray()); if (result) { foreach (var attribute in attributes) { var filter = attribute as IFilter; if (filter != null) { filter.OnPostExecute(context); } } } return result; } catch (Exception) { Log.Info("Not found suitable action for method '{0}'.", method.Name); methResult = null; return false; } }
public IEnumerable<ICoroutineResult> GenerateOutputString(object model, string templateName, IHttpContext context, ModelStateDictionary modelStateDictionary, object viewBag) { foreach (var item in GenerateOutput(model, templateName, context, modelStateDictionary, viewBag)) { yield return item; } }
private void InjectData(RazorTemplateBase template, Type type, IHttpContext context, ModelStateDictionary modelStateDictionary, object viewBag) { string layout = null; var routeHandler = ServiceLocator.Locator.Resolve<IRoutingHandler>(); var bundlesHandler = ServiceLocator.Locator.Resolve<IResourceBundles>(true); var properties = type.GetProperties(); var model = properties.FirstOrDefault(p => p.Name == "Model"); var ga = type.GetGenericArguments(); if (ga.Length == 0) { ga = new[] { model != null ? model.PropertyType : typeof(object) }; } foreach (var property in type.GetProperties()) { if (!property.CanWrite) continue; switch (property.Name) { case ("Styles"): if (bundlesHandler != null) { property.SetValue(template, bundlesHandler.GetStyles()); } break; case ("Scripts"): if (bundlesHandler != null) { property.SetValue(template, bundlesHandler.GetScripts()); } break; case ("Html"): var urlHelper = typeof(HtmlHelper<>).MakeGenericType(ga); //public HtmlHelper(IHttpContext context, ViewContext viewContext, // object nodeCsTemplateBase, string localPath, dynamic viewBag,IRoutingHandler routingHandler) property.SetValue(template, Activator.CreateInstance(urlHelper, new object[] { context,new ViewContext(context,template,modelStateDictionary), template,context==null?string.Empty:context.Request.Url.ToString(),new ExpandoObject(),routeHandler } )); break; case ("Url"): property.SetValue(template, new UrlHelper(context, routeHandler)); break; case ("Context"): property.SetValue(template, context); break; case ("ViewBag"): property.SetValue(template, viewBag ?? new ExpandoObject()); break; default: var value = ServiceLocator.Locator.Resolve(property.PropertyType, true); if (value != null) { property.SetValue(template, value); } break; } } }
public IEnumerable<ICoroutineResult> GenerateOutput(object model, string templateName, IHttpContext context, ModelStateDictionary modelStateDictionary, object viewBagPassed) { var viewBag = viewBagPassed as dynamic; if (templateName == null) throw new ArgumentNullException("templateName"); RazorTemplateEntry entry = null; try { entry = _templateItems[templateName]; } catch (KeyNotFoundException) { throw new ArgumentOutOfRangeException("No template has been registered under this model or name."); } var templateItem = _templateItems[templateName]; if (templateItem.TemplateType == null) { lock (_locker) { templateItem.TemplateType = AssembliesManager.LoadType("Http.Renderer.Razor.Integration." + entry.TemplateName + "Template"); } } var type = templateItem.TemplateType; var template = (RazorTemplateBase)Activator.CreateInstance(type); InjectData(template, type, context, modelStateDictionary, viewBag); template.ObjectModel = model; template.Execute(); var layout = template.Layout; if (!string.IsNullOrWhiteSpace(layout)) { var sb = new StringBuilder(); foreach (var item in template.Buffer) { sb.Append(item.Value); } viewBag.ChildItem = sb.ToString(); foreach (var item in RenderLayout(layout, context, viewBag)) { yield return item; } } else { foreach (var item in template.Buffer) { var bytes = Encoding.UTF8.GetBytes(item.Value.ToString()); yield return CoroutineResult.YieldReturn(bytes); } } }
/// <summary> /// This Execute request /// </summary> /// <param name="context"></param> /// <param name="model"></param> /// <param name="modelStateDictionary"></param> /// <param name="o"></param> public ICoroutineResult ExecuteRequestInternal(IHttpContext context, object model, ModelStateDictionary modelStateDictionary, object viewBag) { var executeRequestCoroutine = SetupInternalRequestCoroutine(context, model, viewBag); return CoroutineResult.RunCoroutine(executeRequestCoroutine) .WithTimeout(TimeSpan.FromSeconds(60)) .AndWait(); }
public ViewContext(IHttpContext context, IRazorTemplate template, ModelStateDictionary modelState) { _context = context; _template = template; ModelState = modelState; }