Umbraco Cannot render a macro when there is no current PublishedContentRequest - c#

Hope you can help me.I encountered that error upon calling a view from my umbraco razor page using RenderMvcController. It's seems it can't render my created macro inside a layout page.
Line 4: }
Line 5:
Line 6: #Umbraco.RenderMacro("ExternalRedirect")
Line 7:
Line 8:
Source File: c:\Working\Git\ID\UMB Packages\Website\Views\Default.cshtml Line: 6
Stack Trace:
[InvalidOperationException: Cannot render a macro when there is no
current PublishedContentRequest.]
Umbraco.Web.UmbracoHelper.RenderMacro(String alias, IDictionary2
parameters) +142 ASP._Page_Views_Default_cshtml.Execute() in
c:\Working\Git\ID\UMB Packages\Website\Views\Default.cshtml:6
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +280
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +125
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext
pageContext, TextWriter writer, WebPageRenderingBase startPage) +196
System.Web.WebPages.WebPageBase.Write(HelperResult result) +89
System.Web.WebPages.WebPageBase.RenderSurrounding(String
partialViewName, Action1 body) +233
System.Web.WebPages.WebPageBase.PopContext() +287
Umbraco.Core.Profiling.ProfilingView.Render(ViewContext viewContext,
TextWriter writer) +140
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+378 System.Web.Mvc.<>c__DisplayClass1a.b__17()
+33 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func1 continuation)
+799724 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func1 continuation)
+799724 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionResult actionResult) +263
System.Web.Mvc.Async.<>c__DisplayClass25.b__22(IAsyncResult
asyncResult) +787092
System.Web.Mvc.<>c__DisplayClass1d.b__18(IAsyncResult
asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult
ar) +15 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult
asyncResult) +65
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult
ar) +15 System.Web.Mvc.Controller.EndExecute(IAsyncResult
asyncResult) +51
System.Web.Mvc.<>c__DisplayClass8.b__3(IAsyncResult
asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.b__3(IAsyncResult
ar) +15 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult
asyncResult) +51
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
public class BlogController : RenderMvcController
{
public BlogController()
: this(UmbracoContext.Current)
{
}
public BlogController(UmbracoContext umbracoContext)
: base(umbracoContext)
{
}
public ActionResult Index(int id)
{
return View("12321");
}
public ActionResult YearPost(int id)
{
string test = "Blog";
var criteria = ExamineManager.Instance.DefaultSearchProvider.CreateSearchCriteria("content");
var filterBlogs = id == 0 ? criteria.NodeTypeAlias("Blog") : criteria.NodeName("Blog");
var result = Umbraco.TypedSearch(filterBlogs.Compile()).ToArray().First();
var renderModel = CreateRenderModel(result);
string viewBlog = "BlogPostPage";
return View(viewBlog, renderModel);
}
private RenderModel CreateRenderModel(IPublishedContent content)
{
var model = new RenderModel(content,CultureInfo.CurrentUICulture);
//add an umbraco data token so the umbraco view engine executes
RouteData.DataTokens["umbraco"] = model;
RouteData.DataTokens["umbraco-doc-request"] = UmbracoContext.PublishedContentRequest;
RouteData.DataTokens["umbraco-context"] = UmbracoContext;
return model;
}
}

Related

Value does not fall within the expected range with T4MVC in ASP.NET MVC site

