MVC 4 Custom Membership Provider troubles - asp.net-mvc

I'm working on my first real MVC project and my task is to implement a custom membership provider. I have implemented one before in asp.net 3.5 Web Forms so I'm trying to reuse some of that code if possible.
Our data comes from a remote web service so I won't be using any of the standard membership database.
Based on some research and experience in Web Forms I created my class:
public class wwdllMembershipProvider : MembershipProvider
I put the following in web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<membership defaultProvider="wwdllMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<add name="wwdllMembershipProvider" type="wwdllMembershipProvider" enablePasswordRetrieval="false" enablePasswordReset="false" writeExceptionsToEventLog="false" enablePasswordChange="true" />
</providers>
</membership>
From there I was just going to try to see if any of the stubbed out code in my membership provider was being hit. But as soon as I click on the login link in the app I get the following error:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
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.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
Source Error:
Line 55: using (var context = new UsersContext())
Line 56: {
Line 57: if (!context.Database.Exists())
Line 58: {
Line 59: // Create the SimpleMembership database without Entity Framework migration schema
Source File: c:\Users\mburt\Documents\Visual Studio 2012\Projects\eSales\4300\Siriusware.eSales\Filters\InitializeSimpleMembershipAttribute.cs Line: 57
Which is puzzling to me because I didn't think the Simple Membership Provider code would execute because of the web.config setting disabling it.
Can someone point out to me what I'm doing wrong? Thanks!

The default account controller is decorated with that very attribute. Check if that is still present.
(Default MVC4 project code below.)
namespace MvcApplication2.Controllers
{
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
[...]
}
}

Related

visual studio 2017 web application mvc SqlException (0x80131904) error

Ive been working on a web app for the past month and now its time to deploy it on real windows server.The problem is once i deployed it my default localdb code first SQL database no longer works with this code:
[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance. See the Windows Application event log for error details.
)]
Source Error:
Line 11: var manager = new UserManager();
Line 12: var user = new ApplicationUser() { UserName = UserName.Text };
Line 13: IdentityResult result = manager.Create(user, Password.Text);
Line 14: if (result.Succeeded)
Line 15: {
my web.config string :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-projecttwo-80a6f83e-fca9-45c3-869f-c5c625497346;AttachDbFilename=|DataDirectory|\aspnet-projecttwo-80a6f83e-fca9-45c3-869f-c5c625497346.mdf;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
Its so frustrating im kinda lost , i dont want to build my login and registration from scratch i just want to use the provided ones from Visual Studio 2017 and there is no tutorial up to date how to do it.
I have SQL Express on my computer installed and its currently running.
There are possible solutions to solve LocalDB instance issue:
1) If the database is already created (as given by AttachDbFilename=|DataDirectory|\aspnet-projecttwo-80a6f83e-fca9-45c3-869f-c5c625497346.mdf), remove the section so that it only contains Initial Catalog shown below.
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet-projecttwo-80a6f83e-fca9-45c3-869f-c5c625497346;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
</connectionStrings>
2) Set IIS application pool for the MVC application to either LocalSystem or NetworkService from ApplicationPoolIdentity - if you suspect a permission-related issue for the application.
3) Find out \%WinDir%\System32\inetsrv\config\applicationHost.config file and enable setProfileEnvironment="true" (restart the application pool afterwards):
<!-- use application pool name depending which pool that your MVC site used -->
<add name="DefaultAppPool" ...>
<processModel identityType="ApplicationPoolIdentity" loadUserProfile="true" setProfileEnvironment="true" />
</add>
Further references:
SQL Server Connection Strings
Using LocalDB with Full IIS Series: (Part 1) (Part 2)
Similar issue:
Deployment of SQL Express LocalDB on IIS

MVC 6 - How to configure remote database connection for Identity 2 and Entity Framework 6

