I created a visual studio 2012 MVC4 App. I am testing the "publish" functionality by right clicking the project and choosing publish. I followed the instructions here. I can connect to the remote web server and the folders get published to the correct folder, except the content folder for some reason.
When I run browse to the remote web server it prompts me for login so the app is working. However, the migrations never happened. The only tables created are the simplemembership tables, so I know the web server is connecting to the remote db server. No other tables are created and the seed method doesn't run. I seed the roles and a default user.
I checked the box in publish settings that says "Execute Code First Migrations (runs on application start)"
Everything works fine on my localdb connection string for local testing. Just can't figure out how to create db from existing migrations and seed when I publish to live site, note I will only seed once. Is there a way to specify which migrations to run again? I can copy the migrations and run on the database server but why the extra step?
EDIT:
When adding the database.setinilizer to my context I now get an error saying some of my fields in my userprofile table are not there, I use simple membership. This error occurs on the first page load after web publish, then on proceeding page loads I get an error The "WebSecurity.InitializeDatabaseConnection" method can be called only once.
HOwever, it does create my simplemembership tables now but my migration for all other tables never runs, that is why I am missing the additional user profile fields.
EDIT:
Basically I am not checking if websecurity is initialized prior to calling WebSecurity.InitializeDatabaseConnection so that resolved that issue. Now I have it partially working. The app creates the simplemembership tables fine but since I added tables to the UserProfile table I can't seed until I change them. So instead I manually create the userprofile table and have the app create the rest of the tables. Then I comment out the userprofile table in my initial migration. After this when I sign in it will then create the rest of my tables.
Open issue is how to get my database migration to run prior to the simplemembership initialization?
To get migration work on remote server, you need to add use SetInitializer in you Context class first :
static MyDatabaseContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyProjectContext, Migrations.Configuration>());
}
And in you Migration Configuration you need to add this code :
public Configuration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
}
I don't select the "Execute Code First Migrations (runs on application start)", and just after setting initialization in MyProjectContext, it does the migration for me.
If you have done by here, for seed your data, you can do same as below in your Migration configuration class:
protected override void Seed(MyProject.Models.MyProjectContextcontext)
{
DoSeed(context);
}
private void DoSeed(MyProjectContext context)
{
var users = new List<User>
{
new Site { UserId = 1, Name = "TestUser", IsDeleted = false },
new Site { UserId = 2, Name = "TestUser2", IsDeleted = false }
};
users.ForEach(s => context.Users.AddOrUpdate(s));
context.SaveChanges();
}
I have not selected the "Execute Code First Migrations (runs on application start)" on deploy Profile.
For some more details on this see this:
This link
and
This link
Hope this helps(as it worked for me), otherwise please add any error if there is, when you deploy you app.
I think the issue is ,Because of the fact that as long as you have not tried to access data
or create any data from/in site, which needs to connect to database, the migration and seeding
will not run"
And the reason for running migration on your site after logging into the site,
would be because your site need to be authorised in all pages, or the page that you want
to see data in.
If you have a page example home page, that does not authorization to access to the page,
you will see the page and if in this page there is some data that needs to be fetched from
data base, you may see the migration runs.
I found this from this Deploy it to IIS, but not sure if it is the reason.
Please let me know if your migration still has not ran if you browse your home page that
has data and no authentication needed for this data access.
Related
I am trying to set up a log in page on my ASP.NET MVC site. I have a working database that stores all the data needed for my site. When I started my site, I used the base template in visual studio because I wanted a basic layout so I could get right into displaying the data I needed and then I could go back later and change the styling. This template created a log in page, which works but I need it to store the tables in my existing database, not a new database. When I register a user it creates a database on my local db server named "aspnet-KU_PLAN_DEV-20140909071149". I need it to store these tables in my "KuPlan" database on my local db server. In my application, my connection string in my web.config file is named "KuPlanEntities" and my model is named "KuPlan.edmx". I can't figure out why it still creates this new database for the tables needed for authentication/security and would appreciate any tips/help that will help me store them in my current database.
Thank you.
Go to Model Folder -> IdentityModel.cs
Change
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
To
public ApplicationDbContext()
: base("KuPlanEntities", throwIfV1Schema: false)
{
}
Actually in my web project i am using logger concept to save user operations. it is working but my where i am facing the problem is when a user-A is loggedin means it is saving properly his operations in database but at the same time when another user-B is logged in means it is overlaping the information by saving User-B with User-A Details in database. is there any solution. below is my sample code
GlobalDiagnosticsContext.Set("PageViewed", "mInbox Page");
GlobalDiagnosticsContext.Set("PageType", "Mob");
GlobalDiagnosticsContext.Set("TimeStamp", DateTime.Now.ToString());
GlobalDiagnosticsContext.Set("UserId", Session["UserID"].ToString());
logger.Info("*** mInbox Page ***");
I have a site built using MVC4 which is getting content out of a database and it all works fine.
If I then rebuild the solution and try to refresh the page to check my changes, I will always get the SQL Network Interfaces, error: 26 saying that I cannot connect to the server.
However, if I then browse to my homepage and then back to the page I was looking at it will work fine.
Does anyone know what could cause this problem as it is really annoying
EDIT
Further to this I have found it is when the AuthorizationContext filterContext is being loaded after the rebuild that it cannot connect to the db
EDIT 2
As with neil below I have found that I only get the problem if I try to access a page that has had a role assigned to it
I'm seeing the exact same problem and can trace it to the .ASPXAUTH session cookie in the browser. Delete that cookie and the database error goes away until the next rebuild.
The error occurs regularly if you are authenticated and then rebuild the project and try to browse any page that either:
Requires authentication
Makes a call to the User object (e.g. #if (User.IsInRole("Administrators")))
If you have the AuthorizeAttribute filter set in App_Start/FilterConfig.cs you'll get this on every page.
This seems to be new behavior following the most recent Patch Tuesday updates. Previously, I was seeing weird behavior where I would remain logged in but I would loose my roll membership. After the most recent patches, it seems Simple Membership chokes when it gets a bad .ASPXAUTH cookie (invalid because of the rebuild).
I've got the correct connection string in InitializeSimpleMembershipAttribute.cs but it's like Simple Membership is defaulting to something else in this one instance.
Note that I've moved the Simple Membership databases from the original (localDb) to a full-fledged (local) SQL Server instance. Don't know why that would matter, and it works fine in all other cases.
Update:
I've also tried making the connection string name the same as the EF context name (e.g. "ProjectContext") on the theory that it is defaulting to the standard convention, but that made no difference. I am explicitly identifying the connection string name in all my context class constructors (using the : base("connectionString") syntax) and Simple Membership is able to find the right connection string all other times.
Update 2:
The problem only occurs after rebuild when accessing a page protected by role. A simple [Authorize] won't trigger it. You need something like [Authorize(Role="Admin")]. I've replicated this on a new MVC 4 project with no other modifications, using the default (localDb) database. Clear the cookie and that same user can access the protected content w/o any problems. I believe this is a core .NET or MVC bug and needs to be reported as such.
This happened to me while rebuilding the application when I was logged in the browser.
Deleting cookies fixed the problem for me.
When using SimpleMembership, this bug occurs with any use of Roles-not just in the controller, but also when I use:
if(Roles.IsUserInRole(rolename){...
I am late to the game with this answer, but I added [InitializeSimpleMembership] to my home controller and I think that fixed it.
I need a little help getting started. I have a new JSF-2 web application that I intend to deploy under GlassFish 3.1 (or higher). Normally the server stores all its log files as text in one of its private directories, which also includes the logging I do with ether System.println( .. ) or something like java.util.logging.Logger.getLogger( ... )
What I want to do is instead of those logging entries going to the text file, capture them and file them into my SQL data base. I can then add table columns for timestamp and key values so it can be easily searched as part of the admin web page in the application, rather than having to go to the admin console for it. It would be possible also to expose some of that data to users.
Can this be done and how?
Follow up question: could this be done in a way that would be portable to Tomcat or another container?
You will need to write custom log handler. Custom log handler is a class that extends java.util.logging.Handler:
package test.stackoverflow;
import java.util.logging.Handler;
..
public class AlanHandler extends Handler {
..
#Override
public void publish(LogRecord record) {
//CODE THAT STORES LOG RECORD INTO THE DATABASE
}
}
Additionally, you will have to slightly change logging.properties file:
handlers=java.util.logging.ConsoleHandler, test.stackoverflow.AlanHandler
Deploy JAR of AlanHandler on Glassfish (as a library), restart the server and that should do it.
Using Entity Framework Migrations (Beta1), using Update-Database command is all good during development.
But when the application is running on some customer's server somewhere, I really want my application to automatically update it's database schema to the latest version when it's started.
Is this possible? Documentation is scarce.
They aren't providing a way to do this until RTM, at which point they have promised a command line app and a msdeploy provider.
Source: http://blogs.msdn.com/b/adonet/archive/2011/11/29/code-first-migrations-beta-1-released.aspx
Of course not being satisfied with that, the powershell command is stored in the packages directory and is plain text, it appears to just load up an assembly called EntityFramework.Migrations.Commands stored in the same directory.
Tracing through that assembly I came up with the following
public class MyContext : DbContext
{
static MyContext()
{
DbMigrationsConfiguration configuration = new DbMigrationsConfiguration() {
MigrationsAssembly = typeof(MyContext).Assembly,
ContextType = typeof(MyContext),
AutomaticMigrationsEnabled = true,
};
DbMigrator dbMigrator = new DbMigrator(configuration);
dbMigrator.Update(null);
}
}
UPDATE: after a bit of experimentation I figured out a few more things
Performing an update in the static constructor for your context is bad as it breaks the powershell commands, much better off adding the code to application startup another way (Global.asax, WebActivator or Main method)
The above code only works when using AutomaticMigrations, you need to set the MigrationsNamespace for it to pickup on manually created migrations
The configuration class I was creating should already exist in your project (added when you install the migration nuget package), so just instantiate that instead.
Which means the code is simplified to
DbMigrator dbMigrator = new DbMigrator(new NAMESPACE.TO.MIGRATIONS.Configuration());
dbMigrator.Update(null);
Another options for this issue is to add
Database.SetInitializer<MyContext>(new MigrateDatabaseToLatestVersion<MyContext, NAMESPACE.TO.MIGRATIONS.Configuration>());
line to your Global.asax Application_Start method.