By default ASP.NET Identity user data is stored in an mdf file.
I want to store the data in a Sql database so that I changed the defaultconnection string in my web.config to my EF based connection:
<add name="DefaultConnection" connectionString="metadata=res://*/Models.StartifyModel.csdl|res://*/Models.StartifyModel.ssdl|res://*/Models.StartifyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MYPC\SQLEXPRESS;initial catalog=mydb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Now I am getting the error The entity type ApplicationUser is not part of the model for the current context. as soon as I want to register a user.
I use the default MVC5 project template of VS2013.
Please try specify the connection string in the format:
<add name="DefaultConnection" connectionString="Data Source=127.0.0.1, 1433;Initial Catalog=YourDB;User Id=XXXX;Password=XXXXX;Asynchronous Processing=True;Encrypt=False;TrustServerCertificate=True;Persist Security Info=True" providerName="System.Data.SqlClient" />
And then make sure in Models/IdentityModels.cs you have
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
Related
I created a project "SmartHome" using the ASP.NET MVC. I used two types of databases;
PostgreSQL
TIMESCALE
Here, I integrate the TIMESCALE with the PostgreSQL.
I connected the PostgreSQL with ASP.NET MVC and it is working fine. the connection string as below.
<add name="SmartHomeContext"
connectionString="Server=127.0.0.1;Port=5432;Database=smarthome;
User Id=postgres;Password=postdata;" providerName="Npgsql" />
here database names of;
PostgreSQL = smarthome
TIMESCALE = smarthomeData
My problem is " How TIMESCALE database connect to work with same "SmartHome" database in the ASP.NET MVC ? "
I tried the connection string for TIMESCALE as below.
<add name="SmartHomeContext"
connectionString="Server=127.0.0.1;Port=5432;Database=smarthomeData;
User Id=postgres;Password=postdata;" providerName="Npgsql" />
but it shows the below error:
"The entry 'SmartHomeContext' has already been added."
Please help me or guide me, I am very new to do this.
Above error ("The entry 'SmartHomeContext' has already been added.") was solved and the connection also done. the steps are followed as below;
Web.config file : add a another connection string for TIMESCALE database as "SmartHomeContext1". In the below code snippet, third connection string.
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=
(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-SmartHome-
20181019034449.mdf;Initial Catalog=aspnet-SmartHome-20181019034449;Integrated
Security=True" providerName="System.Data.SqlClient" />
<add name="SmartHomeContext"
connectionString="Server=127.0.0.1;Port=5432;Database=smarthome;User
Id=postgres;Password=postdata;" providerName="Npgsql" />
<add name="SmartHomeContext1"
connectionString="Server=127.0.0.1;Port=5432;Database=smarthomeData;User
Id=postgres;Password=postdata;" providerName="Npgsql" />
</connectionStrings>
create "timescalecontext.cs" file in the Model as attached image.
timescalecontext.cs in the Models folder in visual studio
already I created a table in the database "smarthomeData" as attached image.
timescale database
then, code the "timescalecontext.cs" file as below.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace SmartHome.Models
{
public class timescalecontext : DbContext
{
public timescalecontext() : base("name=SmartHomeContext1")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("public");
base.OnModelCreating(modelBuilder);
}
public System.Data.Entity.DbSet<SmartHome.Models.DeviceReading> DeviceReadings { get; set; }
public System.Data.Entity.DbSet<SmartHome.Models.Event> Events { get; set; }
}
}
since the controller file already created before make the above connection, change the code matched with the Dbcontext as below:
namespace SmartHome.Controllers
{
public class DeviceReadingsController : Controller
{
private timescalecontext db = new timescalecontext();
after all that, It worked. Hope, this will be helpful.
In data layer I am trying to fetch connection string from app.config.
App.config
<connectionStrings>
<add name="DBConnection" connectionString="Data Source=****;Initial Catalog=****;Persist Security Info=True;User ID=*****; Password=***" />
</connectionStrings>
Fetching Value:
Shared _ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
this is not working.
And I tried
Shared _ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings(0).ConnectionString
it is partially fetching - "Data Source=****;Initial Catalog=****;Persist Security Info=True"
Kindly explain.
Try using ConnectionStrings["DBConnection"].ConnectionString instead of ConnectionStrings("DBConnection").ConnectionString.
I have an ASP.NET MVC application for which I've configured sessions in the web.config as follows:
<!--
If you are deploying to a cloud environment that has multiple web server instances,
you should change session state mode from "InProc" to "Custom". In addition,
change the connection string named "DefaultConnection" to connect to an instance
of SQL Server (including SQL Azure and SQL Compact) instead of to SQL Server Express.
-->
<sessionState customProvider="DefaultSessionProvider" mode="InProc" timeout="65">
<providers>
<add name="DefaultSessionProvider"
type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
connectionStringName="DefaultConnection" />
</providers>
</sessionState>
FYI, our production environment has four app servers which is I assume why the DefaultSessionProvider was set (by someone else).
I'm using a SessionHelper class to store information in the session:
public class SessionHelper : ISessionHelper
{
private readonly HttpContextBase context;
public SessionHelper(HttpContextBase context)
{
this.context = context;
}
public int? GetUserId()
{
return getSessionValue<int?>(USER_ID_KEY);
}
private T getSessionValue<T>(string key)
{
var value = context.Session[key];
if (value == null)
{
return default(T);
}
return (T)value;
}
}
I'm using Ninject to inject HttpContextBase like so:
kernel.Bind<HttpContextBase>().ToMethod(ctx => new HttpContextWrapper(HttpContext.Current)).InTransientScope();
What I'm seeing is that before the timeout of 65 mins which I have set in the web.config, the session variables are null. I also noticed Session_End() in my Global.asax.cs being called.
I've done some research and the information I found regarding sessions ending prematurely seems to be focused on things that would affect all users like files being changed in the bin directory causing the app pool to restart. Things like that. I believe my issue is on a session-by-session basis.
Why is my session ending before I want it to? Thanks in advance.
So i get the error that i should call WebSecurity.InitializeDatabaseConnection
before i call any function of the webSecurity Class
So i created _AppStart.cshtml and placed this code in it :
#using System.Configuration;
#{
string connString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
WebSecurity.InitializeDatabaseConnection(connString, "users", "id", "email", autoCreateTables: true);
}
and in Web.Config i got
<appSettings>
<add key="enableSimpleMembership" value="true" />
</appSettings>
<connectionStrings>
<add name="conString" providerName="System.Data.SqlClient"
connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=sales;Integrated Security=True;Pooling=False"/>
</connectionStrings>
now i get this error from the InitializeDatabaseConncection method :
Connection string "Data Source=(local)\SQLEXPRESS;Initial Catalog=sales;Integrated Security=True;Pooling=False" was not found.
whats the problem ?
WebSecurity.InitializeDatabaseConnection is not asking you for a connection string. It's asking you for the name of the connection string. It will then retrieve the connection string form the configuration file for you.
WebSecurity.InitializeDatabaseConnection("conString", "users", "id", "email", autoCreateTables: true);
When you have a question about why a method is not behaving as expected, read the documentation! It states for that parameter:
The name of the connection string for the database that contains user information. If you are using SQL Server Compact, this can be the name of the database file (.sdf file) without the .sdf file name extension.
I'm playing around with asp.net for the first time. I want to use it with a MySQL database because this is what is offered by my hosting service and I don't want to upgrade/change services. I'm using visual web developer 2010 express. I created an MVC 4 project from the default template. The template created the ASP.NET Simple Membership objects which is what I'm trying to get working. The project builds and runs correctly when using the default database connection string. When I change the web.config file to point to MySQL I get the following error when I attempt to navigate to any of the pages in the account folder.
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'IDENTITY,
RoleName nvarc' at line 2
When I open the MySQL work bench and connect to the local server I notice that the database has been created. If I drop the DB and run the app again it gets recreated. I'm note sure if it was created correctly or if the entire database was created but there is something there.
Obviously there is an issue with the SQL syntax that is created by the Entity Framework. Do I need to add something to the web.config file to tell it what syntax it should use when creating the queries?
I've been searching for an answer to this for the past two days. any help pointing in the right direction would be appreciated.
I'm using mysql server version 5.5.27. and connector 6.5.4.0
here is the mysql part of my web.config file:
<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.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=aspnet-MyWebPage-20120817115958;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
<add name="myDatabaseConnection" connectionString="server=localhost;Port=3306;uid=root;pwd=****;database=myDatabase;" providerName="MySql.Data.MySqlClient" />
</connectionStrings>
Edit adding code
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private class SimpleMembershipInitializer
{
public SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("LocalMySqlServer", "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);
}
}
}
}
public class UsersContext : DbContext
{
public UsersContext()
: base("LocalMySqlServer")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
}
Try to modify the source of the SMP and remove the syntax specific to ms sql server.
The role provider is still defaulting to the standard ASP one which is expecting a SQLServer DB on the end of the connection, "Identity" is SQLServerese for "autoinc".
You can set the default providers in the web.config like this:-
<configuration>
<system.web>
<profile defaultProvider="MySQLProfileProvider"></profile>
<roleManager defaultProvider="MySQLRoleProvider"></roleManager>
</system.web>
</configuration>