I need to connect with oracle database using entity framework in my MVC WebAPI project. I am using VS2022 with .Net Framework 4.8. I prefer working with code first approach and need to auto create the Database and Tables if not exists.
The packages I have added in my project for oracle are
My web.config of the project is as below
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
<!-- 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" />
</configSections>
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<!-- Customize these connection alias settings to connect to Oracle DB -->
<dataSource alias="OracleDataSource" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=175.16.2.1)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=oracledb12c))) " />
</dataSources>
</version>
</oracle.manageddataaccess.client>
<connectionStrings>
<add name="OracleDbContext" providerName="Oracle.ManagedDataAccess.Client" connectionString="User Id=oracle_user;Password=oracle_user_password;Data Source=OracleDataSource" />
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.8" />
<httpRuntime targetFramework="4.8" />
</system.web>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<publisherPolicy apply="no" />
<assemblyIdentity name="Oracle.ManagedDataAccess" publicKeyToken="89b483f429c47342" culture="neutral" />
<bindingRedirect oldVersion="4.122.0.0 - 4.65535.65535.65535" newVersion="4.122.21.1" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<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.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</DbProviderFactories>
</system.data>
<entityFramework>
<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.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers>
</entityFramework>
</configuration>
My DBContext class and model class are
public class OracleDbContext : DbContext
{
public OracleDbContext() : base("OracleDbContext")
{
}
public DbSet<User> Users { get; set; }
}
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
}
After all this when I run add-migration m1, it runs successfully and created its cs file. After that when I run Update-Database, it is giving me an exception and DB not created. The exception I am getting is as follows
Oracle.ManagedDataAccess.Client.OracleException (0x80004005): ORA-01918: user 'dbo' does not exist
at OracleInternal.ServiceObjects.OracleConnectionImpl.VerifyExecution(Int32& cursorId, Boolean bThrowArrayBindRelatedErrors, SqlStatementType sqlStatementType, Int32 arrayBindCount, OracleException& exceptionForArrayBindDML, Boolean& hasMoreRowsInDB, Boolean bFirstIterationDone)
at 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, OracleConnection connection, Boolean isFromEF)
at Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ExecuteSql(MigrationStatement migrationStatement, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinTransaction(IEnumerable`1 migrationStatements, DbTransaction transaction, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsWithinNewTransaction(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection, DbInterceptionContext interceptionContext)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatementsInternal(IEnumerable`1 migrationStatements, DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements, DbTransaction existingTransaction)
at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, VersionedModel targetModel, IEnumerable`1 operations, IEnumerable`1 systemOperations, Boolean downgrading, Boolean auto)
at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration)
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Infrastructure.Design.Executor.Update.<>c__DisplayClass0_0.<.ctor>b__0()
at System.Data.Entity.Infrastructure.Design.Executor.OperationBase.Execute(Action action)
ORA-01918: user 'dbo' does not exist
So, I don't understand why this user not exist error is coming. Any help regarding this will be beneficial.
Related
I am having trouble figuring out an issue with an angular 4 preflight request not passing a CORS access-control check: “No 'Access-Control-Allowed-Origin'”. I am able to successfully get data from the db but not able to post/save data. I am using VS code for my front end to access my visual studio 2015 back end. My Web Api controller has an attribute of:
[EnableCors(origins: "*", headers: "*", methods: "*")]
[HttpPost]
public async Task<IHttpActionResult> Post([FromBody]Employee employee)
{
_repo.Create(employee);
return Ok();
}
…but when request is made, I'm getting an error of:
XMLHttpRequest cannot load http://localhost:54429/api/createEmployee/.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access
In my vs code, my service looks like this:
postEmployeeForm(employee: Employee): Observable<any>{
let body = JSON.stringify(employee);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
console.log('posting employee ' , employee);
return this.http.post("http://localhost:54429/api/employees/", body, options)
.map(this.extractData)
.catch(this.handleError)
}
405 Response after removing the body and options from the post.
Not sure what I am missing.
web config
<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" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-TBryant.WebAPI-20170303082842.mdf;Initial Catalog=aspnet-TBryant.WebAPI-20170303082842;Integrated Security=True" providerName="System.Data.SqlClient" />
<!--<add name="SampleEntities" connectionString="metadata=res://*/MyModels.csdl|res://*/MyModels.ssdl|res://*/MyModels.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\MSSQLLocalDB;initial catalog=Sample;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />-->
<add name="northwindEntities" connectionString="metadata=res://*/NorthwindModel.csdl|res://*/NorthwindModel.ssdl|res://*/NorthwindModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\MSSQLLocalDB;initial catalog=northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="SampleEntities1" connectionString="metadata=res://*/EmployeeDataModel.csdl|res://*/EmployeeDataModel.ssdl|res://*/EmployeeDataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(localdb)\MSSQLLocalDB;initial catalog=Sample;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings></appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<system.webServer>
<!--<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELTE,OPTIONS"/>
</customHeaders>
</httpProtocol>-->
<modules>
<remove name="FormsAuthentication" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
I have managed to reproduce your problem. The solution that worked for me is to replace part of Web.config. Under system.webServer, either add or replace the existing <handlers> block with the following:
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
If you already have that exact content in place, try removing it, running the server, stopping the server, re-adding the content and then running the server again. I know that sounds odd but I think it's what ended up fixing it for me. Good luck.
UPDATE #1
Now that we have something happening on the server side of things, try removing the Content-Type header and JSON.stringify stuff in your Angular code. i.e.:
postEmployeeForm(employee: Employee): Observable<any>{
console.log('posting employee ' , employee);
return this.http.post("http://localhost:54429/api/employees/", employee)
.map(this.extractData)
.catch(this.handleError)
}
UPDATE #2
I think your IIS Express configuration may be overriding some of the changes we've made. Close Visual Studio, delete the .vs/config folder at the root of the solution in Windows Explorer and then try re-running the project. This should reset your IIS Express settings. If you're not completely comfortable with deleting the folder, just rename it and follow the same process.
UPDATE #3
I've managed to get your example project running. It demonstrates a problem with CORS, but this was fixed by using my initial suggestion of adding config.EnableCors:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The problem seems to be on the server side.
Before any non-simple CORS request, the browser sends an OPTIONS preflight request to make sure that this server allows non-simple CORS requests. (POST requests with application/json are not considered simple)
In your case, as the error implies, only if the response to the preflight OPTIONS request contains the access-control-allow-origin header with the value 'http://localhost:4200' your original POST request will be sent. (The response in your screenshot doesn't contain this header)
You didn't write much about your server implementation, but if you're using asp.net-web-api here is a simple (a bit hacky) solution on how to make it respond to these preflight OPTIONS requests - link (Also see the comment there by Marcus Cunningham)
this is all about server side configuration. for your development side testing you can use Google chrome and its plugin.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
hope this helpful.
I'm using ASP.Net MVC 3, spring.net 1.3.2 and nhibernate 3.2. I've been struggling to get the web application to run in IIS 7.5. It works fine inside Visual Studio 2010.
The error I'm getting is
No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
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: NHibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
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:
[HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here]
Spring.Data.NHibernate.SpringSessionContext.CurrentSession() in c:\_prj\spring-net\trunk\src\Spring\Spring.Data.NHibernate12\Data\NHibernate\SpringSessionContext.cs:72
Technolog.Rma.Business.Repositories.RepairBatchDAO.findRepairBatchPageCount(String login, Int32 rowsPerPage) in C:\work\samplemvc\src\Technolog.Rma.Business\Repositories\RepairBatchDAO.cs:55
_dynamic_Technolog.Rma.Business.Repositories.RepairBatchDAO.findRepairBatchPageCount(Object , Object[] ) +273
Spring.Reflection.Dynamic.SafeMethod.Invoke(Object target, Object[] arguments) in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Reflection\Dynamic\DynamicMethod.cs:156
Spring.Aop.Framework.DynamicMethodInvocation.InvokeJoinpoint() in c:\_prj\spring-net\trunk\src\Spring\Spring.Aop\Aop\Framework\DynamicMethodInvocation.cs:100
Spring.Dao.Support.PersistenceExceptionTranslationInterceptor.Invoke(IMethodInvocation invocation) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data\Dao\Support\PersistenceExceptionTranslationInterceptor.cs:181
<snip/>
My web.config file is
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
Spring.Context.Support.ContextHandler, Spring.Core
<resource uri="~/Config/propertyConfigurer.xml" />
-->
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc3" />
</sectionGroup>
</configSections>
<appSettings>
<add key="dataFile" value="App_Data\data.db3" />
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="SessionFactory"/>
</appSettings>
<spring>
<context>
<resource uri="file://~/Config/propertyConfigurer.xml" />
<resource uri="file://~/Config/sessionFactory.xml" />
<resource uri="file://~/Config/mappers.xml" />
<resource uri="file://~/Config/repositories.xml" />
<resource uri="file://~/Config/controllers.xml" />
<resource uri="file://~/Config/scopedobjects.xml" />
<resource uri="file://~/Config/utils.xml" />
</context>
</spring>
<system.web>
<httpModules>
<!--
<add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
<add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate32"/>
-->
</httpModules>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<customErrors mode="Off"/>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
<add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate32"/>
</modules>
<!--
<handlers>
<add name="SpringPageHandler" verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
<add name="SpringWebServiceHandler" verb="*" path="*.asmx" type="Spring.Web.Services.WebServiceHandlerFactory, Spring.Web" />
<add name="SpringContextMonitor" verb="*" path="ContextMonitor.ashx" type="Spring.Web.Support.ContextMonitor, Spring.Web"/>
</handlers>
-->
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.7.0" newVersion="4.0.7.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
My sessionFactory.xml file is
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net"
xmlns:db="http://www.springframework.net/database"
xmlns:tx="http://www.springframework.net/tx">
<object
id="siteRoot"
type="System.Web.Hosting.HostingEnvironment, System.Web"
factory-method="get_ApplicationPhysicalPath" />
<object
id="dataFile"
type="System.IO.Path, mscorlib"
factory-method="Combine">
<constructor-arg name="path1" ref="siteRoot" />
<constructor-arg name="path2" value="${dataFile}" />
</object>
<db:provider id="dbProvider"
provider="System.Data.SqlClient"
connectionString="Data Source=AJASQL7;Initial Catalog=Xanadu;User ID=RMA;Password=RMA;"/>
<object id="sessionFactory" scope="application" type="Spring.Data.NHibernate.LocalSessionFactoryObject, Spring.Data.NHibernate32">
<property name="DbProvider" ref="dbProvider"/>
<property name="MappingAssemblies">
<list>
<value>Technolog.Rma.Business</value>
</list>
</property>
<property name="HibernateProperties">
<dictionary>
<entry key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<entry key="dialect" value="NHibernate.Dialect.MsSql7Dialect"/>
<entry key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<entry key="use_proxy_validator" value="false" />
<entry key="current_session_context_class" value="Spring.Data.NHibernate.SpringSessionContext, Spring.Data.NHibernate32"/>
</dictionary>
</property>
</object>
<!-- Transaction Management Strategy - local database transactions -->
<object id="transactionManager"
type="Spring.Data.NHibernate.HibernateTransactionManager, Spring.Data.NHibernate32">
<property name="DbProvider" ref="dbProvider"/>
<property name="SessionFactory" ref="sessionFactory"/>
</object>
<!-- Exception translation object post processor -->
<object type="Spring.Dao.Attributes.PersistenceExceptionTranslationPostProcessor, Spring.Data"/>
</objects>
Part of my RepairBatchDao is
[Repository]
class RepairBatchDAO : IRepairBatchDAO
{
public ISessionFactory SessionFactory { get; set; }
public long findRepairBatchPageCount(string login, int rowsPerPage)
{
var rowCount = 1L;
var session = SessionFactory.GetCurrentSession(); // line 55
var transaction = session.BeginTransaction();
try
{
transaction = session.BeginTransaction();
var hqlCountQuery = session.CreateQuery("select count(*) from Technolog.Rma.Business.Domain.RepairBatch rb where rb.Customer.Login=?")
.SetParameter(0, login);
rowCount = hqlCountQuery.UniqueResult<long>();
transaction.Commit();
return (rowCount + rowsPerPage - 1) / rowsPerPage;
}
catch
{
if (transaction != null) transaction.Rollback();
}
finally
{
if (session != null) session.Close(); // I shouldn't be doing this...
}
return 0L;
}
// snip ...
I've spent too much time trying to fix this myself. I'm hoping somebody can point me in the right direction. I've checked various posts in stackoverflow (too many to mention) but they haven't helped.
I'm a Java guy and this is my first .net project so aren't sure whether I've done anything silly.
25/9/2012
I've made changes to my customerDAO
public class CustomerDAO : ICustomerDAO
{
public ISessionFactory SessionFactory { get; set; }
private TransactionTemplate tt;
public IPlatformTransactionManager TransactionManager
{
set { tt = new TransactionTemplate(value); }
}
<snip/>
public Customer find(string login)
{
IList<Customer> customers;
Object result = tt.Execute(delegate(ITransactionStatus status) //line 42
{
var transaction = status.Transaction;
var session = this.SessionFactory.GetCurrentSession();
//var transaction = session.BeginTransaction();
try
{
customers = session.CreateQuery("from Technolog.Rma.Business.Domain.Customer Customer where Customer.Login=?")
.SetParameter(0, login)
.List<Customer>();
if (customers.Count > 0)
{
return customers[0];
}
}
catch
{
}
finally
{
if (session != null) session.Close();
}
return null;
});
return (Customer)result;
}
The error I'm now getting is
Server Error in '/RMA' Application.
--------------------------------------------------------------------------------
Cannot access a disposed object.
Object name: 'AdoTransaction'.
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.ObjectDisposedException: Cannot access a disposed object.
Object name: 'AdoTransaction'.
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:
[ObjectDisposedException: Cannot access a disposed object.
Object name: 'AdoTransaction'.]
NHibernate.Transaction.AdoTransaction.Commit() +425
Spring.Data.NHibernate.HibernateTransactionManager.DoCommit(DefaultTransactionStatus status) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data.NHibernate\Data\NHibernate\HibernateTransactionManager.cs:579
Spring.Transaction.Support.AbstractPlatformTransactionManager.ProcessCommit(DefaultTransactionStatus status) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data\Transaction\Support\AbstractPlatformTransactionManager.cs:853
Spring.Transaction.Support.TransactionTemplate.Execute(TransactionDelegate transactionMethod) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data\Transaction\Support\TransactionTemplate.cs:159
Technolog.Rma.Business.Repositories.CustomerDAO.find(String login) in C:\work\samplemvc\src\Technolog.Rma.Business\Repositories\CustomerDAO.cs:42
_dynamic_Technolog.Rma.Business.Repositories.CustomerDAO.find(Object , Object[] ) +147
Spring.Reflection.Dynamic.SafeMethod.Invoke(Object target, Object[] arguments) in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Reflection\Dynamic\DynamicMethod.cs:156
Spring.Aop.Framework.DynamicMethodInvocation.InvokeJoinpoint() in c:\_prj\spring-net\trunk\src\Spring\Spring.Aop\Aop\Framework\DynamicMethodInvocation.cs:100
Spring.Dao.Support.PersistenceExceptionTranslationInterceptor.Invoke(IMethodInvocation invocation) in c:\_prj\spring-net\trunk\src\Spring\Spring.Data\Dao\Support\PersistenceExceptionTranslationInterceptor.cs:190
CompositionAopProxy_33677284ca854c0b8c01a5b0ae0a0524.find(String login) +383
Technolog.Rma.Web.Controllers.HomeController.Index(Int32 page) in C:\work\samplemvc\src\Technolog.Rma.Web\Controllers\HomeController.cs:36
lambda_method(Closure , ControllerBase , Object[] ) +112
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +248
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +125
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +691
System.Web.Mvc.Controller.ExecuteCore() +162
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +305
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +62
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +469
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
As per the comments above I followed the instructions for implementing osiv. I also found I was closing a session when I should have left it open thus causing a
Cannot access a disposed object.
My web.config file for using OSIV is
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
Spring.Context.Support.ContextHandler, Spring.Core
<resource uri="~/Config/propertyConfigurer.xml" />
-->
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc3" />
</sectionGroup>
</configSections>
<appSettings>
<add key="dataFile" value="App_Data\data.db3" />
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="Spring.Data.NHibernate.Support.OpenSessionInViewModule.SessionFactoryObjectName" value="SessionFactory"/>
</appSettings>
<spring>
<context>
<resource uri="file://~/Config/propertyConfigurer.xml" />
<resource uri="file://~/Config/sessionFactory.xml" />
<resource uri="file://~/Config/mappers.xml" />
<resource uri="file://~/Config/repositories.xml" />
<resource uri="file://~/Config/controllers.xml" />
<resource uri="file://~/Config/scopedobjects.xml" />
<resource uri="file://~/Config/utils.xml" />
</context>
</spring>
<system.web>
<httpModules>
<add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
<add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate32"/>
</httpModules>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<customErrors mode="Off"/>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
<add name="OpenSessionInView" type="Spring.Data.NHibernate.Support.OpenSessionInViewModule, Spring.Data.NHibernate32"/>
</modules>
<!--
<handlers>
<add name="SpringPageHandler" verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
<add name="SpringWebServiceHandler" verb="*" path="*.asmx" type="Spring.Web.Services.WebServiceHandlerFactory, Spring.Web" />
<add name="SpringContextMonitor" verb="*" path="ContextMonitor.ashx" type="Spring.Web.Support.ContextMonitor, Spring.Web"/>
</handlers>
-->
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.7.0" newVersion="4.0.7.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Note that references to osiv and spring WebSupportModule are in / to make it work in my dev environment and also in / to make the application work in IIS 7.5
I'm also using lazy loading in my views so osiv is the better solution. I showed the programmatic transaction control in my question because that's how far I had got with trying to come up with a solution.
You have configured a TransactionManager, but you are not using it. Before calling SessionFactory.GetCurrentSession();, try starting a transaction on your transaction manager. When using Spring's transaction management, you shouldn't explicitly use NHibernate's transaction support.
You can do this programmatically or declaratively; at this stage I'd try the programmatic approach first.
I am using the valums ajax upload component (http://valums.com/ajax-upload/). My site is going to have users uploading files that are greater than 500MB in size. I have a strict pure HTML requirement. I can successfully upload files of this size in Internet Explorer. However, when I attempt to use Chrome, the file is never written on the server, but only in the case of large files. For smaller files, the file is successfully written. But for larger files, I get an "Maximum request length exceeded error".
Considering I can upload files of this size with IE, I know that the settings in my web.config are correct. This leads me to believe there is something in the XHR implementation that needs to be set to accommodate for files of this size. However, i'm not sure what that is. Can anyone provide a sample of values use with ASP.NET MVC that:
Allows for large (>500 mb) file uploads in IE AND Chrome
Shows the progress of an uploaded file in browsers that support XHR
Thank you so MUCH!
I am unable to reproduce your issue. Here's my setup in which I limited the files to 1GB.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Upload(string qqfile)
{
var path = Server.MapPath("~/App_Data");
var file = Path.Combine(path, qqfile);
using (var output = System.IO.File.OpenWrite(file))
{
Request.InputStream.CopyTo(output);
}
return Json(new { success = true });
}
}
Index.cshtml view:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test</title>
<link href="#Url.Content("~/Content/fileuploader.css")" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="file-uploader">
<noscript>
<p>Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script src="#Url.Content("~/Scripts/fileuploader.js")" type="text/javascript"></script>
<script type="text/javascript">
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '#Url.Action("upload")'
});
</script>
</body>
</html>
web.config:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="webpages:Version" value="1.0.0.0"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Things to notice in web.config is <httpRuntime>:
<httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
and if you are hosting this site in IIS7+ (<requestLimits>) as well is required:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
With this setup I am able to upload files up to 1GB of size in the latest versions of FireFox 8.0, IE9 and Chrome 16.
I have hosted the site locally using IIS Express.
I am having my mvc project that is working fine on my local machine. However, once posted on the server, the users can`t access the login the secong time they are trying to access the website. They have to delete the cookies. Why is that so? How can I correct that?
Global.asax.cs
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.cookies[FormsAuthentication.FormsCookieName].Value);
args.user = new MyProject.Web.UI.Classes.UserPrincipal(GetUserFromCache(ticket.Name))
SourceFile: c:\Myproject\Code\MvcUI\Global.asax.cs
public void FormsAuthentication_OnAuthenticate(object sender, FormsAuthenticationEventArgs args)
{
if (FormsAuthentication.CookiesSupported)
{
if (null != Request.Cookies[FormsAuthentication.FormsCookieName])
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
args.User = new MyProject.Web.UI.Classes.UserPrincipal(GetUserFromCache(ticket.Name));
}
}
else
throw new HttpException("Cookieless Forms Authentication is not supported for this application.");
}
public void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs args)
{
string username = args.Identity.Name.Substring(args.Identity.Name.IndexOf("\\") + 1);
Myproject.API.User user = GetUserFromCache(username);
if (null == user)
throw new HttpException("User could not be found.");
args.User = new MyProject.Web.UI.Classes.UserPrincipal(user);
}
AccountController
[HttpPost]
public bool LogOn(string userName, string password, string returnUrl, bool rememberMe = false)
{
MyProject.API.User user = MyProject.API.User.Load(userName);
string errorMessage = "Your user name and/or password is incorrect.";
if (null != user && user.IsValidPassword(password))
{
user.LastLoginDate = DateTime.Now;
user.Save();
FormsAuthentication.SetAuthCookie(userName, rememberMe);
return true;
}
else
throw new Exception(errorMessage);
}
web.config
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="MvcUI.HtmlHelpers" />
<add namespace="MyProject.API" />
<add namespace="MvcUI.Models" />
</namespaces>
</pages>
</system.web.webPages.razor>
<connectionStrings>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Management, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
</assemblies>
<buildProviders>
<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</buildProviders>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
</namespaces>
</pages>
<httpHandlers>
<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
validate="false" />
</httpHandlers>
</system.web>
<nhibernate>
<add key="hibernate.connection.provider" value="NHibernate.Connection.DriverConnectionProvider"/>
<add key="hibernate.dialect" value="NHibernate.Dialect.MsSql2000Dialect"/>
<add key="hibernate.connection.driver_class" value="NHibernate.Driver.SqlClientDriver"/>
<add key="hibernate.connection.connection_string" value="Server=.\SQLEXPRESS;Database=myDatabase;User=me;Pwd=password;"/>
<add key="hibernate.show_sql" value="false"/>
</nhibernate>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
<handlers>
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
account Model
public interface IFormsAuthenticationService
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public class FormsAuthenticationService : IFormsAuthenticationService
{
public void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
The error message points to the Gloabal.asax.cs file and shown above.
Error message:
I have also included a machine key generated but it has not solved the problem,
Based on your feedback, the reason you are experiencing that error may be due to the fact you are using an auto-generated machineKey for your application (also possibly in multiple machines/app pools or even in one app pool that recycles too frequently).
Please make sure to check this one out.
Have you applied this patch?
I see you don't have ticketCompatibilityMode set as .net 4 has changed the way encryption works.
<forms
loginUrl="/Login.aspx"
timeout="2880"
ticketCompatibilityMode="Framework20"
domain="domain.com"/>
Check that you have the same machineKeys on both systems. Make sure you also apply that patch.
Because the patch modifies the encryption/signing behavior of certain features in ASP.NET, it is important that you apply it to all machines in a web-farm. If you have a mix-match of patched/un-patched systems you’ll have forms-authentication, webresource.axd, and scriptresource.axd requests succeed/fail depending on which server they hit in the farm (since the encryption used would be different across them).
I assume your users are redirected to somewhere upon reaching the login page if the request is authenticated and thus they can't access the login page after the first successful login.
If this is the case, you may want to force your users to sign out upon reaching the login page, on the first load of the page. For example (Razor syntax, C#):
#if (!IsPost && Request.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
On the GET (not post) of LogOn action method. Check if user is authenticated and log out if so.
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
}
Thanks to all of you for having tried to reply to the question. Indeed they were all helpful. I solved the problem myself by adding a machinekey to the wenconfig, as well as a form name had to be there. without te form name, even the machine key was not useful
When my Razor view calls #Html.OpenIdSelector(... I get an InvalidOperationException:
The current IHttpHandler is not one of
types: System.Web.UI.Page,
DotNetOpenAuth.IEmbeddedResourceRetrieval.
An embedded resource URL provider must
be set in your .config file.
What exactly should I set in the config file?
Just NuGet the DotNetOpenAuth package. It will setup everything you need in your config file:
Right click on the References of your web project in the solution explorer
Add Library Package Reference...
Click on the Online tab.
In the search box type dotnetopenauth
Click Install
Everything will be automatically setup and the correct assemblies will be downloaded from the internet and added as reference.
Here's how the web.config file looks like after performing this:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true" />
</configSections>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear />
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
<legacyHMACWarning enabled="0" />
</runtime>
<uri>
<!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
which is necessary for OpenID urls with unicode characters in the domain/host name.
It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. -->
<idn enabled="All" />
<iriParsing enabled="true" />
</uri>
<system.net>
<defaultProxy enabled="true" />
<settings>
<!-- This setting causes .NET to check certificate revocation lists (CRL)
before trusting HTTPS certificates. But this setting tends to not
be allowed in shared hosting environments. -->
<!--<servicePointManager checkCertificateRevocationList="true"/>-->
</settings>
</system.net>
<dotNetOpenAuth>
<!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. -->
<!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ -->
<openid>
<relyingParty>
<security requireSsl="false" />
<behaviors>
<!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
with OPs that use Attribute Exchange (in various formats). -->
<add type="DotNetOpenAuth.OpenId.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth" />
</behaviors>
</relyingParty>
</openid>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
</dotNetOpenAuth>
</configuration>
UPDATE:
You could implement a custom resource retrieval provider:
public class CustomResourceProvider : IEmbeddedResourceRetrieval
{
public Uri GetWebResourceUrl(Type someTypeInResourceAssembly, string manifestResourceName)
{
return new Uri("http://www.google.com");
}
}
and then register it in web.config:
<dotNetOpenAuth>
<webResourceUrlProvider type="AppName.CustomResourceProvider, AppName" />
...
</dotNetOpenAuth>
But I would recommend you using the openid-selector library for generating login forms.
I came across this problem when I was trying to get the NerdDinner OpenID working for MVC3/razor. The solution that has worked for me is:
Create this class in your solution: (this was found in one of the NerdDinner builds - http://nerddinner.codeplex.com/SourceControl/changeset/view/55257#1328982 (thanks to JasonHaley)
for some reason, this file isn't in the latest build for NerdDinner MVC3/Razor
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth;
namespace <Your App>.Services
{
public class EmbeddedResourceUrlService : IEmbeddedResourceRetrieval
{
private static string pathFormat = "{0}/{1}/Resource/GetWebResourceUrl?assemblyName={2}&typeName={3}&resourceName={4}";
//private static string pathFormat = "{0}/Resource/GetWebResourceUrl";
public Uri GetWebResourceUrl(Type someTypeInResourceAssembly, string manifestResourceName)
{
if (manifestResourceName.Contains("http"))
{
return new Uri(manifestResourceName);
}
else
{
var assembly = someTypeInResourceAssembly.Assembly;
// HACK
string completeUrl = HttpContext.Current.Request.Url.ToString();
string host = completeUrl.Substring(0,
completeUrl.IndexOf(HttpContext.Current.Request.Url.AbsolutePath));
var path = string.Format(pathFormat,
host,
HttpContext.Current.Request.ApplicationPath.Substring(1),
HttpUtility.UrlEncode(assembly.FullName),
HttpUtility.UrlEncode(someTypeInResourceAssembly.ToString()),
HttpUtility.UrlEncode(manifestResourceName));
return new Uri(path);
}
}
}
}
Then in your web.config, add this line:
<webResourceUrlProvider type="<Your App>.Services.EmbeddedResourceUrlService, <Your App>" />
just put in the DotNetOpenAuth section
you will also need this route set up: ( Html.OpenIdSelectorScripts helper method throwing NullReferenceException )
routes.MapRoute(
"OpenIdDiscover",
"Auth/Discover"
);