Entity Framework doesn't create Database - asp.net-mvc

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..

Related

How do I include a [NotMapped] property in an EF business object without getting FirstChance IndexOutofRangeException?

I was wondering why my XAF WinForms EF application was slow loading a detail view.
Then I learned how to capture FirstChance Exceptions and discovered I was experiencing an IndexOutOfRange exception as described here
Sometimes I want to include a non mapped property in my business object such as Job in example.
public class OrderLineResult
{
public int LineId { get; set; }
public int Quantity { get; set; }
public string Description { get; set; }
[Browsable(false)] public int JobId { get; set; }
[NotMapped] [Browsable(false)] public virtual Job Job { get; set; }
}
And I have a method to get the data inside the OrderLineResult class
public static OrderLineResult[] GetData(int headId)
{
using var connect = new MyDbContext()
const string sql =
#"SET NOCOUNT ON;
create table #temp( JobId int, Quantity int, LineId int, Description )
/* code to populate the table */
select JobId,LineId,Quantity, Description from #temp"
var results = connect.Database.SqlQuery<OrderLineResult>(sql,headId).ToArray();
return results.ToArray();
}
}
Yet the IndexOutOfRange exception occurs for the Job property.
The call stack is
System.IndexOutOfRangeException
Job
at MyApp.Module.Win.Controllers.ToDoList.TaskActionController.<>c.<actExceptions_Execute>b__34_0(Object sender, FirstChanceExceptionEventArgs e)
at System.Data.ProviderBase.FieldNameLookup.GetOrdinal(String fieldName)
at System.Data.SqlClient.SqlDataReader.GetOrdinal(String name)
at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.TryGetColumnOrdinalFromReader(DbDataReader storeDataReader, String columnName, Int32& ordinal)
at System.Data.Entity.Core.Query.InternalTrees.ColumnMapFactory.CreateColumnMapFromReaderAndClrType(DbDataReader reader, Type type, MetadataWorkspace workspace)
at System.Data.Entity.Core.Objects.ObjectContext.InternalTranslate[TElement](DbDataReader reader, String entitySetName, MergeOption mergeOption, Boolean streaming, EntitySet& entitySet, TypeUsage& edmType)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass186_0`1.<ExecuteStoreQueryReliably>b__1()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass186_0`1.<ExecuteStoreQueryReliably>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably[TElement](String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery[TElement](String commandText, ExecutionOptions executionOptions, Object[] parameters)
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at MyApp.Module.BusinessObjects.NonPersistedBusinessObjects.OrderLineResult.GetData(Int32 headId)
I am using EntityFramework 6.4.4 and .Net Framework 4.7.2
This feels like a cludge,
I added
,null as job
to the last select statement

Service provider exception on registering a user manager for a template user

I am learning ASP .NET Core and today I have stumbled across something. I have User class which inherits IdentityUser and adds some custom fields, such as first name, last name, etc...
The User class is further extended by other types of users, which only add one or two extra fields, at most. I have decided to take this route as it was unnecessary to repeat the same code in 4 places.
I have defined a UserRepository which implements an interface IUserRepository<TEntity> where TEntity : User. Whenever I try to access the Index, I get an exception like:
InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[HM.models.users.Medic]' has been registered.
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<T>(IServiceProvider provider)
HM.repositories.UserRepository<TEntity>..ctor(ApplicationDbContext context, IServiceProvider serviceProvider, string role) in UserRepository.cs
+
_userManager = serviceProvider.GetRequiredService<UserManager<TEntity>>();
HM.repositories.MedicRepository..ctor(ApplicationDbContext context, IServiceProvider serviceProvider) in MedicRepository.cs
+
public MedicRepository(ApplicationDbContext context, IServiceProvider serviceProvider) : base(context, serviceProvider, _role) { }
HM.persistence.UnitOfWork..ctor(ApplicationDbContext context, IServiceProvider _serviceProvider) in UnitOfWork.cs
+
Medics = new MedicRepository(_context, _serviceProvider);
app.Controllers.MedicController.Index() in MedicController.cs
+
using (var unitOfWork = new UnitOfWork(_context, _serviceProvider))
Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor+TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Routing.EndpointRoutingMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Those are some code snippets:
MedicController:
// GET: Medic
public async Task<IActionResult> Index()
{
using (var unitOfWork = new UnitOfWork(_context,_serviceProvider))
{
return View(await unitOfWork.Medics.GetAll());
}
}
UserRepository and IUserRepository:
public interface IUserRepository<TEntity> where TEntity : User
{
Task Add(TEntity user, string password);
Task Remove(TEntity user);
Task Update(TEntity user);
Task<IEnumerable<TEntity>> GetAll();
Task<TEntity> GetById(string id);
Task<bool> Any(Func<TEntity, bool> predicate);
}
public class UserRepository<TEntity> : IUserRepository<TEntity> where TEntity : User
{
private readonly string _role;
private readonly UserManager<TEntity> _userManager;
public UserRepository(ApplicationDbContext context, IServiceProvider serviceProvider, string role)
{
_role = role;
_userManager = serviceProvider.GetRequiredService<UserManager<TEntity>>();
}
public async Task<IEnumerable<TEntity>> GetAll()
{
return await _userManager.GetUsersInRoleAsync(_role);
}
}
Finally, the medic:
[Table("Medic")]
public class Medic : User
{
[DisplayName("Departments")]
public ICollection<MedicDepartment> departments { get; set; }
[DisplayName("Diagnostics")]
public ICollection<MedicDiagnostic> diagnostics { get; set; }
[PersonalData]
[DisplayName("Rank")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "The rank name must be between 3 and 30 characters long!")]
public string rank { get; set; }
}
I have debugged the application: it will throw this exception at _userManager = serviceProvider.GetRequiredService<UserManager<TEntity>>(); inside UserRepository. I don't understand why this hapens since
I have clearly stated where TEntity : User.
Thanks!
P.S. I have removed some code and some emthods to make this post more redable.
P.S.S: The MedicRepository class extends UserRepository and calls base and contains, for now, nothing else. The UnitOfWork contains all the application repositories and calls new on each one of them inside its contructor.
P.S.S.S. I wanted to use templates for this repository in order to avoid casting inside controllers. It used to return 'User' related data.
I figured it out. It was not enough to register a service for UserManager<User>, but I also had to register a UserManager for each type of user which inherited User.
First, I added those lines to Startup.cs inside ConfigureServices. This used IdentityCore instead Identity.
services.AddIdentityCore<Medic>() //add the derived user type from custom user
.AddRoles<IdentityRole>()
.AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<Medic, IdentityRole>>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddDefaultUI();
Secondly, don't forget to add the managers. Same as before, in the same file and method, add:
services.AddScoped<UserManager<User>, UserManager<User>>(); //the user manager for the base type of User
services.AddScoped<UserManager<Medic>, UserManager<Medic>>(); //the user manager for Medics
Hope it helps!

