Error after updgrading from EF 5 to EF 6.0.2 - c#

After upgrading from EF 5 to EF 6.0.2 I'm getting this error when executing the Update-Database command from the Package Manager Console:
Could not load file or assembly 'System.Web.Helpers, Version=3.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies. The system cannot find the file specified.
Everything worked just fine before the upgrade.
This is my app.config:
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.;Initial Catalog=aspnet-CodeFirst-Test;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<qualifyAssembly partialName="WebMatrix.WebData" fullName="WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
This is my Configuration.cs file:
public Configuration()
{
Database.SetInitializer<DataContext>(new DropCreateDatabaseAlways<DataContext>());
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(DataContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
SeedMembership(context);
}
I read that SimpleMembershipProvider got 'replaced' with Identity. Not sure if that is related to this error. But if anyone knows a tutorial how to do the migration, I'd love to have a link of that.
Also the database layer is a class lib project. There is no MVC installed in there.

Try adding this to your web.config under runtime section:
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
And System.Web.Helpers should be referenced from your project as well

Related

Facing issue in connecting oracle with entity frameowrk

I am using Oracle 11g and Entity Framework 6 versions.
I am facing the following error:
"An error occurred while getting provider information from the
database. This can be caused by Entity Framework using an incorrect
connection string. Check the inner exceptions for details and ensure
that the connection string is correct."
My App.Config is as follows:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
<section name="oracle.manageddataaccess.client"
type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
<connectionStrings>
<clear/>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client"
connectionString=" Data Source=HRFOLATEST1;User ID=hrms2;Password=hrms2;"/>
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
<provider invariantName="Oracle.ManagedDataAccess.Client"
type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</providers>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="Oracle.ManagedDataAccess.Client"/>
<add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver"
type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<publisherPolicy apply="no"/>
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral"/>
<bindingRedirect oldVersion="4.121.0.0 - 4.65535.65535.65535" newVersion="4.121.2.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
My Db Context:
class DatabaseContext : DbContext
{
public DatabaseContext() : base("OracleDbContext")
{
}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//Configure domain classes using modelBuilder here
modelBuilder.Entity<User>().ToTable("HRMS_OLAS_TREE");
modelBuilder.Entity<User>().Property(user => user.ID).HasColumnName("EMP_ID").HasColumnType("VARCHAR");
modelBuilder.Entity<User>().Property(user => user.NAME).HasColumnName("EMP_NAME").HasColumnType("VARCHAR");
base.OnModelCreating(modelBuilder);
}
}
internal class User
{
public long ID { get; set; }
public string NAME { get; set; }
}
Please let me now what mistake i am doing.
I have changed the connection string to the following and it started working:
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client"
connectionString=" Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname)(PORT=yourportnumber))(CONNECT_DATA=(SERVICE_NAME=""servicename))); User Id=xxx;Password=xxxx;"/>
we can find these details in tnsnames.ora file.
In Db Context add the following code:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema("yourschemaName");
modelBuilder.Configurations.Add(new EmployeeMapper());
}

Inserting a new record updates LocalDB but not SQL server DB

I'm following MVC-Movies tutorial here , and I'm trying to update the records on SQL Server
and NOT on LocalDB .
When I add a new record in my program , for example :
The DB in SQL Server is not updated , only the LocalDB is .
Here is Web.config :
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection"
connectionString="Data Source=localhost;
AttachDbFilename=|DataDirectory|\aspnet-MvcMovie-20140418101450.mdf;
Initial Catalog=aspnet-MvcMovie-20140418101450;Integrated Security=True"
providerName="System.Data.SqlClient" />
<add name="MovieDBContext"
connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\Movies.mdf;
Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthenticationModule" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
Where did I go wrong ?
Name of my DB in sql server is : MoviesDB
Thanks
EDIT:
Class Movie and MovieDBContext :
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace MvcMovie.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}
EDIT 2 :
I changed the connection string to
<add name="MovieDBContext"
connectionString="Data Source=localhost;
AttachDbFilename=|DataDirectory|\Movies.mdf;
Initial Catalog=MoviesDB;
Integrated Security=True"
providerName="System.Data.SqlClient" />
But then I get this :
Server Error in '/' Application.
Invalid value for key 'attachdbfilename'.
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.ArgumentException: Invalid value for key 'attachdbfilename'.
Source Error:
Line 18: public ActionResult Index()
Line 19: {
Line 20: return View(db.Movies.ToList());
Line 21: }
Line 22:
Source File: c:\Users\X3\Documents\Visual Studio 2013\Projects\MvcMovie\MvcMovie\Controllers\MoviesController.cs Line: 20
Neither one of your connection strings there are referencing MoviesDB.
One is referring to aspnet-MvcMovie-20140418101450.mdf and the other Movies.mdf.
Your context will use the connection string that matches it's name, unless you override that setting. So you should modify the MovieDBContext connection string to point to your SQL instance instead of the LocalDB
Edit
I assume that this is similar to the connection string you actually want, but you should refer to the official Microsoft Reference for other examples.
<add name="MovieDBContext" providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MoviesDB;
Integrated Security=True"/>
Change to :
<add name="MovieDBContext"
connectionString="Data Source=localhost;
AttachDbFilename=|DataDirectory|\MoviesDB.mdf;
Initial Catalog=MoviesDB;
Integrated Security=True"
providerName="System.Data.SqlClient" />

EF 6 with System.Data.SQlite SaveChanges() not working?

