How to use Oracle Entity Framework with no config file - oracle

Is it possible to create a code-first Entity Framework model that connects to an existing database using ODP.Net without having any settings in the app.config file?
I have tried many different things.
Currently I am setting DbConfiguration:
sealed class EntityFrameworkConfiguration : DbConfiguration
{
public static readonly DbConfiguration Instance = new EntityFrameworkConfiguration();
EntityFrameworkConfiguration()
{
this.SetDefaultConnectionFactory(new OracleConnectionFactory());
this.SetProviderServices("Oracle.ManagedDataAccess.Client", EFOracleProviderServices.Instance);
}
}
DbConfiguration.SetConfiguration(EntityFrameworkConfiguration.Instance);
I am passing an OracleConnection directly into the EF context.
However, I either have problems with the SQL being generated in SQL Server format (using double-quotes around table aliases), or I get the following error:
An unhandled exception of type 'System.NotSupportedException' occurred in EntityFramework.dll
Additional information: Unable to determine the provider name for provider factory of type 'Oracle.ManagedDataAccess.Client.OracleClientFactory'. Make sure that the ADO.NET provider is installed or registered in the application config.
Has anyone any experience of getting this to work without polluting app.config with crud?

Yes. To complete the switch from machine.config/app.config to code-based configuration, I had to also include a call to SetProviderFactory().
public sealed class EntityFrameworkConfiguration : DbConfiguration
{
public static readonly DbConfiguration Instance = new EntityFrameworkConfiguration();
public EntityFrameworkConfiguration()
{
SetDefaultConnectionFactory(new OracleConnectionFactory());
SetProviderServices("Oracle.ManagedDataAccess.Client", EFOracleProviderServices.Instance);
SetProviderFactory("Oracle.ManagedDataAccess.Client", new OracleClientFactory());
}
}
I also called DbConfiguration.SetConfiguration(EntityFrameworkConfiguration.Instance); in the startup of my application because I had DbContext's in multiple assemblies that all needed to share this configuration.
On a side note, I have also found this to be effective in allowing your application to work around the ConfigurationErrorsException: The 'DbProviderFactories' section can only appear once per config file for cases where you may not have access to repair the user's machine.config.

Uff. Found the problem.
Because I was registering column mapping using lower case the query didn't work. The column and table names must be in upper-case.
How silly.

Related

Mule connector config needs dynamic attributes

I have develop a new Connector. This connector requires to be configured with two parameters, lets say:
default_trip_timeout_milis
default_trip_threshold
Challenge is, I want read ${myValue_a} and ${myValue_a} from an API, using an HTTP call, not from a file or inline values.
Since this is a connector, I need to make this API call somewhere before connectors are initialized.
FlowVars aren't an option, since they are initialized with the Flows, and this is happening before in the Mule app life Cycle.
My idea is to create an Spring Bean implementing Initialisable, so it will be called before Connectors are init, and here, using any java based libs (Spring RestTemplate?) , call API, get values, and store them somewhere (context? objectStore?) , so the connector can access them.
Make sense? Any other ideas?
Thanks!
mmm you could make a class that will create the properties in the startup and in this class obtain the API properties via http request. Example below:
public class PropertyInit implements InitializingBean,FactoryBean {
private Properties props = new Properties();
#Override
public Object getObject() throws Exception {
return props;
}
#Override
public Class getObjectType() {
return Properties.class;
}
}
Now you should be able to load this property class with:
<context:property-placeholder properties-ref="propertyInit"/>
Hope you like this idea. I used this approach in a previous project.
I want to give you first a strong warning on doing this. If you go down this path then you risk breaking your application in very strange ways because if any other components depend on this component you are having dynamic components on startup, you will break them, and you should think if there are other ways to achieve this behaviour instead of using properties.
That said the way to do this would be to use a proxy pattern, which is a proxy for the component you recreate whenever its properties are changed. So you will need to create a class which extends Circuit Breaker, which encapsulates and instance of Circuit Breaker which is recreated whenever its properties change. These properties must not be used outside of the proxy class as other components may read these properties at startup and then not refresh, you must keep this in mind that anything which might directly or indirectly access these properties cannot do so in their initialisation phase or your application will break.
It's worth taking a look at SpringCloudConfig which allows for you to have a properties server and then all your applications can hot-reload those properties at runtime when they change. Not sure if you can take that path in Mule if SpringCloud is supported yet but it's a nice thing to know exists.

Make .dbml file in a class library use connectionstring from config file without subclassing it

