Entity Framework SetInitializer and Seed Data - entity-framework-6

Having difficulty figuring out why my database will not seed:
Here is what I have in my Global.asax code:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
Database.SetInitializer(new DataContextInitializer());
DataContext db = new DataContext();
db.Database.Initialize(true);
WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true);
}
and here is the DataContextInitializer:
public class DataContextInitializer : CreateDatabaseIfNotExists<DataContext>
{
protected override void Seed(DataContext context)
{
if (!WebSecurity.Initialized)
{
WebSecurity.InitializeDatabaseConnection("DataContext", "UserModels", "Id", "UserName", autoCreateTables: true);
WebSecurity.CreateUserAndAccount("admin", "12345");
}
var roles = (SimpleRoleProvider)Roles.Provider;
var membership = (SimpleMembershipProvider)Membership.Provider;
if (!roles.RoleExists("admin"))
{
roles.CreateRole("admin");
}
if (membership.GetUser("admin", false) == null)
{
membership.CreateUserAndAccount("admin", "12345");
}
if (!roles.GetRolesForUser("admin").Contains("admin"))
{
roles.AddUsersToRoles(new[] { "admin" }, new[] { "admin" });
}
}
}
While debugging, the SqlException that I get is "There is already an object named ... in the database." Any idea why this would occur?

These are the steps I took:
Copied seed logic to the Migrations Configuration.cs file.
Excluded an old migration from the project
Within package console manager performed add-migration and gave it a name
Then ran update-database -verbose -force AFTER making sure that WebMatrix.WebData reference properties had 'CopyLocal = true'
I hope this helps someone.

Related

How to use Route attribute while working with areas in mvc?

