7

I am trying to connect to an oracle database in my controller:

 using Oracle.DataAccess.Client;
 using Oracle.DataAccess.Types;

 // Other code

 OracleConnection con;
 con = new OracleConnection();

 con.ConnectionString = "DATA SOURCE=<DSOURCE_NAME>;PERSIST SECURITY INFO=True;USER ID=******;PASSWORD=*******";

 con.Open();

The connection test is successful and I can navigate through tables, functions, etc. in Visual Studio's Server Explorer, but when I try to execute the above code I consistently get[NullReferenceException: Object reference not set to an instance of an object.] on the con.Open(); line.

This is my first time using ODP for .NET and I am generally new to C# as well. Any ideas on what could be the problem?

Stack Trace:

    Source Error: 


Line 27: 
Line 28: 
Line 29:             con.Open();
Line 30: 

Source File: c:\Program Files\Project\source\Project\Project\Areas\Custom\Controllers\HomeController.cs    Line: 29 

 Stack Trace: 


    [NullReferenceException: Object reference not set to an instance of an object.]
   Oracle.DataAccess.Client.OracleConnection.Open() +12156
   Project.Areas.Custom.Controllers.HomeController.Id() in c:\Program Files\Project\source\Project\Project\Areas\Custom\Controllers\HomeController.cs:29
   lambda_method(Closure , ControllerBase , Object[] ) +101
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +435
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
   System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
   System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
   System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +44
   System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +34
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +69
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +123
   System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +133
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1556

[HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.]
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3424518
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +77
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +29
   System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +24
   System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +977
   System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues) +112
   System.Web.Mvc.Html.ChildActionExtensions.Action(HtmlHelper htmlHelper, String actionName, String controllerName) +47
   ASP._Page_Areas_Custom_Views_Home_Home_cshtml.Execute() in c:\Program Files\Project\source\Project\Project\Areas\Custom\Views\Home\Home.cshtml:13
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +270
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +122
   System.Web.WebPages.StartPage.RunPage() +63
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +100
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
   System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
   System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
   System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +37
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9711525
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Mr Man
  • 1,498
  • 10
  • 33
  • 54
  • 1
    You should test this in a smaller testing environment. Create a [mcve]. – nvoigt Oct 22 '15 at 06:30
  • 1
    Please add a try catch block around the open() call and provide the ORA error in the OracleException. – Christian Shay Oct 22 '15 at 06:43
  • @ChristianShay Sorry that I am just getting back to you. I added the try catch block, and it returned ORA12154 - TNS could not be resolved. After some research, I added an SID to my tnsnames.ora file in my ODP for .NET Oracle home path, and it worked! I would love to mark you for an answer if you create one (Though the question should probably change to something about TNS) – Mr Man Oct 22 '15 at 19:47
  • Please post the entire controller method. You should be getting an error. I think you're doing something wrong within the async pattern. – b_levitt Nov 20 '15 at 16:51

5 Answers5

6

I had same problem and solved adding to my C# Project References Oracle.ManagedDataAccess instead of Oracle.DataAccess.
To do this go to (Tools / Nugget Package Manager / Nugget Package Manager for Solution) browse for Oracle References and select Oracle.ManagedDataAccess.
Then you need to comment or delete your actual DataAccess calls to ManagedDataAccess as:

//using Oracle.DataAccess.Client; 
//using Oracle.DataAccess.Types;
using Oracle.ManagedDataAccess.Client;

No need to change your Connection Code, only the using coding. After it works you can delete Oracle.DataAccess from your Project References

ijimenez123
  • 61
  • 1
  • 4
2

I had the same problem when I started to use ODP.NET.

You can adjust your code like this:

try
{
    OracleConnection con;
    con = new OracleConnection();

    con.ConnectionString = "DATA SOURCE=<DSOURCE_NAME>;PERSIST SECURITY INFO=True;USER ID=******;PASSWORD=*******";

    con.Open();
}
catch (OracleException ex)
{
    Console.WriteLine("Oracle Exception Message");
    Console.WriteLine("Exception Message: " + ex.Message);
    Console.WriteLine("Exception Source: " + ex.Source);
}
catch (Exception ex)
{
    Console.WriteLine("Exception Message");
    Console.WriteLine("Exception Message: " + ex.Message);
    Console.WriteLine("Exception Source: " + ex.Source);
}

You can get more information about your error here: ORA-12154

The problem is your Data Source in your connection string. I assume that it looks like this: Data Source=Server.Source as you could find in your TNSNAMES.ORA file on your computer.

The problem is that ODP.NET does not read the TNSNAMES.ORA file as Visual Studio does.

