I am trying to implemente code First Migrations with Oracle.ManagedDataAccess 6.121.1.0 provider, but with no success at all.
As I am receiving a ORA-code, I am assuming that the connection are been opened successfully. But the Migrations are failing because, maybe, the provider are behaving as a SQL Server, instead of Oracle. I think that beacause it is traying to use 'dbo' as default schema.
Here is my web.config settings:
<configuration>
<configSections>
<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.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
<entityFramework>
<contexts>
<context type="MyProject.Context.MainContext, MyProject.Context">
<databaseInitializer type="MyProject.Context.Config.ContextInitializer, MyProject.Context" />
</context>
</contexts>
<defaultConnectionFactory type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess" />
<providers>
<provider invariantName="Oracle.ManagedDataAccess.Client"
type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.121.1.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.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
<connectionStrings>
<add name="MainContext"
providerName="Oracle.ManagedDataAccess.Client"
connectionString="Data Source=OracleServer:1521/BRSYSDS;User ID=USER;Password=PASSWORD;" />
</connectionStrings>
<!-- other settings -->
</configuration>
Here the Stacktrace:
[OracleException (0x77e): ORA-01918: user 'dbo' does not exist]
OracleInternal.ServiceObjects.OracleCommandImpl.VerifyExecution(OracleConnectionImpl connectionImpl, Int32& cursorId, Boolean bThrowArrayBindRelatedErrors, OracleException& exceptionForArrayBindDML, Boolean& hasMoreRowsInDB, Boolean bFirstIterationDone) +652
OracleInternal.ServiceObjects.OracleCommandImpl.VerifyExecution(OracleConnectionImpl connectionImpl, Int32& cursorId, Boolean bThrowArrayBindRelatedErrors, OracleException& exceptionForArrayBindDML, Boolean bFirstIterationDone) +39
OracleInternal.ServiceObjects.OracleCommandImpl.ExecuteNonQuery(String commandText, OracleParameterCollection paramColl, CommandType commandType, OracleConnectionImpl connectionImpl, Int32 longFetchSize, Int64 clientInitialLOBFS, OracleDependencyImpl orclDependencyImpl, Int64[]& scnFromExecution, OracleParameterCollection& bindByPositionParamColl, Boolean& bBindParamPresent, OracleException& exceptionForArrayBindDML, Boolean isFromEF) +7480
Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteNonQuery() +678
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.b__0(DbCommand t, DbCommandInterceptionContext1 c) +10
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) +357
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery() +104
System.Data.Entity.Migrations.DbMigrator.ExecuteSql(DbTransaction transaction, MigrationStatement migrationStatement, DbInterceptionContext interceptionContext) +152
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext) +82
System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable1 migrationStatements, DbConnection connection) +626
System.Data.Entity.Migrations.<>c__DisplayClass30.<ExecuteStatements>b__2e() +19
System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute(Action operation) +9
System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable1 migrationStatements, DbTransaction existingTransaction) +194
System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable1 migrationStatements) +7
System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable1 operations, IEnumerable1 systemOperations, Boolean downgrading, Boolean auto) +825
System.Data.Entity.Migrations.DbMigrator.AutoMigrate(String migrationId, VersionedModel sourceModel, VersionedModel targetModel, Boolean downgrading) +564
System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable1 pendingMigrations, String targetMigrationId, String lastMigrationId) +404
System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) +447
System.Data.Entity.Migrations.<>c__DisplayClassc.b__b() +13
System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) +422
System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) +78
System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func3 createMigrator, ObjectContext objectContext) +89
System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState) +116
System.Data.Entity.Database.Create(DatabaseExistenceState existenceState) +218
System.Data.Entity.DropCreateDatabaseAlways1.InitializeDatabase(TContext context) +137
I had the same problem and it was resolved by Thiago Lunardi's response. Thank you. I didn't have enough reputation to vote up your response. To mention here, I succeeded after setting my schema name in UPPERCASE.
Put this in your Context file under your new dbContext class, like this:
public partial class MyAppContext : DbContext
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("UPPERCASE_SCHEMA_NAME");
...
I solve this just setting the default schema at modelBuilder
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("MyOracleSchema");
// ...
}
Setting default schema didn't work for me.
I found the solution by customizing migrations history table to set a different schema.
You can find a solution here: LINK.
User Dbo also comes in case of missing fully qualified name of the Table. Which may not map to the right Table in the database.
If you use Automatic Migrations (as I was), then note: modelBuilder.HasDefaultSchema whouldn't help until you switch to explicit migrations.
From Oracle Docs:
Code First Automatic Migrations is limited to working with the dbo schema only. Due to this limitation it is recommended to use code-based migrations, that is, add explicit migrations through the Add-Migration command
in Code First you can use the DataAnnotations for Table .
[Table("Emplpoyee",Schema="YOUR SCHEMA NAME"]
I had the same problem. I placed my schema name in OnModelCreating() method.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("MyOracleSchema");
// ...
}
But, setting schema name in UPPERCASE didn't work for me. I added below mentioned code in Confifuration.cs and it worked !!
Go to Migrations -> Configuration.cs
class Configuration : DbMigrationsConfiguration<CodeFirstOracleProject.Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
var historyContextFactory = GetHistoryContextFactory("Oracle.ManagedDataAccess.Client");
SetHistoryContextFactory("Oracle.ManagedDataAccess.Client",
(dbc, schema) => historyContextFactory.Invoke(dbc, "YourSchemaName"));
}
}
In my case writing schema name in Uppercase wasn't sufficient I had to use toUpper() function as such :
modelBuilder.HasDefaultSchema("YOURSCHEMA".ToUpper())
alongside adding
public Configuration()
{
AutomaticMigrationsEnabled = false;
var historyContextFactory = GetHistoryContextFactory("Oracle.ManagedDataAccess.Client");
SetHistoryContextFactory("Oracle.ManagedDataAccess.Client",
(dbc, schema) => historyContextFactory.Invoke(dbc, "YOURSCHEMA".ToUpper()));
}
removed the migrations and regenerating them fixed the issue.
As a beginner, the major issue I had with the answers here was, what does user 'dbo' has to do with schema name.
After researching, here is what I found.
In oracle, A Schema is a collection of database objects. A schema is owned by a database user and has the same name as the user.
The default schema for entity framework is however dbo, and you can override this as in the code listing below:
modelBuilder.HasDefaultSchema("YOURSCHEMA".ToUpper())
For oracle, "YOURSCHEMA" has to be the user_id for the database you are connected to.
Then you need to add the below to your configuration file
public Configuration()
{
AutomaticMigrationsEnabled = false;
var historyContextFactory = GetHistoryContextFactory("Oracle.ManagedDataAccess.Client");
SetHistoryContextFactory("Oracle.ManagedDataAccess.Client",
(dbc, schema) => historyContextFactory.Invoke(dbc, "YOURSCHEMA".ToUpper()));
}
Finally, delete the migration files generated and rerun Add-Migration again.
I hope this will help somebody.
Related
I implemented an ASP.Net Web API 2 project with ADFS cookie authentication and hosted it on IIS. All works fine.
However, some clients have got old cookies which became invalid because of configuration changes. Such cookies cause following error when calling my API:
[CryptographicException: Key not valid for use in specified state.
]
System.Security.Cryptography.ProtectedData.Unprotect(Byte[] encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +447
System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +49
[InvalidOperationException: ID1073: A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API (see inner exception for details). If you are using IIS 7.5, this could be due to the loadUserProfile setting on the Application Pool being set to false. ]
System.IdentityModel.ProtectedDataCookieTransform.Decode(Byte[] encoded) +329
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[] cookie, Boolean outbound) +167
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader reader, SecurityTokenResolver tokenResolver) +826
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[] token, SecurityTokenResolver tokenResolver) +92
System.IdentityModel.Services.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie) +569
System.IdentityModel.Services.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken) +306
System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +159
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +142
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +92
The obvious workaround is to clear the cookies. However, it's likely that I'll change the cookies configuration again in future, so I'd like to clear all invalid cookies automatically from the API.
I've tried adding a custom OWIN middleware and overriding IExceptionHandler.
Here's my WIF config:
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="https://my.web-api.com" />
</audienceUris>
<issuerNameRegistry type="System.IdentityModel.Tokens.ValidatingIssuerNameRegistry, System.IdentityModel.Tokens.ValidatingIssuerNameRegistry">
<authority name="ADFS">
<keys>
<add thumbprint="--a thumbprint--" />
</keys>
<validIssuers>
<add name="http://my.adfs.com/adfs/services/trust" />
</validIssuers>
</authority>
</issuerNameRegistry>
</identityConfiguration>
</system.identityModel>
<system.identityModel.services>
<federationConfiguration>
<wsFederation issuer="https://my.adfs.com/adfs/ls" realm="https://my.web-api.com" requireHttps="true" passiveRedirectEnabled="false"
persistentCookiesOnPassiveRedirects="true" />
<cookieHandler name="my.cookie" path="/" persistentSessionLifetime="7.0:0:0" />
<serviceCertificate>
<certificateReference x509FindType="FindBySubjectName" findValue="my.web-api.com" storeLocation="LocalMachine" storeName="My" />
</serviceCertificate>
</federationConfiguration>
</system.identityModel.services>
Here's my Startup class:
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
config.Services.Replace(typeof(IExceptionHandler), new CryptographicExceptionHandler());
WebApiConfig.Register(config);
appBuilder.UseWebApi(config);
appBuilder.Use<ClearInvalidCookiesMiddleware>();
}
}
No matter what's inside CryptographicExceptionHandler and ClearInvalidCookiesMiddleware, their code is not called and I'm getting 500 error. I also tried to move ClearInvalidCookiesMiddleware before UseWebApi.
My aim is to add Set-Cookie response header to clear invalid cookies and return 401 or a redirect.
How can I make OWIN to customize the response in this case?
The solution appeared to override SessionAuthenticationModule.OnAuthenticateRequest and call SignOut() in case of exceptions:
class ClearInvalidCookiesSessionAuthenticationModule : SessionAuthenticationModule
{
protected override void OnAuthenticateRequest(object sender, EventArgs eventArgs)
{
try
{
base.OnAuthenticateRequest(sender, eventArgs);
}
catch(InvalidOperationException ex) when (ex.InnerException is CryptographicException) // Invalid cookie signing key
{
SignOut();
}
catch(System.Xml.XmlException) // Invalid cookie structure
{
SignOut();
}
}
}
To use the inherited class instead of default one, one should insert following line inside Web.config:
<system.webServer>
<modules ...>
<!-- Insert the line below or replace existing SessionAuthenticationModule -->
<add name="SessionAuthenticationModule" preCondition="managedHandler"
type="MyNamespace.ClearInvalidCookiesSessionAuthenticationModule, MyAssembly" />
...
</modules>
...
</system.webServer>
In March 5, 2015 Oracle provides a tutorial
Link to Tutorial
This tutorial demonstrates how to use Entity Framework (EF) Code First with Oracle Data Provider for .NET (ODP.NET)
Following the steps and running the project I am getting this error.
System.Reflection.TargetInvocationException was unhandled
HResult=-2146232828
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)
at System.Data.Entity.Utilities.MemberInfoExtensions.GetValue(MemberInfo memberInfo)
at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(Type providerType)
at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName)
at System.Data.Entity.Internal.AppConfig.<.ctor>b__2(ProviderElement e)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.Internal.AppConfig.<.ctor>b__1()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Internal.AppConfig.get_DbProviderServices()
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.RegisterDbProviderServices()
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServiceFactory(Type type, String name)
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.<>c__DisplayClass1.<GetService>b__0(Tuple`2 t)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetService(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetServiceAsServices(IDbDependencyResolver resolver, Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.AppConfigDependencyResolver.GetServices(Type type, Object key)
at System.Data.Entity.Infrastructure.DependencyResolution.ResolverChain.<>c__DisplayClass6.<GetServices>b__5(IDbDependencyResolver r)
at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
at System.Linq.Enumerable.<ConcatIterator>d__71`1.MoveNext()
at System.Linq.Enumerable.<OfTypeIterator>d__aa`1.MoveNext()
at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.Infrastructure.DependencyResolution.InternalConfiguration.Lock()
at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.<.ctor>b__1()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Data.Entity.Infrastructure.DependencyResolution.DbConfigurationManager.GetConfiguration()
at System.Data.Entity.Infrastructure.DependencyResolution.InternalConfiguration.get_Instance()
at System.Data.Entity.Database.SetInitializer[TContext](IDatabaseInitializer`1 strategy)
at NuGet.Program.Main(String[] args) in d:\Visual Studio\Tutorials\NuGet\NuGet\Program.cs:line 15
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.TypeInitializationException
HResult=-2146233036
Message=The type initializer for 'Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices' threw an exception.
Source=Oracle.ManagedDataAccess.EntityFramework
TypeName=Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices
StackTrace:
at Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices.get_Instance()
InnerException: System.TypeLoadException
HResult=-2146233054
Message=Could not load type 'OracleInternal.Common.ConfigBaseClass' from assembly 'Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342'.
Source=Oracle.ManagedDataAccess.EntityFramework
TypeName=OracleInternal.Common.ConfigBaseClass
StackTrace:
at Oracle.ManagedDataAccess.EntityFramework.EntityFrameworkProviderSettings.Oracle.ManagedDataAccess.EntityFramework.EFProviderSettings.IEFProviderSettings.get_TracingEnabled()
at Oracle.ManagedDataAccess.EntityFramework.EFProviderSettings.InitializeProviderSettings[T]()
at Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices..ctor()
at Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices..cctor()
InnerException:
I'm seeing this error Message=Could not load type 'OracleInternal.Common.ConfigBaseClass' from assembly 'Oracle.ManagedDataAccess
Haven't been able to find anything related to this error anywhere. Bellow is the generated 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=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.2"/>
</startup>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v12.0"/>
</parameters>
</defaultConnectionFactory>
<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>
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="LocalOracle" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PDBORCL))) "/>
</dataSources>
</version>
</oracle.manageddataaccess.client>
<connectionStrings>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client"
connectionString="User Id=ZR;Password=mypassword;Data Source=LocalOracle"/>
</connectionStrings>
</configuration>
Is anyone getting this same error message, and if so has anyone found a work around or solution.
So I have created a MVC3 (Razor) Website in Visual Studio 2010. Now I want to publish it to a server but keep getting the following error message after I have published and uploaded files to server:
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)
Stack Trace
[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: 26 - Error Locating Server/Instance Specified)]
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +5103182
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning() +260
System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +389
System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject, Boolean withFailover) +197
System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout) +963
System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +195
System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +316
System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +5119675
System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +33
System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +524
System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66
System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +479
System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +108
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +126
System.Data.SqlClient.SqlConnection.Open() +125
WebMatrix.Data.Database.EnsureConnectionOpen() +44
WebMatrix.Data.<QueryInternal>d__0.MoveNext() +71
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +4231764
WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +103
WebMatrix.WebData.SimpleMembershipProvider.CheckTableExists(Database db, String tableName) +59
WebMatrix.WebData.SimpleMembershipProvider.CreateTablesIfNeeded() +55
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider sMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +73
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionStringName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
ASP._Page__AppStart_cshtml.Execute() in *:\HostingSpaces\***\***.com\wwwroot\_AppStart.cshtml:3
System.Web.WebPages.ApplicationStartPage.<ExecuteInternal>b__3() +65
System.Web.WebPages.ApplicationStartPage.<GetSafeExecuteStartPageThunk>b__a(Action action) +7
System.Web.WebPages.ApplicationStartPage.ExecuteInternal() +78
System.Web.WebPages.ApplicationStartPage.ExecuteStartPageInternal(HttpApplication application, Action`1 monitorFile, Func`2 fileExists, Func`2 createInstance, IEnumerable`1 supportedExtensions) +202
System.Web.WebPages.ApplicationStartPage.ExecuteStartPage(HttpApplication application, Action`1 monitorFile, Func`2 fileExists, Func`2 createInstance, IEnumerable`1 supportedExtensions) +41
[HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown.]
System.Web.WebPages.ApplicationStartPage.ExecuteStartPage(HttpApplication application, Action`1 monitorFile, Func`2 fileExists, Func`2 createInstance, IEnumerable`1 supportedExtensions) +88
System.Web.WebPages.ApplicationStartPage.ExecuteStartPage(HttpApplication application) +287
System.Web.WebPages.WebPageHttpModule.StartApplication(HttpApplication application, Action`1 executeStartPage, EventHandler applicationStart) +113
System.Web.WebPages.WebPageHttpModule.StartApplication(HttpApplication application) +71
System.Web.WebPages.WebPageHttpModule.Init(HttpApplication application) +217
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +517
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +194
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +339
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +253
[HttpException (0x80004005): Exception of type 'System.Web.HttpException' was thrown.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9090876
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +97
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +256
This is my Web.Config file:
<configuration>
<system.web>
<customErrors mode="Off"/>
<authentication mode="Forms" />
<roleManager enabled="true" />
<pages maintainScrollPositionOnPostBack="true">
<controls>
<add tagPrefix="ajaxToolkit" assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" />
</controls>
</pages>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Entity.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
<buildProviders>
<add extension=".edmx" type="System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider" />
</buildProviders>
</compilation>
</system.web>
<connectionStrings>
<add name="WhimsicalFurnishingEntities" connectionString="metadata=res://*/App_Code.WhimsicalFurnishingModel.csdl|res://*/App_Code.WhimsicalFurnishingModel.ssdl|res://*/App_Code.WhimsicalFurnishingModel.msl;provider connection string="data source=localhost\sqlexpress;Database=DBNAME;Uid=USERNAME;Password=PASSWORD;integrated security=True;user instance=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Is there something I am missing to add in my project? I am sure the data source is correct with localhost\sqlexpress.
Thank You
I am assuming you are publishing this to a different server like a virtual private host? If so, it is very weird that the datasource is sqlexpress.
Localhost\sqlexpress is for SQLServer Express which is typically installed on developer machines, if it's on a production server you will usually have SQLServer Enterprise or something else.
If you have provided the correct database connection string with SQL Server Instance, then you may restart your database server service. Then again try to publish your site. Please ask if it not worked for you.
I have version 1.6 of the MvcMiniProfiler referenced (via Nuget) and have set everything up as described on the project homepage at http://code.google.com/p/mvc-mini-profiler/.
I have the following code in the Web.config:
<system.data>
<DbProviderFactories>
<remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
<add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider" description="MvcMiniProfiler.Data.ProfiledDbProvider" type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler, Version=1.6.0.0, Culture=neutral, PublicKeyToken=b44f9351044011a3" />
</DbProviderFactories>
</system.data>
(The project homepage has Version=1.5.0.0 - the NuGet package has since been updated)
I have the following code in the Global.asax (and connection string also defined in Web.config):
protected void Application_Start()
{
Log.Info("ReCoupon has started.");
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
var factory = new SqlConnectionFactory(ConfigurationManager.ConnectionStrings["ReCouponContext"].ConnectionString);
var profiled = new MvcMiniProfiler.Data.ProfiledDbConnectionFactory(factory);
Database.DefaultConnectionFactory = profiled;
Database.SetInitializer(new ReCouponContextInitializer());
}
The profiler works great except that I can't get it to profile SQL. I am using SQL Server 2008 Express. I've been following the related issues on the Google Code project homepage and am totally stuck.
This one had me stumped for a long time too. It appears that the connection string naming convention takes precedence over Database.DefaultConnectionFactory.
Could you try renaming the connection string in the web.config?
from
<connectionStrings>
<add name="ReCouponContext" connectionString="..." />
</connectionStrings>
to
<connectionStrings>
<add name="ReCoupon" connectionString="..." />
</connectionStrings>
and then change
var factory = new SqlConnectionFactory(ConfigurationManager.ConnectionStrings["ReCouponContext"].ConnectionString);
to
var factory = new SqlConnectionFactory(ConfigurationManager.ConnectionStrings["ReCoupon"].ConnectionString);
I have a custom asp.net membership class I am building where I have a helper function that the
GetUser() method uses to convert the values from my database into a System.Web.Security.MembershipUser object.
private MembershipUser _converToMembershipUser(MembershipDBModel member)
{
System.Web.Security.MembershipUser membershipUser = new System.Web.Security.MembershipUser(
this.Name,
member.UserName,
member.UserID.ToString(),
member.Email,
member.PasswordQuestion,
member.Comment,
member.IsApproved,
member.IsLockedOut,
member.CreationDate,
member.LastLoginDate,
member.LastActivityDate,
member.LastPasswordChangedDate,
member.LastLockedOutDate);
return membershipUser;
}
This is the error that I keep getting when the above method is being called. I have not idea how to get around this so any suggestion is very welcome.
System.IO.FileLoadException was caught
Message=The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
Source=System.Web
StackTrace:
at System.Web.Security.Membership.Initialize()
at System.Web.Security.MembershipAdapter.get_Providers()
at System.Web.Security.MembershipUser..ctor(String providerName, String name, Object providerUserKey, String email, String passwordQuestion, String comment, Boolean isApproved, Boolean isLockedOut, DateTime creationDate, DateTime lastLoginDate, DateTime lastActivityDate, DateTime lastPasswordChangedDate, DateTime lastLockoutDate)
at TMTechMembershipProvider.MembershipProvider._converToMembershipUser(MembershipDBModel member) in d:\Visual Studio 2010\Projects\TMTechMembershipProvider\TMTechMembershipProvider\TMTechMembershipProvider.cs:line 1005
at TMTechMembershipProvider.MembershipProvider.GetUser(String username) in d:\Visual Studio 2010\Projects\TMTechMembershipProvider\TMTechMembershipProvider\TMTechMembershipProvider.cs:line 965
at TMTechMembershipProvider.MembershipProvider.CreateUser(String username, String password, String email, String passwordQuestion, String passwordAnswer, Boolean isApproved, Object providerUserKey, MembershipCreateStatus& status) in d:\Visual Studio 2010\Projects\TMTechMembershipProvider\TMTechMembershipProvider\TMTechMembershipProvider.cs:line 435
InnerException:
System.Web.Security.MembershipAdapter.get_Providers() Initialize() The given assembly name or codebase was invalid.
config file
<?xml version="1.0"?>
<configuration>
<appSettings></appSettings>
<connectionStrings>
<add name="MembershipDBContext" providerName="System.Data.SqlServerCe.4.0" connectionString="data source=MembershipDBContext.sdf"/>
</connectionStrings>
<system.web>
<membership>
<providers>
<!--<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider" type="TMTechMembershipProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cbae438f5bab0724" connectionStringName="MembershipDBContext" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="MyUnitTests" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>-->
<clear/>
<!--<add name="TMTechMembershipProvider.MembershipProvider" type="TMTechMembershipProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cbae438f5bab0724" connectionStringName="MembershipDBContext" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="MyUnitTests" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>-->
<add name="TMTechMembershipProvider"
type="TMTechMembershipProvider.TempMembershipProvider"
connectionStringName="MembershipDBContext"
enablePasswordRetrieval="true"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="MyUnitTests"
requiresUniqueEmail="true"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""/>
</providers>
</membership>
<machineKey validationKey="EAA358B778400490DE16A414AC2144C740874D426214CA81D8265354535ACCA9C0238D5C20021D4335DBE1171F31C02F0AB8ADD5B1EE2A6E07CC768F04B20F30" decryptionKey="AF622C5C9796D67DEB876483F1341E3708CA056B1EB031CEAD6FD7CBD0F13A50" validation="SHA1" decryption="AES"/>
</system.web>
<!--<system.web>
<membership>
<providers>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LocalSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="1"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression="" />
</providers>
</membership>
</system.web>-->
<startup>
<!--<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>-->
</startup>
</configuration>
Error: "The given assembly name or codebase was invalid"
Your type attribute:
type="TMTechMembershipProvider.TempMembershipProvider"
Your type attribute in your commented line:
type="TMTechMembershipProvider, Version=1.0.0.0, Culture=neutral, PublicKeyToken=cbae438f5bab0724"
Your comment:
i tend to agree but this is needle in haystack. This is what I thought the Fusion Log Viewer was for to help identify what is failing to load.
sry, but lol :)
Update 1: re the comment:
Just found it funny, couldn't resist. Meant no harm and was not imply anything with it, we've all been there.
Now on a more serious note, it still seems an issue with specifically that line.
Let's compare it with the type line of the asp.net provider:
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
[Provider class (including the namespace)], [dll], [Version], ...
It seems you are missing either the class or the dll. Hoping that solves it, good luck.
This is not likely to be a code issue, it is a dll reference issue.
You need to carefully review any "type", "assembly", or "publicKeyToken" xml attributes in your web.config. The most likely cause is that you've mis-copied the public key token for an assembly. I would start by checking anywhere you've referenced the System.Web assembly and make sure that the public key token is exactly right and that there are no mispellings in any type names.
In particular, check the type attribute in the add element under the provider and membership element in your web.config. Also, if the custom membership class is implemented in a separate dll, be certain that you are actually referencing the correct version of the System.Web assembly from that dll.