I've been spinning my wheels on this for awhile now and haven't been able to find anything substantial on the topic.
I've implemented an MVC 6 project that is utilizing the Identity Framework 2 and Entity Framework 6. The application works fine with a local database being used as my identity repository. On the first connection, the Entity Framework creates the identity tables based on my identity model classes. I built it based off of a project from this book. The chapters on using Identity and all of the online samples I find don't cover pointing the entity framework to a remote database.
Here are my connection strings I've experimented with...
Local database connection string. Project works fine.
<add name="IdentityDb" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\IdentityDb.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
Failed approach 1. I based this off of other connection strings from my other projects. I removed the meta data parameters because when it comes to my understanding, this points to the edmx file but I don't have one since I'm taking a code first approach and letting identity and the entity frameworks build the database. I'm wondering if I'm missing something here because I've always taken a database first approach until now.
<add name="IdentityDb" connectionString="provider=System.Data.SqlClient;provider connection string="data source=****;initial catalog=IdentityTest;Uid=*****;Pwd=*****;integrated security=False;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Returned exception details. The metadata keyword is missing.
System.ArgumentException: Some required information is missing from the connection string. The 'metadata' keyword is always required.
Failed approach 2. I built an empty Identity.edmx file thinking this must be where all of the metadata is stored and maybe the entity framework will update it and have it's required resources once the app connects to the database the first time.
<add name="IdentityDb" connectionString="metadata=res://*/Identity.csdl|res://*/Identity.ssdl|res://*/Identity.msl;provider=System.Data.SqlClient;provider connection string="data source=****;initial catalog=IdentityTest;Uid=****;Pwd=****;integrated security=False;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Returned exception detail. The meta data is missing.
System.Data.Entity.Core.MetadataException: Unable to load the specified metadata resource.
Last failed approach. I found a lot of online sources where people simply changed the metadata parameters to "res://*". I'm guessing this is some kind of wildcard that would locate the metadata resources if they existed...
<add name="IdentityDb" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string="data source=****;initial catalog=IdentityTest;Uid=****;Pwd=****;integrated security=False;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Returned exception details (With a identity.edmx file in the project)
System.NotSupportedException: Model compatibility cannot be checked because the DbContext instance was not created using Code First patterns. DbContext instances created from an ObjectContext or using an EDMX file cannot be checked for compatibility.
Returned exception details (Without an identity.edmx file in the project)
System.ArgumentException: Argument 'xmlReader' is not valid. A minimum of one .ssdl artifact must be supplied
My database context class
public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
public AppIdentityDbContext() : base("name=IdentityDb") { }
static AppIdentityDbContext()
{
// Seeds the database when the schema is first created through the Entity Framework.
Database.SetInitializer<AppIdentityDbContext>(new IdentityDbInit());
}
// OWIN uses this method to create instances of this class when needed.
public static AppIdentityDbContext Create()
{
return new AppIdentityDbContext();
}
public System.Data.Entity.DbSet<UAM.Models.Identity.AppRole> IdentityRoles { get; set; }
}
// Seed class for initially populating the identity database.
public class IdentityDbInit : DropCreateDatabaseIfModelChanges<AppIdentityDbContext>
{
protected override void Seed(AppIdentityDbContext context)
{
PerformInitialSetup(context);
base.Seed(context);
}
public void PerformInitialSetup(AppIdentityDbContext context)
{
// Initial database configuration
}
}
Any help or insight would be much appreciated. What is the correct approach for doing this? Is there something that I need to do when I transition from using a local database to a remote one? Let me know if I should provide anymore code samples. I'm fairly new to MVC and am currently building this module so that I can use it for a few enterprise applications that I'll be developing this year.
You need to specify providerName="System.Data.SqlClient" instead of providerName="System.Data.EntityClient"
For Example
<add name="IdentityDb" connectionString="Data Source=*******;Database=IdentityTest;Integrated Security=false;User ID=**;Password=******;" providerName="System.Data.SqlClient"/>
This is the connection string I use and it worked without an issue.
<add name="InventoryEntities"
connectionString="metadata=res://*/Entities.csdl|res://*/Entities.ssdl|res://*/Entities.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlinstance;initial catalog=DBName;persist security info=True;user id=UID;password=PWD;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
The tool generated this for me (I didn't need to do anything custom to the connection string) so maybe you can delete and let the too re-add it? (I think it does that)?
Also, you didn't rename the EF files at all did you? If you did, you would have to update the connection string to match.

Publish web in MVC

I have a MVC Project Which I want to Publish and upload it
I asked the server provider to upload my data base.
My Data base is local
and here is the information of this:
Name : vidiaweb_com_TourDbContext
DataBase: vidiaweb_com_TourDbContext-20160613111028
and here is my connection string
<connectionStrings>
<add name="vidiaweb_com_TourDbContext" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\vidiaweb_com_TourDbContext-20160613111028.mdf;Initial Catalog=vidiaweb_com_TourDbContext-20160613111028;Integrated Security=True;User Id=vidiaweb_com_TourDbContext;Password=password;" providerName="System.Data.SqlClient" />
</connectionStrings>
but in each page Which there is model for example like this
#model IEnumerable<vidiaweb_com.Models.Country>
, an error appeared:
'Server Error in '/' Application.
The system cannot find the file specified
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.ComponentModel.Win32Exception: The system cannot find the file specified
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[Win32Exception (0x80004005): The system cannot find the file specified] '
Dose any one have any idea what may would be the problem?
Obviously, your web host is not putting the database in the /App_Data/ directory of your web site, which is what you are specifying in the connection string with |DataDirectory|\. It is likely being attached to a real SQL Server instance, in which case you won't specify a directory.
You need to obtain the server details of the database from your web host. Most likely your connection string will look something like this:
SERVER=data.somewhere.com;DATABASE=vidiaweb_com_TourDbContext;UID=TheApplicationUserName;PWD=TheApplicationPassword;
See ConnectionStrings.com for some more samples of what the connection string could look like.

Why am I getting "The magic number in GZip header is not correct." error using OWIN auth against Azure SQL

Nothing on Google or SO relates to this specific problem, so asking a new question. I created a brand new Asp.Net MVC Web Application with the standard user-security option. I also created an empty database in Azure.
I did nothing but change the default connection string to this:
<connectionStrings>
<add name="DefaultConnection"
connectionString="data source=mydatabase.database.windows.net;initial catalog=Feedback;persist security info=True;user id=LeaveFeedbackuser;password=mypassword;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
and the default connection factory to this:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
On attempting to register (when I would expect it to normally create the AspNetUsers and related tables) I get the following error:
The magic number in GZip header is not correct. Make sure you are
passing in a GZip stream. 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.IO.InvalidDataException: The magic number
in GZip header is not correct. Make sure you are passing in a GZip
stream.
Source Error:
Line 153: { Line 154: var user = new
ApplicationUser { UserName = model.Email, Email = model.Email }; Line
155: var result = await UserManager.CreateAsync(user,
model.Password); Line 156: if (result.Succeeded) Line
157: {
What has any of this to do with GZip and what is causing this error? This has stopped me getting OWIN working with my Azure database for several days now.
I experienced a similar problem.
The Entity Framework __MigrationHistory Model column contains GZipped data. If the data in this column is corrupted then your app won't be able to unzip the data and you'll get the error.
In my case, the corruption occurred by trying to manually insert into this able.
My solution: delete corrupted __MigrationHistory rows and related DB changes and allow the app to migrate the database properly.
So here's my "theory". I think the Sql Azure Db is not setup correctly or the connection string is in error.
We know that when AspIdentity attempts to hit the database on Login and finds the tables are not set up it will try to create them.
I think there is a breakdown/bug in the AspIdentity code that under this circumstance swallows the exception generated from the bad connection string and thus the failed setup and continues on it's merry way trying to provide an authentication ticket to the client.
If we look into the code for Microsoft.Owin.Security.DataHandler.Serializer.TicketSerializer we find some GZip action:
public virtual byte[] Serialize(AuthenticationTicket model)
{
using (var memory = new MemoryStream())
{
using (var compression = new GZipStream(memory, CompressionLevel.Optimal))
{
using (var writer = new BinaryWriter(compression))
{
Write(writer, model);
}
}
return memory.ToArray();
}
}
So basically I think AspIdentity fails on the connection, this error is swallowed, the Owin pipeline continues processing the request but when it hits the TicketSerializer perhaps a null value or some other bogus value is passed in which Gzip tries to zip and Boom!
Weirdo YSOD output ensues.
The magic number in GZip header is not correct. Make sure you are
passing in a GZip stream. 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.
AspIdentity is not properly short circuiting OWIN request processing for this particular event.
Probably utter nonsense but I'll throw it out there anyway.

MVC Movie Project - Multiple Errors

strong textI'm attempting to run the MVC Movie Project, located here:
http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/accessing-your-models-data-from-a-controller
When I attempt to run it, I'm given an error in the MoviesController.cs:
public ActionResult Index()
{
return View(db.Movies.ToList());
}
Which states: Invalid value for key 'attachdbfilename'.
I researched this and discovered some people has success by changing the connectionString "MovieDBContext" value from this:
<add name="MovieDBContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
to this:
<add name="MovieDBContext"
connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"
/>
That seems to let it run further, but then it errors out again at the same place in MoviesController.cs ...
public ActionResult Index()
{
return View(db.Movies.ToList());
}
with a new 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."
I did a search looking for suggestions to what this was, including these posts:
System.Data.Entity.Core.ProviderIncompatible Exception in MVC 5
An unhandled exception occurred during the execution of the current web request, "Не найден указанный модуль"
It would suggest that my "Movies.mdf" file is missing, but when I check the App_Data folder its there. One person suggested recreating LocalDB, I'm not sure what that is or how I'd do that. As you can tell I'm very new to .NET. Any suggestions are very much appreciated. Thank you for reading.

Resources