MVC project No parameterless constructor defined for this object

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`

Override ItemController in Custom Module in Orchard

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?

Html.Serialize return NullReferenceException

I have an ViewModel like
namespace ViewModel
{
[Serializable]
public class TestViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
Also, I have one action method:
public ActionResult Index()
{
TestViewModel model = new TestViewModel
{
Id = -1,
Name = "Some name",
Description = "Some description"
};
return View(model);
}
And my View something like this:
#using Microsoft.Web.Mvc
#model ViewModel.TestViewModel
#using (Html.BeginForm())
{
Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned);
//....Editor fields
}
In line "Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned);" debugger is stopped and returns exception "object reference not set to an instance of an object" (NullReferenceException). Although, the Model is not null and contains initial values.
I use ASP.Net MVC 3(Razor) and stack trace is below:
in Microsoft.Web.Mvc.SerializationExtensions.SerializeInternal(HtmlHelper htmlHelper,
String name, Object data, SerializationMode mode, Boolean useViewData, MvcSerializer
serializer)
in Microsoft.Web.Mvc.SerializationExtensions.SerializeInternal(HtmlHelper htmlHelper,
String name, Object data, SerializationMode mode, Boolean useViewData)
in Microsoft.Web.Mvc.SerializationExtensions.Serialize(HtmlHelper htmlHelper, String
name, Object data, SerializationMode mode)
in ASP._Page_Views_Wizard_Index_cshtml.Execute()
in c:\Projects\TestProject\Views\Wizard\Index.cshtml:line 15
in System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
in System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
in System.Web.WebPages.StartPage.RunPage()
in System.Web.WebPages.StartPage.ExecutePageHierarchy()
in System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext,
TextWriter writer, WebPageRenderingBase startPage)
in System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer,
Object instance)
in System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter
writer)
in System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
in System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext
controllerContext, ActionResult actionResult)
in System.Web.Mvc.ControllerActionInvoker.
<>c__DisplayClass1c.InvokeActionResultWithFilters>b__19()
in System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter,
ResultExecutingContext preContext, Func`1 continuation)
What's wrong in my code?
You need to use
#Html.Serialize("model", Model, SerializationMode.EncryptedAndSigned)
if you want hidden field with model on form.
The problem was that I had assembly reference to Mvc2Futures ("Microsoft.Web.Mvc.dll"). But when I changed the reference to Mvc3Futures ("Microsoft.Web.Mvc.dll") all work fine.
Thanks a lot.

Resources