I am working on a project which is having some areas defined in it. I want to use Route attribute to do routing in my project. So I used routes.MapMvcAttributeRoutes() in my route.config file. The following is my route.config file.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Shopper.Controllers" }
);
}
}
After that I am having two areas in my project like productarea and productcategoryarea. I have global.asax file as below.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
I want to give routes to some of the methods from productcategoryarea and productarea. but when i applies Route("productcategories") on one of methods of productcategoryarea it will show me 404 error.
This is my productcategoryregistration.cs file from productcategoryarea
public class ProductCategoryAreaAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "ProductCategoryArea";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"ProductCategoryArea_default",
"ProductCategoryArea/{controller}/{action}/{id}",
new {controller="ProductCategory", action = "ListOfProductCategory", id = UrlParameter.Optional }
);
}
}
This is my method on which i want to provide route attribute.
[Route("productcategories")]
public ActionResult ListOfProductCategory(ProductCategoryManager productcategorymanager, int page = 1, int pageSize = 4)
{
if (Session["UserName"].ToString() != null)
{
if (Session["UserName"].ToString() == "admin")
{
//returning list of product category
List<ProductCategory> listproductcategories = db.ProductCategories.ToList();
PagedList<ProductCategory> model = new PagedList<ProductCategory>(listproductcategories, page, pageSize);
return View(model);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
So please help me to get out of it.

How to use SQL Server in individual login ASP.NET MVC 6

I am working on VS2015 preview and I am stuck somewhere with login.. Like in ASP.NET MVC VS2013 where we can login through SimpleMembershipInializer for e.g.
public SimpleMembershipInitializer()
{
Database.SetInitializer<LoginEntities>(null);
try
{
using (var context = new LoginEntities())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("LoginEntities", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
so I am doing in VS2015 like
public class EBuilderUesr : IdentityUser<string, AspNetUserLogin, AspNetUserRole,AspNetUserClaim>
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<EBuilderUesr> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class AspNetUserRole : IdentityUserRole<string> { }
public class AspNetRole : IdentityRole<string, AspNetUserRole> { }
public class AspNetUserClaim : IdentityUserClaim<string> { }
public class AspNetUserLogin : IdentityUserLogin<string> { }
public class AspNetUser : IdentityUserLogin<string> { }
public class ApplicationDbContext : IdentityDbContext<EBuilderUesr, AspNetRole, string,AspNetUserLogin,AspNetUserRole,AspNetUserClaim>
{
public ApplicationDbContext()
: base("BuilderTrackerEntities")
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
Now into IdentityConfig.cs is
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
//var manager = new ApplicationUserManager(new UserStore<EBuilderUesr>(context.Get<ApplicationDbContext>()));
var manager = new ApplicationUserManager(new UserStore<EBuilderUesr, AspNetRole, string, AspNetUserLogin, AspNetUserRole, AspNetUserClaim>(context.Get<ApplicationDbContext>()));
}
getting error on above ApplicationUserManager..?
I have changed connection string in Config file also but still an getting error like..
Please let me know. what I am going to wrong..?
Thank you,
_jitendra

MVC 4 View engine search locations

I have implemented mcfea answer on the bottom of this post but it is not working.
Adding sub-directory to "View/Shared" folder in ASP.Net MVC and calling the view
I have a subfolder under Views/Shared called Timesheet.
This the exception.
The view 'Timesheet' or its master was not found or no view engine
supports the searched locations. The following locations were
searched: ~/Views/Home/Timesheet.aspx ~/Views/Home/Timesheet.ascx
~/Views/Shared/Timesheet.aspx ~/Views/Shared/Timesheet.ascx
~/Views/Home/Timesheet.cshtml ~/Views/Home/Timesheet.vbhtml
~/Views/Shared/Timesheet.cshtml ~/Views/Shared/Timesheet.vbhtml
Malcolm
public class MylesterViewEngine : RazorViewEngine
{
private static readonly string[] NewPartialViewFormats =
{
"~/Views/{1}/Timesheet/{0}.cshtml",
"~/Views/Shared/Timesheet/{0}.cshtml"
};
private static List<string> AreaRegistrations;
public MylesterViewEngine()
{
AreaRegistrations = new List<string>();
BuildAreaRegistrations();
base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(AreaRegistrations).ToArray();
}
private static void BuildAreaRegistrations()
{
string[] areaNames = RouteTable.Routes.OfType<Route>()
.Where(d => d.DataTokens != null && d.DataTokens.ContainsKey("area"))
.Select(r => r.DataTokens["area"].ToString()).ToArray();
foreach (string areaName in areaNames)
{
AreaRegistrations.Add("~/Areas/" + areaName + "/Views/Shared/Timesheet/{0}.cshtml");
AreaRegistrations.Add("~/Areas/" + areaName + "/Views/{1}/Timesheet/{0}.cshtml");
}
}
}
protected void Application_Start()
{
//AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MylesterViewEngine());
//var unityContainer = ModelContainer.Instance;
//DependencyResolver.SetResolver(new UnityDependencyResolver(unityContainer));
Bootstrapper.Initialise();
}
EDIT 2: Even this doesnt work
protected void Application_Start()
{
//AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
RazorViewEngine razorEngine = ViewEngines.Engines.OfType<RazorViewEngine>().FirstOrDefault();
if (razorEngine != null)
{
string[] newPartialViewFormats = new[] {
"~/Views/{1}/Timesheet/{0}.cshtml",
"~/Views/Shared/Timesheet/{0}.cshtml"
};
razorEngine.PartialViewLocationFormats =
razorEngine.PartialViewLocationFormats.Union(newPartialViewFormats).ToArray();
}
//ViewEngines.Engines.Clear();
//ViewEngines.Engines.Add(new MylesterViewEngine());
//var unityContainer = ModelContainer.Instance;
//DependencyResolver.SetResolver(new UnityDependencyResolver(unityContainer));
Bootstrapper.Initialise();
}
The answer you linked to was for specifically returning partial views, not main views. So the code inside it says something like this:
string[] NewPartialViewFormats =
{
"~/Views/{1}/Timesheet/{0}.cshtml",
"~/Views/Shared/Timesheet/{0}.cshtml"
};
base.PartialViewLocationFormats =
base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
Notice that it uses the PartialViewLocationFormats property. If you want to use this method for all views, you should also add your formats to the ViewLocationFormats property:
string[] NewPartialViewFormats =
{
"~/Views/{1}/Timesheet/{0}.cshtml",
"~/Views/Shared/Timesheet/{0}.cshtml"
};
//Add to partial views
base.PartialViewLocationFormats =
base.PartialViewLocationFormats.Union(NewPartialViewFormats).ToArray();
//Add to main views
base.ViewLocationFormats =
base.ViewLocationFormats.Union(NewPartialViewFormats).ToArray();
If you passing under subfolder than need to pass full cshtml page path. If you don't want provide full path than simple add page under Shared folder.

Access asp.net mvc controller ActionResult

i want to access action result in controller(my controlelr is HotelController action is Index)
(http://localhost:9001/Hotel/Index) it gives below error
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Hotel/Index
Hotel controller
public class HotelController : Base.BoxyController
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
ViewBag.Title = "SonDakka - Otel";
}
public ActionResult Index(string culture)
{
.........
BoxyController
public class BoxyController : MainController
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
..........
MainController
public class MainController : SiteController
{
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
......
SiteController
[ExitHttpsIfNotRequired]
public class SiteController : Controller
{
public Account Me { get; set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
.......
and this is my global.asax
using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Tourism.Data;
using Tourism.Data.Mvc.Authorization;
using Tourism.Data.Mvc.Routing;
namespace Tourism
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(TourismContext db, RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
var cultures = db.Cultures.Select(c => c.Code).ToArray();
routes.MapRoute
(
"Ajax",
"{culture}/{controller}/{action}/{id}",
new { id = UrlParameter.Optional },
new { culture = new ArrayRouteConstraint(true, cultures), controller = new ArrayRouteConstraint(true, "Ajax") }
).RouteHandler = new GlobalizedRouteHandler();
routes.Add
(
"Page",
new GlobalizedPageRoute
(
"{culture}/{path}",
null,
new RouteValueDictionary { { "culture", new ArrayRouteConstraint(true, cultures) } },
new GlobalizedRouteHandler()
)
);
routes.Add
(
"Route",
new GlobalizedRoute
(
"{culture}/{path}/{slug}/{id}",
new RouteValueDictionary { { "culture", UrlParameter.Optional }, { "path", UrlParameter.Optional }, { "slug", UrlParameter.Optional }, { "id", UrlParameter.Optional } },
new RouteValueDictionary { { "culture", new ArrayRouteConstraint(false, cultures) } },
new GlobalizedRouteHandler()
)
);
}
protected void Application_Start()
{
Database.SetInitializer<TourismContext>(null);
using (var db = new TourismContext())
{
#if !DEBUG
if (!db.Database.CompatibleWithModel(true))
{
System.Web.HttpRuntime.UnloadAppDomain();
throw new Exception("Veritabanı değişikliği tespit edildi.");
}
#endif
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(db, RouteTable.Routes);
}
}
protected void Application_PostAuthenticateRequest()
{
if (Request.IsAuthenticated)
{
Context.User = System.Threading.Thread.CurrentPrincipal =
new AuthorizationPrincipal(Context.User.Identity);
}
}
}
}
Because this is due to Razor engine unable to find Thanks action in Hotel controller. You need to make a Thanks action with in Hotel controller like this:
public class HotelController : Base.BoxyController
{
public ActionResult Thanks(string culture)
{
return View();
}
}
And also make sure to create a view in Hotel folder with your html code.
Based on the route config you posted, your URL should be with culture, for example:
http://localhost:9001/en/Hotel/Index
Notice the en before Hotel. It could be any value that is valid in your database.

SQL CE 4 System.Transaction support

A similar question was asked here but had no answer.
I am attempting to use a System.Transactions.CommittableTransaction with EF CTP4 and SQL CE 4.
I have created the following transaction attribute for my ASP.NET MVC Controller actions:
public class TransactionAttribute : ActionFilterAttribute
{
CommittableTransaction transaction;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
transaction = new CommittableTransaction();
Transaction.Current = transaction;
base.OnActionExecuting(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
try
{
var isValid = filterContext.Exception == null || filterContext.ExceptionHandled;
if (filterContext.Controller.ViewData.ModelState.IsValid && isValid) {
transaction.Commit();
} else {
transaction.Rollback();
Transaction.Current = null;
}
}
finally
{
transaction.Dispose();
}
}
}
When I use this filter I get the error:
System.InvalidOperationException: The connection object can not be enlisted in transaction scope.
However, the following test passes:
[Test]
public void Transaction_rolls_back_if_exception()
{
var transaction = new CommittableTransaction();
Transaction.Current = transaction;
try
{
var project = new Project { Title = "Test" };
projectRepo.SaveOrUpdate(project);
context.SaveChanges();
var post = new Post { Title = "Some post" };
blogRepo.SaveOrUpdate(post);
throw new Exception();
context.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
Transaction.Current = null;
}
projectRepo.GetAll().Count().ShouldEqual(0);
blogRepo.GetAll().Count().ShouldEqual(0);
}
Has this something to do with how I am initializing the DbContext?
I ran into this same issue. You cannot use Transactions with the CE Connection. I ended up having my datacontext manage my ce connection and implementing a unit of work pattern to hold my actions, then executing all the scheduled actions inside a SqlCeTransaction then calling commit or rollback myself.
http://msdn.microsoft.com/en-us/library/csz1c3h7.aspx

Resources