MVC Movie Project - Multiple Errors - asp.net-mvc

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.

Related

Shared connection string between multiple projects

I have multiple projects being hosted in IIS. These all share a database, which is called using EF6. I want to be able to use a shared connection string config file which I can reference from each of the other projects' web.config. This way, I'm able to manage any chances to the connection string from a single location. From what I've found online, I'm trying to accomplish this through a Virtual Directory and the configSource attribute for the connectionString.
IIS structure
-VirtualDirectory (mapped to /DbConfigFile)
-WebApp 1
-WebApp 2
-WebApp 3
WebApps' Web.config connectionString sections
<connectionStrings configSource="/DbConfigFile/testDB.config"></connectionStrings>
The external config file (testDB.config) containing the connectionString needed by all applications.
<connectionStrings>
<add name="TestDBEntities" connectionString="metadata=res://*/TestDB.csdl|res://*/TestDB.ssdl|res://*/TestDB.msl;provider=System.Data.SqlClient;provider connection string="data source=TestDB;initial catalog=VBODashboard;persist security info=True;user id=Test;password=Test;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
</connectionStrings>
I've tried various paths in the configSource attribute with no luck (~/DbConfigFile/testDB.config, testDB.config). How would I access this file? Or is there a better way to accomplish this?
I ended up going with one of mason's suggestions and creating a custom configuration file. That let me to research finding out that a connection string can be specified through code when initializing the context. I then navigated through the XML file through code and extracted the connection string value. :
public partial class TestDBEntities : DbContext
{
public TestDBEntities()
: base(<calling code to get connection string> , true)
{
}
...
}

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.

ASP.Net MVC WebSecurity.InitializeDatabaseConnection return error

whenever this line execute WebSecurity.InitializeDatabaseConnection then it is giving error "Connection string "Data Source=BBATRIDIP\SQLSERVER2008R2;Initial Catalog=test;User ID=sa,password=test#" was not found."
again LazyInitializer.EnsureInitialized return error "An exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll but was not handled in user code Additional information: Exception has been thrown by the target of an invocation."
anyone tell me where i made the mistake.
my WebSecurity.InitializeDatabaseConnection() code look like WebSecurity.InitializeDatabaseConnection(#"Data Source=BBATRIDIP\SQLSERVER2008R2;Initial Catalog=test;User ID=sa,password=test#", "UserProfile", "UserId", "UserName", autoCreateTables: true);
thanks
this is how my connection string look like in web.config
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=BBATRIDIP\SQLSERVER2008R2;Initial Catalog=test;User ID=sa,password=tintin11#" providerName="System.Data.SqlClient" />
</connectionStrings>
but still getting error. any idea?
As you can see from MSDN signature of this method is next:
public static void InitializeDatabaseConnection(
string connectionStringName,
string userTableName,
string userIdColumn,
string userNameColumn,
bool autoCreateTables
)
So as first parameter you must provide connection name from app.config or web.config file, e.g. "SecurityConnectionString"

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.

Keyword not supported: 'data source'.: EF code-first using ObjectContext and LocalDB

I am getting a "keyword not supported error" when I try to connect to a LocalDB database using ObjectContext.
This is my connection string:
<add name="connStr" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=proj1db;Integrated Security=True" />
and this is the code that tries to create an instance of the ObjectContext:
var connectionString = ConfigurationManager
.ConnectionStrings["connStr"]
.ConnectionString;
ObjectContext _context = new ObjectContext(connectionString);
The last line throws System.ArgumentException: Keyword not supported: 'data source'.
I am using Visual Studio 2012 for Web and targeting .NET Framework 4.5. I have LocalDB installed on my machine.
If I use DbContext instead it works:
public class proj1dbContext: DbContext
{
public proj1dbContext() : base("name=connStr")
...
It seems that this is a similar question
Help with EF Code first connection string
but unfortunately it does not give a definitive answer to why instantiating ObjectContext throws that error.
Any help is appreaciated. Thanks!
ObjectContext takes an EF connection string (with Metadata and Provider Connection String keywords), not a provider-specific connection string.
You can't use ObjectContext with Code-First; ObjectContext requires the metadata XML files.

Resources