So I just started using System.Data.Sqlite with entity framework 6 (downloaded the latest System.Data.Sqlite from Nuget, version 1.0.91.0)
After some configuration and code, I found out that I can read from the database but somehow write is not working.
Here's my code:
using (var context = new InternalDbContext())
{
var demo = context.DemoEntities.Where(d => d.ID == 1).FirstOrDefault();
demo.Name = "TestTest";
context.DemoEntities.Add(new Demo { Name = "Test" });
context.SaveChanges();
}
Basically after SaveChanges, nothing was updated in the DB. However I can read fro the DB with the data I manually populated via SQlite admin tool.
Here's my DB schema:
Table name :Demo
Field: ID - Integer Primary Key AutoIncrement
Field: Name - VARCHAR(256)
Here's my classes
public class InternalDbContext : DbContext
{
public DbSet<Demo> DemoEntities { get; set; }
public InternalDbContext()
{
// Turn off the Migrations, (NOT a code first Db)
Database.SetInitializer<InternalDbContext>(null);
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Database does not pluralize table names
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
[Table("Demo")]
public class Demo
{
public long ID { get; set; }
public string Name { get; set; }
}
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net">
<arg key="configType" value="FILE-WATCH" />
<arg key="configFile" value="log4net.config" />
</factoryAdapter>
</logging>
</common>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.2.13.0" newVersion="1.2.13.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
</entityFramework>
<connectionStrings>
<add name="InternalDbContext" connectionString="Data Source=.\testdb.sqlite" providerName="System.Data.SQLite.EF6" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider" invariant="System.Data.SQLite.EF6" description="Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
</DbProviderFactories>
</system.data>
</configuration>
If anyone could point me to the right direction, that'd be fantastic, thanks so much
Nick
Your ./bin/Debug/ folder should contain a copy of your testdb.sqlite DB. That should have the changes.

MySql exception with EF5 and Winform

I'm trying to create a MySql Db with EF5 , so I have my dbSet and My SqlContext class, but when I run the program throws this exception
I have this code in my App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient"/>
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory,MySql.Data, Version=6.7.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="ConnectionStringName" connectionString="server=localhost;Database=auth;uid=root;pwd=1234;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.7.4.0" newVersion="6.7.4.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
and MySqlContext.cs
public class MySqlContext : System.Data.Entity.DbContext
{
public System.Data.Entity.DbSet<LoginModel> LoginModel { get; set; }
//public System.Data.Entity.DbSet<Roles> Roles { get; set; }
public MySqlContext()
: base("ConnectionStringName")
{ }
}
I'm using Entity Framework 5 , MySqlConector 6.7.4.0, Visual Studio 2012. Hope you guys can help me with this!
I found the answer with the post that user2453734 pointed EF5 Getting this error message: Model compatibility cannot be checked because the database does not contain model metadata and made a changes in the SetInitializer in Program.cs and I changed
this:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MySqlContext>());
into this:
Database.SetInitializer<MySqlContext>(new DropCreateDatabaseIfModelChanges<MySqlContext>());
now it works!

Logged in users get logged out after some time

I made a new MVC3 application and it's hosted on WinHost's basic plan.
The gist of the problem is, the app pool memory limits are reached and every session InProc is erased, meaning my users are logged out.
As per their documentation, I see this:
http://support.winhost.com/KB/a626/how-to-enable-aspnet-sql-server-session-on-your-web.aspx
Here is the contents of my web.config after following the steps outlined above:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<connectionStrings>
<!-- REMOVED FOR PRIVACY -->
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<sessionState mode="SQLServer"
allowCustomSqlDatabase="true"
cookieless="false"
timeout="2880"
sqlConnectionString="data Source='tcp:s407.winhost.com';database='DB_41_xx';user id='DB_11_xx_user'; password='xx';" />
<trust level="Full"/>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/" timeout="2880"/>
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/"/>
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/"/>
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers"/>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-4.0.8.0" newVersion="4.0.8.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Here lies the problem:
My users are still getting logged of after some time. I thought using SQL for the session would prevent this issue.
Here is the relevant bit of code on how I'm loggin my users in:
[HttpPost]
public ActionResult Login(LogOnModel model)
{
using (EfAccountRepository accountRepository = new EfAccountRepository())
{
if (accountRepository.ValidateCredentials(model.Email, model.Password))
{
FormsAuthentication.SetAuthCookie(model.Email, true);
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "Your email or password is incorrect.");
return View(model);
}
And here is some code I use to see if the user is logged in:
public static MvcHtmlString AdminDashboardLink()
{
if (SecurityHelpers.UserIsPartOfCompany(HttpContext.Current))
{
string html = "<li><a href='/Admin'>ADMIN DASHBOARD</a></li>";
return new MvcHtmlString(html);
}
else
{
return new MvcHtmlString("");
}
}
public static bool UserIsPartOfCompany(HttpContext context)
{
if (!context.Request.IsAuthenticated)
return false;
using (EfAccountRepository accountRepository = new EfAccountRepository())
{
var loggedInUser = accountRepository.FindByEmail(context.User.Identity.Name);
string[] userRoles = accountRepository.GetRolesForUser(loggedInUser.AccountId);
return userRoles.Contains("Editor") || userRoles.Contains("Finance") || userRoles.Contains("Administrator");
}
}
Any suggestions? Maybe my web.config is botched and this is causing issues. Maybe I also needed to remove something after I added in the session information?
It is caused some times because the garbage collector cleans the machine key assigned to your application and assigns a new key that causes the looged in users to log out. Solution is to generate a machineKey for your application and place it in the web.config under system.web like
<system.web>
<machineKey validationKey="###YOUR KEY HERE ###"
decryptionKey="## decrypt key here ##"
validation="SHA1" decryption="AES" />
...
...
this link may help you http://aspnetresources.com/tools/machineKey
Forms auth is not session related, at all. It has nothing to do with session state. Everything required is stored in the forms auth cookie.
Your timeout above is set to 2880, so 48 hours i.e. two days so I would expect timeouts to happen.

Categories