I have this property below that gets called fine but every once in a while I get the error System.ArgumentException: Value does not fall within the expected range.. The ID going in looks like so what else could be making this error?
protected readonly Controller Controller;
public EventUrls(Controller controller, string storeHost = null)
{
Controller = controller;
StoreHost = storeHost;
}
public virtual string HomeUrl { get { return Controller.Url.Action(MVC.Event.Index(EventId, EventName.GenerateSlug())); } }
Full Stack
System.Web.HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'. ---> System.ArgumentException: Value does not fall within the expected range.
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)
at System.Web.WebPages.UrlRewriterHelper.WasThisRequestRewritten(HttpContextBase httpContext)
at System.Web.WebPages.UrlUtil.GenerateClientUrlInternal(HttpContextBase httpContext, String contentPath)
at System.Web.WebPages.UrlUtil.GenerateClientUrl(HttpContextBase httpContext, String contentPath)
at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, String protocol, String hostName, String fragment, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
at System.Web.Mvc.UrlHelper.RouteUrl(String routeName, RouteValueDictionary routeValues, String protocol, String hostName)
at System.Web.Mvc.T4Extensions.Action(UrlHelper urlHelper, ActionResult result)
at Tournaments.Models.ViewModels.EventUrls.get_HomeUrl() in F:\Rankings\Websites\Tournaments\Models\ViewModels\EventUrls.cs:line 30
at ASP._Page_Views_Event_Controls_EventHeader_cshtml.Execute() in C:\StoreBeta\Views\Event\Controls\EventHeader.cshtml:line 5
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.<>c__DisplayClass5_0.<Wrap>b__0()
at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func`1 func)
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
at System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter)
at System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues)
at ASP._Page_Views_Shared__Event_cshtml.Execute() in C:\StoreBeta\Views\Shared\_Event.cshtml:line 72
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.WebPages.WebPageBase.<>c__DisplayClass40_0.<RenderPageCore>b__0(TextWriter writer)
at System.Web.WebPages.WebPageBase.Write(HelperResult result)
at System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body)
at System.Web.WebPages.WebPageBase.PopContext()
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Edit
I was able to replicate this, as the Season.Id is 2025386, Organization.Id is 1294, and Team.DivisionId is 1919. Which all are within value range so I am not sure why this is throwing that error?
if it is about arguament and if you are getting the error sometimes ı think it can be you are trying to pass value to that method which does not match the type or range of parameter
For example if you are passing a value 123213123434212312 to a parameter of type int then you will get ArgumentException

Custom cache not working at Child Actions

I'm working with a custom class that output cche for mobile and normal pages seperately. I only caches index page. It works perfect while caching with index page. But when using with child actions, the following error is thrown:
Server Error in '/' Application.
Unable to cast object of type 'System.IO.StringWriter' to type 'System.Web.HttpWriter'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object of type 'System.IO.StringWriter' to type 'System.Web.HttpWriter'.
Source Error:
Line 82: sw = new StringWriter(sb);
Line 83: tw = new HtmlTextWriter(sw);
Line 84: output = (HttpWriter)filterContext.RequestContext.HttpContext.Response.Output;
Line 85: filterContext.RequestContext.HttpContext.Response.Output = tw;
Line 86: }
Source File: H:\Yazılımlar\Haber Sitesi v2\HaberSitesiV2\HaberSitesiV2\Filters\CustomCacheAttribute.cs Line: 84
Stack Trace:
[InvalidCastException: Unable to cast object of type 'System.IO.StringWriter' to type 'System.Web.HttpWriter'.]
HaberSitesiV2.Filters.CustomCacheAttribute.OnActionExecuting(ActionExecutingContext filterContext) in H:\Yazılımlar\Haber Sitesi v2\HaberSitesiV2\HaberSitesiV2\Filters\CustomCacheAttribute.cs:84
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +69
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +489
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +489
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +191
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +197
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.Mvc.<>c__DisplayClass7.<BeginProcessRequest>b__6() +31
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +27
System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +98
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +2019
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +76
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +28
System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +19
System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +483
System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +83
System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName) +10
ASP._Page_Views_Anasayfa_Index_cshtml.Execute() in h:\Yazılımlar\Haber Sitesi v2\HaberSitesiV2\HaberSitesiV2\Views\Anasayfa\Index.cshtml:29
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +97
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +260
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +295
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
And my class is follow.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Web.UI;
using System.Web.WebPages;
namespace HaberSitesiV2.Filters
{
public enum CachePolicy
{
NoCache = 0,
Client = 1,
Server = 2,
ClientAndServer = 3
}
public class CustomCacheAttribute : ActionFilterAttribute
{
#region Public properties
public string VaryByParam { get; set; }
public CachePolicy CachePolicy { get; set; }
#endregion
#region Private members
private HtmlTextWriter tw;
private StringWriter sw;
private StringBuilder sb;
private HttpWriter output;
private bool cacheHitNormal = false;
private bool cacheHitMobile = false;
#endregion
#region ActionFilterAttribute overrides
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Server-side caching?
if (CachePolicy == CachePolicy.Server || CachePolicy == CachePolicy.ClientAndServer)
{
if (filterContext.HttpContext.Application["cacheSql"] != null)
{
// Fetch cached data
string key = GenerateKey(filterContext);
object cachedData = HttpContext.Current.Cache.Get(key);
if (cachedData != null)
{
// cache hit
if (filterContext.HttpContext.GetOverriddenBrowser().IsMobileDevice)
cacheHitMobile = true;
else
cacheHitNormal = true;
// Return cached data
filterContext.HttpContext.Response.Write(cachedData);
filterContext.Result = new EmptyResult();
}
else
{
// Cache not hit.
if (filterContext.HttpContext.GetOverriddenBrowser().IsMobileDevice)
cacheHitMobile = false;
else
cacheHitNormal = false;
//
sb = new StringBuilder();
sw = new StringWriter(sb);
tw = new HtmlTextWriter(sw);
output = (HttpWriter)filterContext.RequestContext.HttpContext.Response.Output;
filterContext.RequestContext.HttpContext.Response.Output = tw;
}
}
}
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
// Server-side caching?
if (CachePolicy == CachePolicy.Server|| CachePolicy == CachePolicy.ClientAndServer)
{
if (filterContext.HttpContext.Application["cacheSql"] != null)
{
if (filterContext.HttpContext.GetOverriddenBrowser().IsMobileDevice ? !cacheHitMobile : !cacheHitNormal)
{
int duration = 0;
duration = Convert.ToInt32(filterContext.HttpContext.Application["cacheSql"]);
//response processing
output.Write(sb.ToString());
// Add data to cache
HttpContext.Current.Cache.Insert(
GenerateKey(filterContext),
sb.ToString(),
null,
DateTime.Now.AddMinutes(duration),
Cache.NoSlidingExpiration,
CacheItemPriority.Normal,
null);
}
}
}
}
#endregion
#region Helper methods
private string GenerateKey(ControllerContext filterContext)
{
StringBuilder cacheKey = new StringBuilder();
// Controller + action
cacheKey.Append(filterContext.Controller.GetType().FullName);
if (filterContext.RouteData.Values.ContainsKey("action"))
{
cacheKey.Append("_");
cacheKey.Append(filterContext.RouteData.Values["action"].ToString());
}
// Variation by parameters
List<string> varyByParam = VaryByParam.Split(';').ToList();
if (!string.IsNullOrEmpty(VaryByParam))
{
foreach (KeyValuePair<string, object> pair in filterContext.RouteData.Values)
{
if (VaryByParam == "*" || varyByParam.Contains(pair.Key))
{
cacheKey.Append("_");
cacheKey.Append(pair.Key);
cacheKey.Append("=");
cacheKey.Append(pair.Value.ToString());
}
}
}
cacheKey.Append("_");
cacheKey.Append(filterContext.HttpContext.GetOverriddenBrowser().IsMobileDevice ? "mobil" : "normal");
return cacheKey.ToString();
}
#endregion
}
}

constructor of a controller don't take a param mvc

why when i add a param for the constructor of the controller, I get an error.
this is my code:
public partial class RegistrationController : Controller
{
public RegistrationController(int i)
{
}
public ActionResult Index()
{}
}
the error is `Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 14:
Line 15: <fieldset>
Line 16: #{string visibleCountry = (Model.CountryParam == ConfigurationParamValue.NotVisible) ? "display:none" : "display:inline";
Line 17: string mandatoryCountry = (Model.CountryParam == ConfigurationParamValue.isMandatory) ? "display:inline" : "display:none";
Line 18: <div id="county" style="#visibleCountry">
Source File: e:\VP5-Nuguet\src\Registration\Registration.Front.Web\Views\Registration\Index.cshtml Line: 16
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Registration_Index_cshtml.Execute() in e:\VP5-Nuguet\src\Registration\Registration.Front.Web\Views\Registration\Index.cshtml:16
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +97
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +260
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +295
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9630364
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929 `
If you insist the the constructor parameter you have to build your own ControllerFactory implementing the IControllerFactory interface and set it in the app start.
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
MVC will try to instantiate the controller specified in the route for each request by calling its default constructor.
From the looks of it, you want to hit a URL like: /registration/{someNumber}.
If this is the case, move the int id from the constructor to the action method:
public partial class RegistrationController : Controller
{
public RegistrationController()
{ }
public ActionResult Index(int i)
{
// do something
}
}

Linq selecting from GroupBy

I want to select every group into custom class and every item into another custom class,
I done this like this:
_notificationsManager
.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.Select(g => new NotificationsGroupData {
Name = g.Key,
Notifications = g.Take(3).Select(s => new NotificationData {
Category = g.Key,
Text = s.Text,
Time = DateTime.Now.Subtract(s.Time)
})
})
Here the NotificationsGroupData:
public class NotificationsGroupData
{
public string Name { get; set; }
public IEnumerable<NotificationData> Notifications { get; set; }
}
And NotificationData:
public class NotificationData
{
public virtual TimeSpan Time { get; set; }
public virtual string Category { get; set; }
public virtual string Text { get; set; }
}
But when I'm trying to create loop over this I'm getting error:
The method or operation is not implemented.
On this line:
#foreach (var group in Model.Notifications)
How I can fix it?
Uodate:
I updated the code to this:
_notificationsManager.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.Select(g => new
{
Name = g.Key,
Notifications =
g.OrderBy(o => o.Time)
.Take(3)
.Select(s => new
{
Category = g.Key,
s.Text,
s.Time
})
}).AsEnumerable().Select(g => new NotificationsGroupData
{
Name = g.Name,
Notifications = g.Notifications
.Select(s => new NotificationData
{
Category = g.Name,
Text = s.Text,
Time = now - s.Time
})
})
And here the error:
The method or operation is not implemented.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NotImplementedException: The method or operation is not implemented.
Source Error: #foreach (var group in Model.Notifications)
Stack Trace:
[NotImplementedException: The method or operation is not implemented.] NHibernate.Linq.GroupBy.NonAggregatingGroupByRewriter.FlattenSubQuery(SubQueryExpression subQueryExpression, QueryModel queryModel) +608 NHibernate.Linq.GroupBy.NonAggregatingGroupByRewriter.ReWrite(QueryModel queryModel) +598 NHibernate.Linq.Visitors.QueryModelVisitor.GenerateHqlQuery(QueryModel queryModel, VisitorParameters parameters, Boolean root) +126 NHibernate.Linq.NhLinqExpression.Translate(ISessionFactoryImplementor sessionFactory) +208 NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryIdentifier, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory) +51 NHibernate.Engine.Query.HQLExpressionQueryPlan.CreateTranslators(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) +100 NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) +74 NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) +53 NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters) +320 NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow) +188 NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression) +164 NHibernate.Linq.DefaultQueryProvider.PrepareQuery(Expression expression, IQuery& query, NhLinqExpression& nhQuery) +152 NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)
+70 NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression) +59 Remotion.Linq.QueryableBase`1.GetEnumerator() +128 System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +61 ASP._Page_Views_Layout_Notifications_cshtml.Execute() in d:\Dev\Projects\ADDE\ADDE\Views\Layout\Notifications.cshtml:21 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +88 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235 System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+291 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
+23 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245 System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
+22 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176 System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20()
+75 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99 System.Web.Mvc.Async.WrappedAsyncResult`1.End()
+50 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+31 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +22 System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +10 System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +27 System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +64 System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +71 System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1464
[HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.] System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3033503 System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +76 System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +28 System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +19 System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +463 System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName) +35 ASP._Page_Views_Shared__Layout_cshtml.Execute() in d:\Dev\Projects\ADDE\ADDE\Views\Shared\_Layout.cshtml:33 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +88 System.Web.WebPages.<>c__DisplayClass7.<RenderPageCore>b__6(TextWriter writer) +233 System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +10 System.Web.WebPages.WebPageBase.Write(HelperResult result) +71 System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +64 System.Web.WebPages.WebPageBase.PopContext() +246 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +95 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235 System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+291 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
+23 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245 System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
+22 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176 System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20()
+75 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99 System.Web.Mvc.Async.WrappedAsyncResult`1.End()
+50 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+31 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+9629708 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I suspect the problem may well be in the DateTime.Now.Subtract(s.Time) part, possibly combined with your use of NotificationsGroupData.
I suggest you change your query to simply fetch all the data you need without processing it much, and then perform the more complex work locally using AsEnumerable. So something like:
// Use a single common idea of "now", don't re-evaluate each time
var now = DateTime.Now;
var query = _notificationsManager
.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.Select(g => new {
Name = g.Key,
Notifications = g.Take(3)
.Select(s => new {
Text = s.Text,
Time = s.Time
})
})
.AsEnumerable() // Force local evaluation for final step
.Select(g => new NotificationsGroupData {
Name = g.Name,
Notifications = g.Notifications
.Select(s => new NotificationData {
Category = g.Name,
Text = s.Text,
Time = now - s.Time
})
});
EDIT: Okay, as that's still giving problems, you could try doing everything post-grouping in-process:
var now = DateTime.Now;
var query = _notificationsManager
.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.AsEnumerable() // Force local evaluation for final step
.Select(g => new NotificationsGroupData {
Name = g.Key,
Notifications = g.Take(3)
.Select(s => new NotificationData {
Category = g.Key,
Text = s.Text,
Time = now - s.Time
})
});
Note that this is far from idea - it'll pull all the properties from the database, not just the ones you want. (And not just the first three - although "first" depends on the ordering too, which hasn't been specified anywhere that we can see.) It could be that this is one of those situations where you need to fall back to SQL, but it does sound like NHibernate could be doing more for you...
NHibernate cannot translate your query to sql. The quickest solution will be to make your selection statement on inmemory collection other than pass it to NHibernate. Try this:
_notificationsManager
.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.ToList()
.Select(g => new NotificationsGroupData {
Name = g.Key,
Notifications = g.Take(3).Select(s => new NotificationData {
Category = g.Key,
Text = s.Text,
Time = DateTime.Now.Subtract(s.Time)
})
})
Another optin will be to write your query on HQL\SQL and pass it to NHibernate, so you'll have necessary number of data pulled from database and map it to your custom entities afterwards.

