What do I want?
I'm trying to override the Display method of the ItemController (Orchard.Core.Contents.Controllers.ItemController), so I can change the output based on the Accept Header.
If the header is "application/xml" I want to return xml
If the header is "application/json" I want to return json
Else return html ( like the default Display method)
What have I done?
I've made a copy of the ItemController and have placed it in the Controller folder of my custom Module. Also added the OrchardSuppressDependency Attribute above the class.
[OrchardSuppressDependency("Orchard.Core.Contents.Controllers.ItemController")]
[Themed]
public class ItemController : Controller
{
private readonly IContentManager _contentManager;
public ItemController(IContentManager contentManager, IShapeFactory shapeFactory, IOrchardServices services)
{
_contentManager = contentManager;
Shape = shapeFactory;
Services = services;
T = NullLocalizer.Instance;
}
dynamic Shape { get; set; }
public IOrchardServices Services { get; private set; }
public Localizer T { get; set; }
// /Contents/Item/Display/72
public ActionResult Display(int id)
{
var contentItem = _contentManager.Get(id, VersionOptions.Published);
if (contentItem == null)
return HttpNotFound();
if (!Services.Authorizer.Authorize(Permissions.ViewContent, contentItem, T("Cannot view content")))
{
return new HttpUnauthorizedResult();
}
//#Todo change output
dynamic model = _contentManager.BuildDisplay(contentItem);
return View((object)model);
}
Result
An error is thrown in ShellRoute.cs Displaying
{"The controller for path '/OrchardLocal/products/product-2' was not found or does not implement IController."}
StackTrace
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at Orchard.Mvc.OrchardControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\src\Orchard\Mvc\OrchardControllerFactory.cs:line 76
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at Orchard.Mvc.Routes.ShellRoute.HttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) in XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\src\Orchard\Mvc\Routes\ShellRoute.cs:line 148
Have I overlooked something?
Or is this the wrong approach?
Related
I'm having some difficulty with crashing code in a Delete method (MVC). Here are two methods in my ProductItem controller class. The "Delete" works fine, but I'm getting an error message and when I step through, I notice that the DeleteConfirmed below it is getting a null value for prodID (itemID passes in fine). I have a tough time troubleshooting this because I don't know how the DeleteConfirmed method is being "called" or how the values are getting passed in (or supposed to be passed in) so I don't know what to trace or step through.
EDIT: I removed the nullable from the two arguments for itemID and productID, now it doesn't even get to DeleteConfirmed, I get this:
[ArgumentException: The parameters dictionary contains a null entry for parameter 'prodID' of non-nullable type 'System.Int32' for method 'System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] DeleteConfirmed(Int32, Int32)' in 'Memberships.Areas.Admin.Controllers.ProductItemController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters]
System.Web.Mvc.ActionDescriptor.ExtractParameterFromDictionary(ParameterInfo parameterInfo, IDictionary`2 parameters, MethodInfo methodInfo) +527
System.Web.Mvc.Async.<>c__DisplayClass20_0.<BeginExecute>b__0(ParameterInfo parameterInfo) +19
System.Linq.WhereSelectArrayIterator`2.MoveNext() +58
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +196
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +79
System.Web.Mvc.Async.TaskAsyncActionDescriptor.BeginExecute(ControllerContext controllerContext, IDictionary`2 parameters, AsyncCallback callback, Object state) +152
System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__0(AsyncCallback asyncCallback, Object asyncState) +28
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAsynchronousActionMethod(ControllerContext controllerContext, AsyncActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +179
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +45
System.Web.Mvc.Async.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex) +87
System.Web.Mvc.Async.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex) +629
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__0(AsyncCallback asyncCallback, Object asyncState) +58
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
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__DisplayClass3_1.<BeginInvokeAction>b__0(AsyncCallback asyncCallback, Object asyncState) +640
System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +346
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +494
System.Web.Mvc.<>c.<BeginExecute>b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +403
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +427
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +105
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
// GET: Admin/ProductItem/Delete/5
public async Task<ActionResult> Delete(int? itemID, int? productID)
{
if (itemID == null || productID == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product_Item product_Item = await GetProductItem(itemID, productID);
if (product_Item == null)
{
return HttpNotFound();
}
return View(await product_Item.Convert(db));
}
// POST: Admin/ProductItem/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int itemID, int prodID)
{
Product_Item product_Item = await GetProductItem(itemID, prodID);
db.Products_Items.Remove(product_Item);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
As requested: The View Model
using Memberships.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Memberships.Areas.Admin.Models
{
public class ProductItemModel
{
[DisplayName("Product ID")]
public int ProductID { get; set; }
[DisplayName("Item ID")]
public int ItemID { get; set; }
[DisplayName("Product")]
public string ProductTitle { get; set; }
[DisplayName("Item")]
public string ItemTitle { get; set; }
public ICollection<Product> Products { get; set; }
public ICollection<Item> Items { get; set; }
}
}
public static async Task<ProductItemModel> Convert
(this Product_Item productItem, ApplicationDbContext db, bool addListData=true)
//Only fill collections if the parameter passed in is true
{
var model = new ProductItemModel
{
ItemID = productItem.ItemID,
ProductID = productItem.ProductID,
Items = addListData ? await db.Items.ToListAsync() : null,
Products = addListData ? await db.Products.ToListAsync() : null,
ItemTitle = (await db.Items.FirstOrDefaultAsync(i => i.ID.Equals(productItem.ItemID))).Title,
ProductTitle = (await db.Products.FirstOrDefaultAsync(p => p.ID.Equals(productItem.ProductID))).Title
};
return model;
}
private async Task<Product_Item> GetProductItem(int? item, int? prod)
{
try
{
int itemID = 0, prodID = 0;
int.TryParse(item.ToString(), out itemID);
int.TryParse(prod.ToString(), out prodID);
var productItem = await db.Products_Items.FirstOrDefaultAsync
(
pi => pi.ProductID.Equals(prodID) && pi.ItemID.Equals(itemID)
);
return productItem;
}
catch {return null;}
}
I figured it out, oddly enough when I had to copy the code and paste it for a new function. The problem was in the delete button itself. The model used to build the parameter string for the Edit Details and Delete buttons (code pasted below) uses "ProductID" for a parameter name, yet the controller's delete method used the argument ProdID instead of ProductID so it was coming in null!!
public string ActionParameters //Build a string containing any id paramaters which are passed in.
{
get
{
var param = new StringBuilder("?");
if(ID != null && ID>0)
{ //If the ID is not null then "id=<ID>" will be appended to the parameter string.
param.Append(String.Format("{0}={1}&","id",ID));
}
if ((ItemID ?? 0) > 0)
{ //If the ID is not null then "id=<ID>" will be appended to the parameter string.
param.Append(String.Format("{0}={1}&", "ItemID", ItemID));
}
if ((ProductID ?? 0) > 0)
{ //If the ID is not null then "id=<ID>" will be appended to the parameter string.
**param.Append(String.Format("{0}={1}&", "ProductID", ProductID));**
}
if ((SubscriptionID ?? 0) > 0)
{ //If the ID is not null then "id=<ID>" will be appended to the parameter string.
param.Append(String.Format("{0}={1}&", "Subscription", SubscriptionID));
}
return param.ToString().Substring(0,param.Length-1); //Remove last "&"
}
I found this when I had to copy and paste the code for a similar function and noticed that the arguments didn't match.
Thanks for everyone who contributed!
im getting this error. Im newbie on MVC .
Can you help me please.I found somethings but i didnt understand what i will do. Sorry for my english.
I have 4 projects in a solution
.Admin
.UI
.Core
.Data
I have a problem with admin side.
Im trying to LoginFilter in admin page. When i run the project the page forwarding to /Account/Login page but its giving this error.
Error Page:
No parameterless constructor defined for this 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.MissingMethodException: No parameterless constructor defined for this object.
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: No parameterless constructor defined for this object.]
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, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +206
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +11
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +55
[InvalidOperationException: An error occurred when trying to create a controller of type 'WebHaber.Admin.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +76
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +88
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +194
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1098.0
AccountController.cs
using WebHaber.Core.Infrastructure;
using WebHaber.Data.Model;
namespace WebHaber.Admin.Controllers
{
public class AccountController : Controller
{
#region Kullanıcı
private readonly IKullaniciRepository _kullaniciRepository;
public AccountController(IKullaniciRepository kullaniciRepository)
{
_kullaniciRepository = kullaniciRepository;
}
#endregion
// GET: Account
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Kullanici kullanici)
{
var KullaniciVarmi = _kullaniciRepository.GetMany(x => x.Email == kullanici.Email && x.Sifre == kullanici.Sifre && x.Aktif == true).SingleOrDefault();
if (KullaniciVarmi != null)
{
if (KullaniciVarmi.Rol.RolAdi == "Admin")
{
Session["KullaniciEmail"] = KullaniciVarmi.Email;
return RedirectToAction("Index", "Home");
}
ViewBag.Mesaj = "Yetkisiz Kullanıcı";
return View();
}
ViewBag.Mesaj = "Kullanıcı Bulunamadı";
return View();
}
LoginFilter.cs
namespace WebHaber.Admin.CustomFilter
{
public class LoginFilter : FilterAttribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
HttpContextWrapper wrapper = new HttpContextWrapper(HttpContext.Current);
var SessionControl = context.HttpContext.Session["KullaniciEmail"];
if (SessionControl == null)
{
context.Result = new RedirectToRouteResult(
new RouteValueDictionary { { "Controller", "Account" }, { "action", "Login" } });
}
}
public void OnActionExecuting(ActionExecutingContext context)
{}
BootStrapper.cs
using Autofac;
using Autofac.Integration.Mvc;
using WebHaber.Core.Infrastructure;
using WebHaber.Core.Repository;
using WebHaber.Data.DataContext;
namespace WebHaber.Admin.Class
{
public class BootStrapper
{
//Boot aşamasında çalışacak.
public static void RunConfig()
{
BuilAutoFac();
}
private static void BuilAutoFac()
{
var builder = new ContainerBuilder();
builder.RegisterType<HaberRepository>().As<IHaberRepository>();
builder.RegisterType<ResimRepository>().As<IResimRepository>();
builder.RegisterType<KullaniciRepository>().As<IKullaniciRepository>();
builder.RegisterType<RolRepository>().As<IRolRepository>();
builder.RegisterControllers(typeof(MvcApplication).Assembly);
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
Global.asax
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
BootStrapper.RunConfig();
}
}
KullaniciRepository.cs
namespace WebHaber.Core.Repository
{
public class KullaniciRepository : IKullaniciRepository
{
private readonly HaberContext _context = new HaberContext();
public IEnumerable<Kullanici> GetAll()
{
//Tüm haberler dönecek
return _context.Kullanici.Select(x => x);
}
public Kullanici GetByID(int id)
{
return _context.Kullanici.FirstOrDefault(x => x.ID == id);
}
public Kullanici Get(Expression<Func<Kullanici, bool>> expression)
{
return _context.Kullanici.FirstOrDefault(expression);
}
public IQueryable<Kullanici> GetMany(Expression<Func<Kullanici, bool>> expression)
{
return _context.Kullanici.Where(expression);
}
public void Insert(Kullanici obj)
{
_context.Kullanici.Add(obj);
}
public void Update(Kullanici obj)
{
_context.Kullanici.AddOrUpdate();
}
public void Delete(int id)
{
var kullanici = GetByID(id);
if (kullanici!= null)
{
_context.Kullanici.Remove(kullanici);
}
}
public int Count()
{
return _context.Kullanici.Count();
}
public void Save()
{
_context.SaveChanges();
}
}
}
IKullaniciRepository.cs
namespace WebHaber.Core.Infrastructure
{
public interface IKullaniciRepository : IRepository<Kullanici>
{
}
}
IRepository.cs
namespace WebHaber.Core.Infrastructure
{
public interface IRepository<T> where T: class
{
IEnumerable<T> GetAll();
T GetByID(int id);
T Get(Expression<Func<T, bool>> expression);
IQueryable<T> GetMany(Expression<Func<T, bool>> expression);
void Insert(T obj);
void Update(T obj);
void Delete(int id);
int Count();
void Save();
}
}
Kullanici.cs model
namespace WebHaber.Data.Model
{
[Table("Kullanici")]
public class Kullanici
{
public int ID { get; set; }
[Display(Name = "Ad Soyad")]
[MaxLength(150, ErrorMessage = "150 karakterden fazla girildi.")]
[Required]
public string AdSoyad { get; set; }
[Display(Name = "Email")]
[DataType(DataType.EmailAddress)]
[Required]
public string Email { get; set; }
public string KullaniciAdi { get; set; }
[Display(Name = "Şifre")]
[DataType(DataType.Password)]
[Required]
public string Sifre { get; set; }
..............
..............
.............
The issue is pretty straightforward — An error occurred when trying to create a controller of type 'WebHaber.Admin.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.
You're trying to use Autofac to inject IKullaniciRepository service into the AccountController but the compiler couldn't find one although you've the declared the service registration at BootStrapper.cs
Therefore it's likely that BootStrapper.cs's RunConfig never get invoked. Just place a call (e.g. BootStrapper.RunConfig()) to Application_Start() method in Global.asax and you're fine.
#Zephyr thank you for help.
I added new global.asax file.
Because my Application_Start() was not firing.
In global.asax
Old one :
public class MvcApplication : System.Web.HttpApplication
new one: `
public class Global : System.Web.HttpApplication`
I've used StructureMap in MVC2/3 many times without any concern, but I guess handling IoC is different in MVC4.
When i used StructureMap for handling IoC in MVC4 I get the following exception.:
No parameterless constructor defined for this object
Why?
I have not found any correct result in google except this: IoC Not Working In MVC4
These is my IoC classes:
public static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
//scan.Assembly("DLL.Core");
scan.Assembly("DLL.CMS");
scan.TheCallingAssembly();
scan.WithDefaultConventions();
});
x.For<IDbContext>().Use<ModelEntities>();
x.For(typeof(IRepository<>)).Use(typeof(Repository<>));
x.For<IHttpControllerActivator>();
x.For<IController>();
});
return ObjectFactory.Container;
}
And SmDependencyResolver is:
public class SmDependencyResolver : IDependencyResolver
{
private readonly IContainer _container;
public SmDependencyResolver(IContainer container)
{
_container = container;
}
public object GetService(Type serviceType)
{
if (serviceType == null) return null;
try
{
return serviceType.IsAbstract || serviceType.IsInterface
? _container.TryGetInstance(serviceType)
: _container.GetInstance(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.GetAllInstances(serviceType).Cast<object>();
}
}
And my error is:
No parameterless constructor defined for this 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.MissingMethodException: No parameterless constructor defined for this object.
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: No parameterless constructor defined for this
object.] 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.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +67
[InvalidOperationException: An error occurred when trying to create a
controller of type
'Parsian.Web.Areas.Dashboard.Controllers.MemberController'. Make sure
that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext
requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
httpContext, IController& controller, IControllerFactory& factory)
+196 System.Web.Mvc.<>c__DisplayClass6.b__2() +49 System.Web.Mvc.<>c__DisplayClassb1.<ProcessInApplicationTrust>b__a()
+13 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action
action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func1 func)
+124 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
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.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+8862676 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Thanks for correct answers.
oops.I found an emergency solution :) Try to implement a class from IControllerActivator
public class StructureMapControllerActivator : IControllerActivator
{
private IContainer _container;
public StructureMapControllerActivator(IContainer container)
{
_container = container;
}
public IController Create(RequestContext requestContext, Type controllerType)
{
return _container.GetInstance(controllerType) as IController;
}
}
and then register it to the IoC class:
x.For<IControllerActivator>().Use<StructureMapControllerActivator>();
and then enjoy it.
Good luck
If you remove any old configuration for structuremap and install structurmap.mvc4 from nuget then configure your IoC container, you don't have any problems.
try adding this class as your ControllerFactory, I've actually seen the error above in MVC3 and this usually fixed it for me
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
try
{
return (controllerType == null)
? base.GetControllerInstance(requestContext, controllerType)
: ObjectFactory.GetInstance(controllerType) as IController;
}
catch (Exception ex)
{
return null;
}
}
}
Using StructureMap.MVC5.Update I had to do this or else the nested IContainer was already disposed (weird) :
public class StructureMapControllerActivator : IControllerActivator
{
public IController Create(RequestContext requestContext, Type controllerType)
{
return StructuremapMvc.StructureMapDependencyScope.GetInstance(controllerType) as IController;
}
}
i'm creating a database with entity framework, in an mvc asp.net application, using code first.
I'm new to the argument so be patient... I've created the database for the first time and all seems to be right; but couse of i didn't create a DropCreateDatabaseIfModelChanges method to change the tables i decided to manually delete the database.
The problem is that the database is not recreating!
I've implemented the initializer and it is in a different class from the context...
public class WidgetDbInitializer : DropCreateDatabaseIfModelChanges<WidgetDbContext>
{
}
Setted it up in Global.asax.cs and forced to init that
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Database.SetInitializer<Portale.Models.WidgetDbContext>(new Portale.Models.WidgetDbInitializer());
var _initer = new WidgetDbInitializer();
using (var db = new WidgetDbContext())
{
_initer.Seedit(db);
db.Database.Initialize(true);
}
}
I've just the default connection string couse now i don't care about it...
Please help me i've read tons of articles over the web and i can't get a solution...
The error i get:
System.ArgumentNullException non è stata gestita dal codice utente
Message=Il valore non può essere null.
Nome parametro: key
Source=mscorlib
ParamName=key
StackTrace:
in System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
in System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.SortedEntityTypeIndex.Add(EdmEntitySet entitySet, EdmEntityType entityType)
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Analyze()
in System.Data.Entity.ModelConfiguration.Configuration.Mapping.EntityMappingService.Configure()
in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
in System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
in System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
in System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
in System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
in System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
in System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
in System.Data.Entity.Internal.InternalContext.Initialize()
in System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
in System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
in System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
in System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
in System.Linq.Queryable.Join[TOuter,TInner,TKey,TResult](IQueryable`1 outer, IEnumerable`1 inner, Expression`1 outerKeySelector, Expression`1 innerKeySelector, Expression`1 resultSelector)
in Portale.Controllers.WidgetContainerController.Index() in C:\Users\doompro\Documents\Visual Studio 2010\Projects\Portale\Portale\Controllers\WidgetContainerController.cs:riga 56
in lambda_method(Closure , ControllerBase , Object[] )
in System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
in System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
in System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
in System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
InnerException:
override Seed function in your WidgetDbInitializer class and try to add some data to your database .
protected override void Seed(WidgetDbContext context)
{
context.yourodel.add(new class() )
}
first check your overriden seed invoke correctly , then if your database dose not generated you will get an exception .
Solved the problem:
public class Widget
{
//This properties rapresent the primary key for entity framework
[Key]
public int WidgetID { get; set; }
//Foreing key to the column where this widget is stored
public virtual int ColumnID { get; set; }
//The title of the widget
public string Title { get; set; }
//Controller of the Widget, this property may be used on the RenderAction call
public string Controller { get; set; }
//ActionMethod of the Widget, this property may be used on the RenderAction call
public string ActionMethod { get; set; }
//The Type of the Model, used on deserialization
public Type ModelType { get; set; }
//The context of the widget
public string SerializedModel { get; set; }
}
The database just didn't accept the type "Type", all working fine as soon as I deleted that field... I just didn't look at it because it was working with the "Object" type, didn't expect it doesnt with Type..
I've just installed the new Ninject.MVC3 from NuGet and trying to make it work in my asp.net mvc 3 app, however I get this weird error now and then when surfing my site:
[InvalidOperationException: Error loading Ninject component ICache
No such component has been registered in the kernel's component container.
Suggestions:
1) If you have created a custom subclass for KernelBase, ensure that you have properly
implemented the AddComponents() method.
2) Ensure that you have not removed the component from the container via a call to RemoveAll().
3) Ensure you have not accidentally created more than one kernel.
]
Ninject.Components.ComponentContainer.Get(Type component) in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\Components\ComponentContainer.cs:146
Ninject.Components.ComponentContainer.Get() in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\Components\ComponentContainer.cs:102
Ninject.KernelBase.CreateContext(IRequest request, IBinding binding) in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\KernelBase.cs:540
Ninject.<>c__DisplayClassa.<Resolve>b__6(IBinding binding) in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\KernelBase.cs:375
System.Linq.<>c__DisplayClass12`3.<CombineSelectors>b__11(TSource x) +20
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +151
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4178557
Ninject.Web.Mvc.NinjectDependencyResolver.GetService(Type serviceType) in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectDependencyResolver.cs:56
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +51
[InvalidOperationException: An error occurred when trying to create a controller of type 'MyApp.Controllers.NewsController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +196
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
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.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862580
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
And my code is:
// AppStart_NinjectMVC3.cs
using System.Web.Mvc;
using Ninject.Modules;
[assembly: WebActivator.PreApplicationStartMethod(typeof(MyApp.AppStart_NinjectMVC3), "Start")]
namespace MyApp
{
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
public static class AppStart_NinjectMVC3
{
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpApplicationModule));
}
}
}
// NinjectHttpApplicationModule.cs
using MyApp.Data;
using NHibernate;
namespace MyApp
{
using System;
using System.Web;
using Ninject;
using Ninject.Web.Mvc;
public sealed class NinjectHttpApplicationModule : IHttpModule, IDisposable
{
#region Ninject Mvc3 extension bootstrapper (Do not touch this code)
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
private static bool initialized;
private static bool kernelDisposed;
/// <summary>
/// Initializes a module and prepares it to handle requests.
/// Do not change this method!
/// </summary>
/// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param>
public void Init(HttpApplication context)
{
lock (bootstrapper)
{
if (initialized)
{
return;
}
initialized = true;
bootstrapper.Initialize(CreateKernel);
}
}
/// <summary>
/// Disposes the <see cref="T:System.Web.HttpApplication"/> instance.
/// Do not change this method!
/// </summary>
public void Dispose()
{
lock (bootstrapper)
{
if (kernelDisposed)
{
return;
}
kernelDisposed = true;
bootstrapper.ShutDown();
}
}
#endregion
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
RegisterServices(kernel);
return kernel;
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ISession>().ToMethod(x => kernel.Get<SessionFactoryBuilder>().CreateFactory().OpenSession()).InRequestScope();
kernel.Bind<ITransaction>().ToMethod(x => kernel.Get<ISession>().BeginTransaction()).InRequestScope();
kernel.Bind(typeof(IRepositoryBase<>)).To(typeof(RepositoryBase<>));
kernel.Bind<IUnitOfWork>().To<UnitOfWork>();
}
}
}
Most of the code is the default one you get when installing by NuGet.. the only thing I've done is to add some bindings to the RegisterServices()
Any suggestions?
Fixed in 2.2.1.0
See http://www.planetgeek.ch/2011/03/01/ninject-2-2-1-0-and-ninject-mvc3-2-2-1-0-released/ for more information.
Looks like its a bug according to this thread, and that they are working on a fix...
Like previously mentioned it does look like a bug.
One option is to simply implement a singleton extension method yourself:
public static class NinjectSingletonExtension
{
public static CustomSingletonKernelModel<T> SingletonBind<T>(this IKernel i_KernelInstance)
{
return new CustomSingletonKernelModel<T>(i_KernelInstance);
}
}
public class CustomSingletonKernelModel<T>
{
private const string k_ConstantInjectionName = "Implementation";
private readonly IKernel _kernel;
private static object padlock = new Object();
private T _concreteInstance;
public CustomSingletonKernelModel(IKernel i_KernelInstance)
{
this._kernel = i_KernelInstance;
}
public IBindingInNamedWithOrOnSyntax<T> To<TImplement>(TImplement i_Constant = null) where TImplement : class, T
{
_kernel.Bind<T>().To<TImplement>().Named(k_ConstantInjectionName);
var toReturn =
_kernel.Bind<T>().ToMethod(x =>
{
if (i_Constant != null)
{
return i_Constant;
}
if (_concreteInstance == null)
{
lock (padlock)
{
if (_concreteInstance == null)
{
_concreteInstance = _kernel.Get<T>(k_ConstantInjectionName);
}
}
}
return _concreteInstance;
}).When(x => true);
return toReturn;
}
}
And then simply use:
i_Kernel.SingletonBind<T>().To<TImplement>();
Rather then
i_Kernel.Bind<T>().To<TImplement>().InSingletonScope();