SQL Server connection error when checking User Roles inside a view - c#

When i put this in my Index.cshtml:
#if (Request.IsAuthenticated && User.IsInRole("Admin"))
{
<li>Gerenciar</li>
}
It throws this error:
An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code
Additional information:
It is not possible to connect with the SQL Server database
Everything is working SQL Server related, it creates the database, create users fine.
I already looked at other questions and there is no answer that helps!
UPDATE 1
I initialize my context using the default Identity 2.0 context:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
static ApplicationDbContext()
{
// Set the database intializer which is run once during application start
// This seeds the database with admin user credentials and admin role
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<Gatos.Models.Gato> Gato { get; set; }
public System.Data.Entity.DbSet<Gatos.Models.Formulario> Formulario { get; set; }
public System.Data.Entity.DbSet<Gatos.Models.Imagem> Imagem { get; set; }
}
My connection string:
<add name="DefaultConnection" connectionString="Data Source=Bruno-PC;Initial Catalog=Gatos;User Id = sa; Password = *******" providerName="System.Data.SqlClient" />
Update 2
Now my:
[Authorize(Roles="Admin")]
in my controllers are throwing the same error! This is driving me insane!

Are you using a custom Membership for authentication / Authorization?
As a Shortcut, try removing the following line from your main Web.Config:
<roleManager enabled="true" />
Also, take a look at the following page regarding this issue and the solution:
MVC 5 - RoleManager

Try setting your password in a connection string instead of asterisk (*)
<add name="DefaultConnection" connectionString="Data Source=Bruno-PC;Initial Catalog=Gatos;User Id = sa; Password = your_db_pwd" providerName="System.Data.SqlClient" />

Related

EF CodeFirst with Trusted_Connection=True does not create database

Am using EF CodeFirst (Version 6.1.3) with ASP.Net MVC5 / Sql 2014 Express.
It's Entity Framework code first, setup to talk to a local sql server instance using trusted authentication, however database does not get created.
connection string in the Web.config file is
<connectionStrings>
<add name="Ppa" providerName="System.Data.EntityClient" connectionString="Server=localhost;Database=PpaOnline;Trusted_Connection=True;" />
</connectionStrings>
connection string in the App.config file of DAL layer is:
<connectionStrings>
<add name="Ppa" providerName="System.Data.EntityClient" connectionString="Server=localhost;Database=PpaOnline;Trusted_Connection=True;" />
</connectionStrings>
DbContext class is:
public class Db : DbContext
{
static Db()
{
var type = typeof(SqlProviderServices);
if (type == null)
throw new Exception("Do not remove, ensures static reference to System.Data.Entity.SqlServer");
}
public Db()
{
Configuration.LazyLoadingEnabled = false;
}
public DbSet<Company> Companies { get; set; }
public DbSet<User> Users { get; set; }
}
The PpaOnlineConfiguration class is:
public class PpaOnlineConfiguration : DbConfiguration
{
public PpaOnlineConfiguration()
{
SetDefaultConnectionFactory(new SqlConnectionFactory("Server=localhost;Database=PpaOnline;Trusted_Connection=True;"));
}
}
Kindly provide input, as to where am I going wrong.
Thanks,

Code First always wants to create new database when deploying to another PC

i have a win-form app that uses CodeFirst to work with data.
after creating database from my models i have imported records to it from another database.it works fine in my PC but when i deploy my app to another pc, codefirst tries to create new database and throws this error :
System.Data.Entity.Core.EntityException: The underlying provider failed on Open. --->
System.Data.SqlClient.SqlException: Cannot create file
'E:\New folder (2)\Release\MyDB_log.ldf' because it already exists.
Change the file path or the file name, and retry the operation.
Could not open new database 'MyDB'. CREATE DATABASE is aborted.
Cannot attach the file 'E:\New folder (2)\Release\MyDB.mdf' as database 'MyDB'.
connection string :
<connectionStrings>
<add name="AppDbContext"
connectionString="Server=.\sqlexpress;AttachDbFilename=|DataDirectory|\MyDB.mdf;Database=MyDB;Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
</connectionStrings>
AppDbContext :
public class AppDbContext :DbContext
{
static AppDbContext() {
Database.SetInitializer<AppDbContext>(null);
}
public DbSet<Stock> Stocks { get; set; }
public DbSet<Report> Reports { get; set; }
}
Migration class:
internal sealed class Configuration : DbMigrationsConfiguration<Sita_Election.DAL.AppDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "Sita_Election.DAL.AppDbContext";
AutomaticMigrationDataLossAllowed = false;
}
protected override void Seed(Sita_Election.DAL.AppDbContext context)
{
}
}
so i want to use existing database that is created in development with codefirst,how can i do this ?
Is there any reason to have a database per application?
I would suggest using just a SQL DB if possible.
Thanks,
Phill
Your connection string is using a trusted connection so your IIS user is going to need access to that file or you could switch to a sql login. http://th2tran.blogspot.com/2009/06/underlying-provider-failed-on-open.html