Why is my element variable always null in this foreach loop?

Here is the code:
public IEnumerable<UserSummary> getUserSummaryList()
{
var db = new entityContext();
List<UserSummary> model = new List<UserSummary>();
List<aspnet_Users> users = (from user in db.aspnet_Users
select user).ToList<aspnet_Users>();
foreach (aspnet_Users u in users) //u is always null while users is a list that contains 4 objects
{
model.Add(new UserSummary()
{
UserName = u.UserName,
Email = u.aspnet_Membership.Email,
Role = Roles.GetRolesForUser(u.UserName).First(),
AdCompany = u.AD_COMPANIES.ad_company_name != null ? u.AD_COMPANIES.ad_company_name : "Not an Advertiser",
EmployeeName = u.EMPLOYEE.emp_name != null ? u.EMPLOYEE.emp_name : "Not an Employee"
});
}
return model;
}
For some reason the u variable in the foreach loop is always null. I've stepped through the code and the users collection is always populated. The table entity for db.aspnet_Users is the users table that comes with asp.net membership services. I've only added a couple associations to it.
edit : image of debugger
Here is the stacktrace:
[NullReferenceException: Object reference not set to an instance of an object.]
OutAd.Models.AccountMembershipService.getUserSummaryList() in C:\Users\stephen\Desktop\outad\OutAd\OutAd\Models\AccountModels.cs:301
OutAd.Controllers.AdminController.UserList() in C:\Users\stephen\Desktop\outad\OutAd\OutAd\Controllers\AdminController.cs:78
lambda_method(Closure , ControllerBase , Object[] ) +96
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +23
System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +12
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +38
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +65
System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +71
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1072
[HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.]
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3049403
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +77
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +28
System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +22
System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +497
System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +88
System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName) +10
ASP._Page_Views_Admin_Users_cshtml.Execute() in c:\Users\stephen\Desktop\outad\OutAd\OutAd\Views\Admin\Users.cshtml:7
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81
System.Web.WebPages.StartPage.RunPage() +19
System.Web.WebPages.StartPage.ExecutePageHierarchy() +65
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +220
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +303
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260
System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969201
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Replace :
Roles.GetRolesForUser(u.UserName)
By:
Roles.Provider.GetRolesForUser(u.UserName);
cfr.: http://www.lhotka.net/weblog/CallingRolesGetRolesForUserInAWCFService.aspx
I'm going to guess that u is not null in itself, but one of it's properties is null, or the Roles.GetRolesForUser(u.UserName) call returns null. If that is the case then when you try to access the members of those null values you get the NullReferenceException.
Example:
public class Person
{
public Address HomeAddress { get; set; }
}
public class Address
{
public String StreetAddress { get; set; }
}
public void SomeFunc()
{
var person = new Person();
//NullReferenceException because HomeAddress is null.
//NOT because person is null...
var address = person.HomeAddress.StreetAddress;
}
You can verify this by hovering over each item in the Debugger to ensure that it is not null, but I bet you one of those objects is. To ensure that your GetRolesForUser method is not returning null, simply call that in the immediate window and see what you get back. If you get back null, there's your issue.
Alternatively, just throw each of the right hand assignments into your local watch window and one of them will present itself as the issue.
Oh, and a few other things...
If you are planning to return an IEnumerable<T> do not create a list and then return that list, instead just yield return your objects.
Use null coalescing operators when necessary.
Use a using statement for your IDisposable objects.
Fixed version:
public IEnumerable<UserSummary> getUserSummaryList()
{
using (var db = new EntityContext())
{
foreach (aspnet_Users user in users)
{
// Retrieve the username (with logic if it is null or empty)
var username = user.UserName;
// Retrieve the email (with logic if it is null or empty)
var email = (user.aspnet_Membership != null)
? user.aspnet_Membership.Email ?? String.Empty
: String.Empty;
// Retrieve the role (with logic if it is null)
var roles = Roles.GetRolesForUser(username);
var role = (roles != null) ? roles.FirstOrDefault() : null;
// Retrieve the Ad Company (with logic if it is null)
var adCompany = (user.AD_COMPANIES != null)
? user.AD_COMPANIES.ad_company_name ?? "Not an Advertiser"
: "Not an Advertiser";
var empName = (user.EMPLOYEE != null)
? user.EMPLOYEE.emp_name ?? "Not an Employee"
: "Not an Employee";
yield return new UserSummary
{
UserName = username,
Email = email,
Role = role,
AdCompany = adCompany,
EmployeeName = empName,
};
}
}
}

Categories

Resources