I'm using Postal library for sending emails in an ASP.NET MVC5 Web project. It works fine when called from a controller. However, I planned a number of jobs to send emails using fluentScheduler. And I am calling a method that sends emails using the instructions here http://aboutcode.net/postal/outside-aspnet.html.
But I still get the same exception everytime I run the background task.
object reference not set to an instance of an object
Here is the stack:
at Glimpse.AspNet.AspNetFrameworkProvider.get_HttpRequestStore()
at Glimpse.Core.Framework.Factory.<>c__DisplayClass5.<InstantiateRuntimePolicyStrategy>b__4()
at Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context, TimerResult& timerResult)
at Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context)
at Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.IViewEngineProxy.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache)
at System.Web.Mvc.ViewEngineCollection.<>c__DisplayClass6.<FindView>b__4(IViewEngine e)
at System.Web.Mvc.ViewEngineCollection.Find(Func`2 lookup, Boolean trackSearchedPaths)
at System.Web.Mvc.ViewEngineCollection.Find(Func`2 cacheLocator, Func`2 locator)
at System.Web.Mvc.ViewEngineCollection.FindView(ControllerContext controllerContext, String viewName, String masterName)
at Postal.EmailViewRenderer.CreateView(String viewName, ControllerContext controllerContext)
at Postal.EmailViewRenderer.Render(Email email, String viewName)
at Postal.EmailService.CreateMailMessage(Email email)
at Postal.EmailService.Send(Email email)
at Postal.Email.Send()
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid1[T0](CallSite site, T0 arg0)
at Bay3.Helpers.EmailHelper.FollowerEmail(String to, String link, String articleName, String lang) in e:\_TFS2\Bay3\Bay3\Helpers\EmailHelper.cs:line 39
I hope that someone had the same problem before
Related
I am new to Sitecore,SoleNet. I have installed and configured Solr to work with Sitecore and I am able to see results.
I am now using code.
I added the connection string to UnityMVCActivator.cs in the Start()
Startup.Init("http://localhost:8983/solr/sitecore_web_index");
In my controller - Actionresults Index()
var solr = ServiceLocator.Current.GetInstance>();
I get this error
[InvalidOperationException: The type ISolrOperations1 does not have an
accessible constructor.]
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext
context) +226 lambda_method(Closure , IBuilderContext ) +39
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.b__0(IBuilderContext
context) +33
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext
context) +337
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext
context) +396 Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type
t, Object existing, String name, IEnumerable1 resolverOverrides) +238
[ResolutionFailedException: Resolution of the dependency failed, type
= "SolrNet.ISolrOperations`1[Niddk.Model.SearchResultsViewModel]", name = "(none)". Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type ISolrOperations`1 does not have an accessible constructor.
At the time of the exception, the container was:
Resolving
SolrNet.ISolrOperations1[Niddk.Model.SearchResultsViewModel],(none) ]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object
existing, String name, IEnumerable1 resolverOverrides) +500
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name,
ResolverOverride[] resolverOverrides) +20
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type
serviceType, String key) +55
[ActivationException: Activation error occured while trying to get
instance of type ISolrOperations1, key ""]
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type
serviceType, String key) +156
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance()
+62 Niddk.Web.Controllers.SearchController.Index() in C:\Users\ksivanandan\Source\Repos\web\Niddk\Niddk.Web\Controllers\SearchController.cs:23
lambda_method(Closure , ControllerBase , Object[] ) +87
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary2 parameters) +229
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters) +35
System.Web.Mvc.<>c__DisplayClass15.b__12()
+80 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
filter, ActionExecutingContext preContext, Func1 continuation) +453
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter
filter, ActionExecutingContext preContext, Func`1 continuation) +453
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName) +533
My ViewModel
public class SearchResultsViewModel
{
[SolrField("headline_t")]
public string Headline { get; set; }
}
Any help is greatly appreciated.
Thank you!
Edit: this thread was also raised in GitHub in SolrNet and the project maintainer provided the right answer.
The problem is that for registering he is using the built in IoC but then resolving via Unity.
Original response
I may be reading your code wrong or something might be missing from the post but you are not passing the type:
In my controller - Actionresults Index()
var solr = ServiceLocator.Current.GetInstance<[you are missing this part]>();
When using generics you need to specify the type. I thinks this part would not even compile because of the .GetInstance>() being incomplete.
After deploying an MVC3 application that has Telerik Extensions menu, I have noted there are times it throws an OutOfMemoryException and after that the application freezes and no user is able to use the application until after about an hour or so.
I managed to trace the errors from the windows event log and the following is a stack trace of one of the errors extracted from the event log
Exception information:
Exception type: OutOfMemoryException
Exception message: Exception of type 'System.OutOfMemoryException' was thrown.
at System.RuntimeTypeHandle.ConstructName(RuntimeTypeHandle handle,
Boolean nameSpace, Boolean fullInst, Boolean assembly, StringHandleOnStack retString)
at System.RuntimeType.RuntimeTypeCache.ConstructName(String& name, Boolean nameSpace, Boolean fullinst, Boolean assembly)
at System.RuntimeType.get_Name()
at Telerik.Web.Mvc.Infrastructure.Implementation.ControllerTypeCache.<GetAllControllerTypes>b__d(Type type)
at System.Linq.Enumerable.WhereArrayIterator`1.MoveNext()
at Telerik.Web.Mvc.Extensions.CollectionExtensions.AddRange[T](ICollection`1 instance, IEnumerable`1 collection)
at Telerik.Web.Mvc.Infrastructure.Implementation.ControllerTypeCache.GetAllControllerTypes()
at Telerik.Web.Mvc.Infrastructure.Implementation.ControllerTypeCache.<GetControllerTypesWithinNamespaces>b__4()
at Telerik.Web.Mvc.Infrastructure.Implementation.Cache.Get[T](String key, Func`1 defaultValueFactory)
at Telerik.Web.Mvc.Infrastructure.Implementation.ControllerTypeCache.GetControllerTypesWithinNamespaces(String controllerName, IEnumerable`1 namespaces)
at Telerik.Web.Mvc.Infrastructure.Implementation.ControllerTypeCache.GetControllerTypes(String controllerName)
at Telerik.Web.Mvc.Infrastructure.Implementation.ControllerDescriptorCache.ControllerDescriptorFactory(String controllerName, String areaName)
at Telerik.Web.Mvc.Infrastructure.Implementation.ControllerDescriptorCache.<>c__DisplayClass1.<GetControllerDescriptor>b__0()
at Telerik.Web.Mvc.Infrastructure.Implementation.Cache.Get[T](String key, Func`1 defaultValueFactory)
at Telerik.Web.Mvc.Infrastructure.Implementation.ControllerDescriptorCache.GetControllerDescriptor(String controllerName, String areaName)
at Telerik.Web.Mvc.Infrastructure.Implementation.AuthorizationContextCache.AuthorizationContextFactory(RequestContext requestContext, String controllerName, String actionName, String areaName)
at Telerik.Web.Mvc.Infrastructure.Implementation.AuthorizationContextCache.<>c__DisplayClass1.<GetAuthorizationContext>b__0()
at Telerik.Web.Mvc.Infrastructure.Implementation.Cache.Get[T](String key, Func`1 defaultValueFactory)
at Telerik.Web.Mvc.Infrastructure.Implementation.AuthorizationContextCache.GetAuthorizationContext(RequestContext requestContext, String controllerName, String actionName, RouteValueDictionary routeValues)
at Telerik.Web.Mvc.Infrastructure.Implementation.ControllerAuthorization.IsAccessibleToUser(RequestContext requestContext, String controllerName, String actionName, RouteValueDictionary routeValues)
at Telerik.Web.Mvc.Infrastructure.Implementation.NavigationItemAuthorization.IsAccessibleToUser(RequestContext requestContext, INavigatable navigationItem)
at Telerik.Web.Mvc.UI.NavigatableExtensions.<>c__DisplayClass2`1.<IsAccessible>b__1(T item)
at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source, Func`2 predicate)
at Telerik.Web.Mvc.UI.NavigatableExtensions.IsAccessible[T](IEnumerable`1 items, INavigationItemAuthorization authorization, ViewContext viewContext)
at Telerik.Web.Mvc.UI.NavigationItemContainerExtensions.WriteItem[TComponent,TItem](TItem item, TComponent component, IHtmlNode parentTag, INavigationComponentHtmlBuilder`1 builder)
at Telerik.Web.Mvc.UI.Menu.<>c__DisplayClass4.<WriteHtml>b__3(MenuItem item)
at Telerik.Web.Mvc.Extensions.EnumerableExtensions.Each[T](IEnumerable`1 instance, Action`1 action)
at Telerik.Web.Mvc.UI.Menu.WriteHtml(HtmlTextWriter writer)
at Telerik.Web.Mvc.UI.ViewComponentBase.Render()
at Telerik.Web.Mvc.UI.ViewComponentBuilderBase`2.Render()
at ASP._Page_Views_Shared__Layout_cshtml.Execute() in e:\kidda\Views\Shared\_Layout.cshtml:line 34
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__DisplayClass7.<RenderPageCore>b__6(TextWriter writer)
at System.Web.WebPages.HelperResult.WriteTo(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.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d()
at System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Common in the stack trace to all error stack traces is line 34 in _Layout.cshtml which draws the menu using the following code
<nav>
<div id="topMenu" >
<div style="width: 45%; float: right">
#{ Html.Telerik().Menu()
.Name("Menu")
.Items(menu =>
{
menu.Add()
.Text("Ngaari")
.Items(item =>
{
item.Add().Text("List").Action("Index", "Ngaari");
item.Add().Text("Statement").Action("Index", "Statement");
});
menu.Add()
.Text("Njia")
.Action("Index", "Njia");
menu.Add()
.Text("Kiama")
.Action("Index", "Kiama");
menu.Add()
.Text("Ngaari Type")
.Action("Index", "NgaariType");
menu.Add()
.Text("Admin")
.Items(item =>
{
item.Add().Text("List Users").Action("Index", "Account");
item.Add().Text("Add User").Action("NewUser", "Account");
item.Add().Text("Change Password").Action("ChangePassword", "Account");
});
})
.Render();
}
</div>
</div>
</nav>
The application is running on a Windows 2003 SP2 which has 4Gb of memory and the users are using Mozilla Firefox to access the system.
I have googled and searched in Telerik forums and SOF and found no answers or similar users who could have had a similar problem.
What could be causing this error and how can I go about in resolving it?
Resolved the problem by monitoring performance and memory usage on the server.
I realized IIS was competing for memory with SQL Server and the memory was not
being recycled frequently and this was what was causing the problem
Following recommendations from IIS 6 Administration, I performed the following:
Set application pool to recycle after a preset number of requests
Set times to recycle worker processes during low activity times
Set a cap on the amount of virtual and physical memory to be used by
the application
Performing the above has totally eliminated the problem.
Based on the great answer at multi-step registration process issues in asp.net mvc (splitted viewmodels, single model), I used the example Darin Dimitrov provided to test out an ASP.net MVC3 wizard. It works standalone, but not inside Orchard CMS v1.3.
I am getting the following error:
Server Error in '/' Application.
Cannot create an instance of an interface.
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.MissingMethodException: Cannot create an
instance of an interface.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[MissingMethodException: Cannot create an instance of an interface.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean
publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean
fillCache) +241 System.Activator.CreateInstance(Type type, Boolean
nonPublic) +69
System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext
controllerContext, ModelBindingContext bindingContext, Type modelType)
+199 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext
controllerContext, ModelBindingContext bindingContext) +572
System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext
controllerContext, ModelBindingContext bindingContext) +449
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext
controllerContext, ParameterDescriptor parameterDescriptor) +317
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext
controllerContext, ActionDescriptor actionDescriptor) +117
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.b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass81.<BeginSynchronous>b__7(IAsyncResult
_) +12 System.Web.Mvc.Async.WrappedAsyncResult1.End() +62 System.Web.Mvc.<>c__DisplayClasse.b__d() +50
System.Web.Mvc.SecurityUtil.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
Orchard.Mvc.Routes.HttpAsyncHandler.EndProcessRequest(IAsyncResult
result) in
d:\Builds\OrchardFull\src\Orchard\Mvc\Routes\ShellRoute.cs:148
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+8963149 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Version Information: Microsoft .NET Framework Version:4.0.30319;
ASP.NET Version:4.0.30319.237
I am venturing a guess that it's the controller that's causing a fuss. Here is the code:
[Themed]
public class WizardController : Controller
{
public ActionResult Index()
{
var wizard = new WizardViewModel();
wizard.Initialize();
return View(wizard);
}
[HttpPost]
public ActionResult Index([Deserialize] WizardViewModel wizard, IStepViewModel step)
{
wizard.Steps[wizard.CurrentStepIndex] = step;
if (ModelState.IsValid)
{
if (!string.IsNullOrEmpty(Request["next"]))
{
wizard.CurrentStepIndex++;
}
else if (!string.IsNullOrEmpty(Request["prev"]))
{
wizard.CurrentStepIndex--;
}
else
{
// TODO: we have finished: all the step partial
// view models have passed validation => map them
// back to the domain model and do some processing with
// the results
return Content("thanks for filling this form", "text/plain");
}
}
else if (!string.IsNullOrEmpty(Request["prev"]))
{
// Even if validation failed we allow the user to
// navigate to previous steps
wizard.CurrentStepIndex--;
}
return View(wizard);
}
}
But I am not 100% sure, and the other culprit could be the WizardViewModel:
[Serializable]
public class WizardViewModel
{
public int CurrentStepIndex { get; set; }
public IList<IStepViewModel> Steps { get; set; }
public void Initialize()
{
Steps = new IStepViewModel[]
{
new Step1ViewModel(),
new Step2ViewModel(),
new Step3ViewModel()
};
}
}
That last part is a manual insertion of the steps and alters the code originally posted (direct from author). Any help is greatly appreciated.
Apparently, the Model Binder you are using can't find the model it needs to instantiate from the supplied interface (IStepViewModel)
I am quite sure that the default ASP.NET MVC ModelBinder can't do such thing, as it would require some custom logic to choose the concrete interface implementation that should be instantiated.
Therefore, you have two solutions:
Check your sample, I think it provides a custom ModelBinder, and register it in Orchard by implementing an IModelBinderProvider
Don't ask for a IStepViewModel in the Index action:
public ActionResult Index([Deserialize] WizardViewModel wizard, IStepViewModel step)
And replace it with a concrete class.
I'm trying to use mvcmailer in my mvc web app. When I used it in a dummy project and continued the steps stated in the wiki, it worked fine and I was able to send an email.
But when I tried to integrate it in my web app, its giving an error at "PopulateBody(mailMessage, viewName: "Welcome");" stating that it is unable to find _Layout.text. _Layout.text.cshtml and _Layout.cshtml exists in Usermailer folder along with Welcome.cshtml.
Usermailer code
public class UserMailer : MailerBase, IUserMailer
{
public UserMailer():
base()
{
MasterName="_Layout";
}
public virtual MailMessage Welcome(string email, string validationUrl)
{
var mailMessage = new MailMessage{Subject = "Welcome to GiftSocial"};
mailMessage.To.Add(email);
ViewBag.Validationkey = validationUrl;
PopulateBody(mailMessage, viewName: "Welcome");
return mailMessage;
}
}
Controller code
UserMailer.Welcome(email: model.Email, validationUrl: validationUrl).Send();
Copied exception Details:
System.Web.HttpException was unhandled by user code
Message=The layout page "_Layout.text" could not be found at the following path: "~/Views/UserMailer/_Layout.text".
Source=Mvc.Mailer
ErrorCode=-2147467259
WebEventCode=0
StackTrace:
at Mvc.Mailer.StringResult.ExecuteResult(ControllerContext context, String mailerName)
at Mvc.Mailer.MailerBase.EmailBody(String viewName, String masterName)
at Mvc.Mailer.MailerBase.PopulateTextBody(MailMessage mailMessage, String viewName, String masterName)
at Mvc.Mailer.MailerBase.PopulateBody(MailMessage mailMessage, String viewName, String masterName, Dictionary`2 linkedResources)
at MvcGiftSocial.Mailers.UserMailer.Welcome(String email, String validationUrl)
at MvcGiftSocial.Controllers.AccountController.Register(RegisterViewModel viewmodel, String returnUrl) in C:\Users\ASUS\Documents\Visual Studio 2010\Projects\GiftSocialAzureNew\MvcGiftSocial\Controllers\AccountController.cs:line 86
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
I would sincerely appreciate if someone could tell me what I'm doing wrong..
Thanks
Arnab
The error is pretty much self-explanatory. The required views were not found.
It seems that you were trying to send text/plain mail message. Therefor MvcMailer was looking for such views.
See: https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide#wiki-send-multi-part-emails
I am intermittently getting an System.InvalidCastException: Specified cast is not valid. error in my repository layer when performing an abstracted SELECT query mapped with LINQ.
The error can't be caused by a mismatched database schema since it works intermittently and it's on my local dev machine.
Could it be because StructureMap is caching the data context between page requests? If so, how do I tell StructureMap v2.6.1 to inject a new data context argument into my repository for each request?
Update: I found this question which correlates my hunch that something was being re-used. Looks like I need to call Dispose on my injected data context. Not sure how I'm going to do this to all my repositories without copypasting a lot of code.
Edit: These errors are popping up all over the place whenever I refresh my local machine too quickly. Doesn't look like it's happening on my remote deployment box, but I can't be sure.
I changed all my repositories' StructureMap life cycles to HttpContextScoped() and the error persists.
Code:
public ActionResult Index()
{
// error happens here, which queries my page repository
var page = _branchService.GetPage("welcome");
if (page != null)
ViewData["Welcome"] = page.Body;
...
}
Repository:
GetPage boils down to a filtered query mapping in my page repository.
public IQueryable<Page> GetPages()
{
var pages = from p in _db.Pages
let categories = GetPageCategories(p.PageId)
let revisions = GetRevisions(p.PageId)
select new Page
{
ID = p.PageId,
UserID = p.UserId,
Slug = p.Slug,
Title = p.Title,
Description = p.Description,
Body = p.Text,
Date = p.Date,
IsPublished = p.IsPublished,
Categories = new LazyList<Category>(categories),
Revisions = new LazyList<PageRevision>(revisions)
};
return pages;
}
where _db is an injected data context as an argument, stored in a private variable which I reuse for SELECT queries.
Calling code:
public Page GetPage(string slug)
{
return _pageRepository.GetPages()
.WithSlug(slug).FirstOrDefault();
}
WithSlug is just a pipeline filter that adds a where clause to the query.
Error:
Specified cast is not valid.
Exception Details: System.InvalidCastException: Specified cast is not valid.
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +4539
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +207
System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +500
System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +50
System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +383
Manager.Controllers.SiteController.Index() in C:\Projects\Manager\Manager\Controllers\SiteController.cs:68
lambda_method(Closure , ControllerBase , Object[] ) +79
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +258
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +125
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709
System.Web.Mvc.Controller.ExecuteCore() +162
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +58
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371
Messing around with disposing repositories didn't help, but setting MultipleActiveResultsets to true in my SQL connection string solved the problem.