I have a class library that is referenced from a web application. The class library defaults to using TestProject.Properties.Settings.Default.NFU_Custom_Website_DataConnectionString1. I would like it to get the connectionstring from ConfigurationManager.ConnectionStrings.
I can't change the .designer.cs file because it will get overwritten. If possible I would like to avoid creating a class which inherits from the .dbml file and setting the connection string in there. My boss recommends creating a web application project and deleting all of the default.aspx etc files from it and using that instead of a class library, is this a viable solution?
Thanks
Joe
You can do that. We had done that inadvertently and I got this problem when I switched to a class library. Rather than switch back I found the answer here: Point connectionstring in dbml to app.config
In summary:
Set the connection property of the DBML to (none) in the designer. This will remove the default constructor from the DB Context class.
Create a partial class for your DB Context with a default constructor:
using System.Configuration;
namespace TestProject
{
public partial class MyDBContext
{
public MyDBContext() : base(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString)
{
OnCreated();
}
}
}

Class library Database Connection String

I have a solution with multiple project using the same domain model. I thus created a class library that holds my domain models. This class library also contains other parameters that are used within my projects. I then add the reference to the class library in each of my projects.
My class library also has some repository classes derived from this example.
I however have an issue with connecting to a database. I want my class library to be able to connect to the database since I defined my database context class in there, where I set my database sets. With a single project, I usually define my connection string in my web.config file. But the class library has no web.config file. How do I set my connection string?
EDIT
Say i have the constructor of my database context, mydbcontext, defined in the class library as
public mydbcontext() : base(ConfigurationManager.ConnectionStrings["DatabaseCon"].ConnectionString)
{
}
If I understanding this right, will it be OK to just set the name of the connection string of each project to "DatabaseCon"?
You don't.
Pass in the connection string as a dependency to whatever classes that require it.
You can encapsulate the access to it - but you should instantiate it in whatever program that uses this library. This program will hold the connection string in its configuration.
You should define the connection string in the web.config file of the application that is using the class library. As an alternative you could hardcode the connection string into the constructor of your DbConext inside the class library - pretty bad approach because you won't be able to modify it from the outside - for example you will have hard time managing different connection strings for the different environments - staging, production, ...

Using StructureMap in ASP.NET MVC Areas

I'm using StructureMap for IoC and it works fine for regular controllers but I can't make it work with Areas. I have the following AccountController in Administration Area:
public class AccountController : Controller
{
private readonly IFormsAuthenticationService formsService;
private readonly IMembershipService membershipService;
public AccountController(IFormsAuthenticationService formsService, IMembershipService membershipService)
{
this.formsService = formsService;
this.membershipService = membershipService;
}
...
}
And here's the error:
System.InvalidOperationException: An error occurred when trying to create a controller of type 'Foo.Areas.Administration.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor. ---> System.MissingMethodException: No parameterless constructor defined for this object.
Any help would be greatly appreciated!
EDIT
StructureMap couldn't resolve MembershipProvider.
Here's the solution:
For<MembershipProvider>().Use(Membership.Providers["AspNetSqlMembershipProvider"]);
I doubt that this is a problem with areas because I am using them happily. It is more likely a pure IOC issue. You get this error when one of the injected services cannot be resolved by your container, which has the consequence that the container cannot match a signature for the constructor and tries to fall back to the empty constructor, which doesn't exist, rightly.
So, my first instinct would be to make sure that the two injected services are available. It is possible that one of them did not get created properly; a common cause is that the Membership provider cannot connect to its database, or similar.
For diagnosing, in your global.asax, after the container has been created, see if you can manually resolve those two services. I don't know SM, but something like:
var s = container.Resolve<IMembershipService>();
Satisfy yourself that both those services can be resolved.

Custom Membership provider that would read connection string from custom file

In my web application project I am using MYSQLMemberShipProvider. Now I want that instead of reading the connection string from web.config file, it will read the connection string from external file every time.
So that I am implementing the custom membership provider class, this class inherits the MembershipProvider class.
But the problem is that if I inherits the MembershipProvider class then I have to implement all of its method in my custom membership provider class, But I want to use all other inbuilt methods of Memebership. What can I do.
I only want to add the code like below:
public class CustomSqlMembershipProvider :MembershipProvider
{
public override void Initialize(string name, NameValueCollection configs)
{
base.Initialize(name, configs);
Connectionstring objProducts = // reading the connection string.
}
}
But on compilation it is giving me the error does not implement inherit abstract member.
Please Suggest me any idea.
Thanks in advance
Aayushi
What are your motivations for reading in the connection string from another file, is it purely to get a different connection string for debug/release environments? If that is the case you could use web.config transformations if you have VS2010. It is a very clean solution that may be of use to you.

Resources