AddToRole() method doesn't result in db entry in ASP.NET Identity

I'm using ASP.NET Identity in my ASP.NET MVC app. My problem occures while adding user to role. There isn't any exception, but as a result of um.AddToRole() no db entry is added to AspNetUserRoles table. My action method looks like that:
public ActionResult GrantAdmin(string id)
{
ApplicationUser user = um.FindById(id);
if (!rm.RoleExists("admin"))
{
rm.Create(new IdentityRole("admin"));
}
um.AddToRole(user.Id, "admin");
return View((object)user.UserName);
}
um is an object of UserManager class:
private UserManager<ApplicationUser> um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
What can be a reason of that kind of application behavior? Any idea?
===EDIT===
It is my DbContext:
public ApplicationDbContext()
: base("DefaultConnection")
{
}
And Default Connection in Web.config:
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-RecommendationPlatform-20140404055015.mdf;Initial Catalog=aspnet-RecommendationPlatform-20140404055015;Integrated Security=True" providerName="System.Data.SqlClient" />
When working with ASP.NET Identity it is important to remember that many operations return a result object where eventual errors are stored. There are no exceptions. Therefore one should check the result object for success after every operation. This is true not only for roles but for most methods that save data to the database. Even if it works you should still test for success and eventually throw an exception if the result is not success.
As per the comments in your case the problem was invalid username.

The type User was not mapped

I am implementing o-auth in my mvc4 web application. but when I log in using external login (Microsoft)
it gives error in my Account model.
The type User was not mapped.
my Account model is-
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection") //Exception raise here
{
}
public DbSet<User> UserProfiles { get; set; }
}
User is database generated model class. I have seen link but no help. same exception is raising every time.
my Connection string is-
<add name="DefaultConnection" connectionString="Data Source=URLofWebsite;Initial Catalog=gestest;User ID=Username;Password=Password" providerName="System.Data.SqlClient" />

EF connection String Error

My connection String in web.config file:
<connectionStrings>
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EFcodefirst-20131213155231;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EFcodefirst-20131213155231.mdf" />
</connectionStrings>
My context File
namespace EFcodefirst.Models
{
public class SampleContext: DbContext
{
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}
}
My controller
SampleContext dbContext = new SampleContext();
var customerList = dbContext.Customers.ToList();
return View(customerList);
Here is the 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.
Please help me to solve this problem
Looks like you are trying to create database in same file which is used by ASP.NET membership and you don't have SQLEXPRESS installed on your machine (otherwise Entity Framework would create database with YourNamespace.SampleContext name in your SQLEXPRESS database). So, just add another connection string which will point to another database file:
<connectionStrings>
<add name="SampleContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Sample;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Sample.mdf" />
<add name="DefaultConnection"
providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-EFcodefirst-20131213155231;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-EFcodefirst-20131213155231.mdf" />
</connectionStrings>
NOTE: If you don't want connection string to have same name as your context class, you can provide connection string name to constructor of base context class:
public class SampleContext: DbContext
{
public SampleContext()
: base("AnotherConnectionStringName")
{
}
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}
Modify your dbcontext file :
public class SampleContext: DbContext
{
public SampleContext()
: base("DefaultConnection")
{
}
public DbSet<EFcodefirst.Models.Customer> Customers { get; set; }
}

Categories