You have multiple choices to solve this issue:

  1. Edit your Web.Config or App.config file to tell ODP.NET how to handle your source.
  2. Copy your TNSNAMES.ORA file in the same directory as the .exe. (If it's not a web app)
  3. Change the Data Source in order to write the long version instead of the alias. E.g. : Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=sales-server)......)))

My favorite method is the #3. It's a lot easier to debug when you have a problem.

You can find more information in the dataSources Section of the Configuring Oracle Data Provider for .NET documentation.

Maxime
  • 8,645
  • 5
  • 50
  • 53
  • It is not correct that "ODP.NET does not read TNSNAMES.ORA file". It uses the "TNS_ADMIN" variable to find it, which depending on how you installed ODP.NET might be set at install time in machine.config (OUI machine wide install), or not at all (Nuget). Your app will also read the tnsnames .ora file found in the working directory of your app when TNS_ADMIN is not set. See the documentation for the specifics. – Christian Shay Oct 23 '15 at 15:15
  • Did you read the full answer ? You missed the last part of my sentence which "as Visual Studio does" explaining why the connection test works but it doesn't in the code. Then, for all 3 options, I got them from the documentation I linked in my answer! And yes, ODP.NET uses the "TNS_ADMIN" variable (it's my point #1). :-) – Maxime Oct 23 '15 at 16:31
  • @ChristianShay Wouldn't it also check `ORACLE_HOME` if `TNS_ADMIN` isn't set? – jpmc26 Aug 02 '16 at 21:36
1

In my version the Oracle Path variable was set wrong ( cos there was another Oracle client installation before). So i suggest to take this possiblity into consideration too.

By following the My computer(this PC)->Properties->Advanced System Settings->Advanced->Enviromental Variables->Path you can edit Oracle Home path.

nooaa
  • 399
  • 1
  • 6
  • 17
0

Add a try catch block around the open() call and resolve the ORA error that shows up in the OracleException.

Christian Shay
  • 2,570
  • 14
  • 24
  • I added the try catch block, and it returned ORA12154 - TNS could not be resolved. After some research, I added an SID to my tnsnames.ora file in my ODP for .NET Oracle home path, and it worked – Mr Man Oct 23 '15 at 12:58
  • @Dan Your terminology is wrong. It's a "connect identifier." An SID is one possible parameter in a connect identifier, and you could use a Service Name instead. – jpmc26 Aug 02 '16 at 21:24
-2

I think there's an over-reaching try somewhere, or the stack makes me think this is an async controller call, but you're not using the async methods ("async all the way").

Explanation:

Something else is going on here. While I'm glad suggestions for a try/catch block helped you resolve the issue, they should not have been required with the simplified code bock - the ora exception should have been thrown in place of the null reference exception.

b_levitt
  • 7,059
  • 2
  • 41
  • 56
  • I see your point, but I still have an answer in there. I put that part first instead. – b_levitt Nov 19 '15 at 22:16
  • The other two answers propagate the generic idea that wrapping the problem in a try/catch to get additional information is a solution here and that is absolutely NOT correct. Could I comment on both of them and say that sure. But in the mean time, other people see these two answers. I'd rather increase my chances of stopping that propagation and post another answer. If the OP would like to post additional detail, I'd gladly explore further. – b_levitt Nov 20 '15 at 16:26
  • Not sure where the downvoters comments went, but it would have been nice if he also removed his downvotes when he removed his comments ;). – b_levitt Feb 09 '16 at 14:45
  • Probably just people frustrated by Oracle like I am. (I didn't downvote.) Despite the fact other answers don't help with finding the solution, this answer doesn't really either. – jpmc26 Feb 02 '17 at 20:08
  • That helps actually. Maybe post your own question and I'll take another shot ;). I'd be happy to help but it's clear this q was somewhat abandoned without the full story. – b_levitt Feb 07 '17 at 23:57
  • Thanks, but I don't really feel comfortable posting a question. I get the error on some machines but not others, with no discernible pattern. Process Monitor doesn't report any failures loading libraries, and it loads from the paths I expect. The connection string works verbatim on the machines where it works. And it only fails under ASP.NET with MVC3; it works in a command line tool. The full .NET implementation works, but I can't use it because 11g and FIPS. I don't know where to start formulating a question about it. It's the dumbest thing I've ever seen, typical Oracle. – jpmc26 Feb 08 '17 at 00:06
  • But along the lines of this question - does your connection.open actually appear to be null? That should never happen. But if it does, I would love for you to post your code. Either way, I would suggest you post what you posted in your comment along with the error message. What can it hurt ;)? – b_levitt Feb 10 '17 at 18:49