Refresh data source and connectionstring - c#

Currently I using EF 5 and Oracle ManagedDataAccess for my application. I create a small tool to enable user to configure database connection while the application is running.They communicate using WCF SOAP. So mainly the changes will be on the application.
However, I am not able to refresh data source once EF is able to connect. Connection String is able to refresh, but not data source.
public Entities(): base("name=MyEntities")
{
}
public UnitOfWork()
{
_context = new Entities();
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connection = config.ConnectionStrings.ConnectionStrings["Entities"].ConnectionString;
var connString = new EntityConnectionStringBuilder(connection);
context.Database.Connection.ConnectionString = connString.ProviderConnectionString;
}
My App.config will be look like
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</configSections>
<connectionStrings>
<add name="Entities" connectionString="metadata=res://*/Mapping.Models.csdl|res://*/Mapping.Models.ssdl|res://*/Mapping.Models.msl;provider=Oracle.ManagedDataAccess.Client;provider connection string="data source=datasource1;password=123;persist security info=True;user id=user123"" providerName="System.Data.EntityClient" />
</connectionStrings>
<oracle.manageddataaccess.client>
<version number="*">
<dataSources>
<dataSource alias="datasource1" descriptor="(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=W2K8R2o11G020)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PCMS))) " />
</dataSources>
</version>
</oracle.manageddataaccess.client>
</configuration>
Once _context is established and able to connect to database, the datasource cannot be changed via my small tool. I still manage to change username and password with my small tool, but not data source (hostname, port, service name).
I tried to use OracleConnection.ClearAllPools(), but it is not working as well. Try to force new connection every time, not working too.
Is there any other way to make it happen?

Related

MicrosoftConfigurationBuilders Connection String Provider Name Error (C#, Oracle)

Web.config is like that.
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false"/>
</configSections>
<connectionStrings configBuilders="Environment">
<add name="ConnectionString" connectionString="ConnectionString" providerName="System.Data.OracleClient" />
<add name="OracleDbContex" providerName="Oracle.ManagedDataAccess.Client" connectionString="OracleDbContex" />
</connectionStrings>
<configBuilders>
<builders>
<add name="Environment" mode="Greedy" type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Environment" />
</builders>
</configBuilders>
I have two connection string one of them is normal Ado.net connection. Another one is the oracle entity. But problem is that when program start and connection strings change from environment variables, ado.net connections work normally but dbcontex give this error.
System.InvalidOperationException: 'The connection string 'OracleDbContex' in the application's configuration file does not contain the required providerName attribute."'
If I don't use ConfigurationBuilders, two connection working normally. I need to get connection strings from environment variables. What should I do?
I found solution. Its about builder mode. I changed greedy to strict and it fixed.
When using Strict mode the configuration values are looked up first and every entry found is updated with override value (if present). Meaning the original connectionString XML node is kept with all its attributes, including the attribute providerName.

EntityException was unhandled the underlying provider failed to open

I am using VisualStudio2012 for the development. I have created a class library EMPDAL where I am using Employees table of NorthWnd database to connect with Entity Framework and I tested the connection while configuring the database. I have written below code to get employees details.
public class EmplooyeeData
{
public static List<Employee> GetEmployees( int EmployeeId)
{
using (DbEntities dbContext = new DbEntities())
{
return dbContext.Employees.Where(x => x.EmployeeID == EmployeeId).ToList();
}
}
}
I created a console application to use this EMPDAL so I had given the reference to my EMPDAL and using below code to retrieve employee details
static void Main(string[] args)
{
List<EmpDAL.Employee> emp = new List<EmpDAL.Employee>();
emp = EmpDAL.EmplooyeeData.GetEmployees(1);
}
But when client code calls GetEmployees(1) and debugger goes in to the EMPDAL.EmpDataGetEmployess method then in return statement it throws the exception ![Exception is shown below]
The underlying provider failed on Open.
AppConfig I have used same in my class library and client application.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DbEntities" connectionString="metadata=res://*/EmployeeModel.csdl|res://*/EmployeeModel.ssdl|res://*/EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=localhost;initial catalog=NorthWnd;user id=sa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
You've made mention of at least two tiers to your application (class library and a console application). N-tier applications require you to have the connection string for your EF database to be declared in the web.config / app.config of all tiers of your application that Entity Framework is referenced in.
Ensure you have the connection string for your database listed in your console applications app.config as well as the class library's app.config.
As per the above comments from #Yuliam, it is worth ensuring you have the following in your connection strings:
Integrated security=True;
What this does is When it is set to True, .Net tries to open the connection with the current user event if you specify a user and password. Set the Integrated Security to False if you want to open the connection string as a specific user.

Enterprise library exception: Activation error occured while trying to get instance of type ICacheManager, key?

Using .net 3.5 and Enterprise library 5.0.
From my research, I found a similar issue here:
Activation error occured while trying to get instance of type ICacheManager, key "Cache Manager" *** this solution did not fix my issue.
I can't seem to figure it out, my config should be set up correctly, but keep getting the exception? Anyone have similar issues?
I made the suggestion to add cacheManager and reference when I call the cache manager:
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
.....
....
ICacheManager cm = CacheFactory.GetCacheManager("TrackingCacheManager");
The App.config:
<configuration>
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
<section name="cachingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Caching.Configuration.CacheManagerSettings, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
</configSections>
<cachingConfiguration defaultCacheManager="TrackingCacheManager">
<cacheManagers>
<add name="TrackingCacheManager" type="Microsoft.Practices.EnterpriseLibrary.Caching.CacheManager, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
expirationPollFrequencyInSeconds="120" maximumElementsInCacheBeforeScavenging="1000"
numberToRemoveWhenScavenging="10" backingStoreName="NullBackingStore" />
</cacheManagers>
<backingStores>
<add type="Microsoft.Practices.EnterpriseLibrary.Caching.BackingStoreImplementations.NullBackingStore, Microsoft.Practices.EnterpriseLibrary.Caching, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="NullBackingStore" />
</backingStores>
</cachingConfiguration>
<dataConfiguration defaultDatabase="ConnectionString" />
<connectionStrings>
<add name="ConnectionString" connectionString="server=AFS7BCBRNGQ5O0\DEVELOPMENT;database=EITC_RTS;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
My references:
My guess is that you've setup this configuration in an App.config for your Domain project. But your main project has it's own config file which this configuration must be copied into.
So for example, if your main project was a webapp, then it would have a web.config. The caching configuration you have added to the App.config of the Domain project is not used at runtime. The configuration being used is from main project's config, in this example the web.config.
Copy your Caching configuration from the Domain App.Config to the main config file and it will work.
I have done silly mistake, but after read above, understand the issue. This is my vb.net code which give me the above error.
Imports System.Collections
'Imports System.Configuration
Public Class DatabaseLogic
Public ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("db").ToString()
Public Function ServerDataMagic(StoredProcedure As String, PDMdata As Hashtable) As DataSet
Dim db As Database = DatabaseFactory.CreateDatabase(ConnectionString ) 'Here I am getting error.
Using cmd As DbCommand = db.GetStoredProcCommand(StoredProcedure)
Try
db.DiscoverParameters(cmd)
Catch discover_ex As Exception
End Try
and in web.config entry is
<add name="db" connectionString="Database=Dbname;Server=SERVER;uid=sa;pwd=sa#1234" providerName="System.Data.SqlClient" />
After read just get the issue is CreateDatabase method wants a config entry key as a string and I was given the exact connection string via config entry access. This is my updated code.
Dim db As Database = DatabaseFactory.CreateDatabase("db") 'Here I changed the config entry key
I was post to somebody help.

EntityFramework ignore login name in connectionString

Hi iam trying to configure my first application with EF but find no way to connect to DB
this is my context
public partial class FunzionamentoContext : DbContext
{
public FunzionamentoContext()
: base("FunzionamentoContext")
{}
static FunzionamentoContext()
{
Database.SetInitializer<FunzionamentoContext>(null);
}
public DbSet<Controllo> Controllo { get; set; }
}
this is connection string (present in app.config file of DAL project since i still don't have UI project):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="FunzionamentoContext"
providerName="System.Data.SqlClient"
connectionString="Data Source=xyzxyz; Initial Catalog=dbName;
Integrated Security=false;User ID=test;Password=test" />
</connectionStrings>
<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>
</configuration>
this is a simply method i make to test connection (only for search if connection is done, next i will rewrite it in a more beautyful way :D)
[Test]
public void TestTrue()
{
FunzionamentoContext fctx = new FunzionamentoContext();
Controllo c = new Controllo();
.id = 1
fctx.Controllo.Add((Controllo)c);
fctx.SaveChanges();
}
When i try to connect i see this error:
FunzIA.UnitTest.DAL.TestFixture1.TestTrue:
System.Data.Entity.Core.EntityException : The underlying provider failed on Open.
----> System.Data.SqlClient.SqlException : Cannot open database "FunzionamentoContext" requested by the login. The login failed.
Login failed for user 'DOMAIN\U123456'.
where DOMAIN\U123456 is my windows account
Why EF use my windows account and not the one wrote in connection string?
I am assuming that you have your DAL in a separate project from the project you're actually running.
Your application will use the config file from the project you're trying to run, and not the one directly related to the DAL project.
By this, I mean, if you're only using the test project (assuming it's in a different project from the DAL) then you need the connection string in the app.config of your test project.

All artifacts loaded into the item collection must have the same version. Multiple versions were encountered

I'm getting this error when I try to access a view in my .edmx:
All artifacts loaded into an ItemCollection must have the same version. Multiple versions were encountered.
Here's the code that's genereating the error:
private IQueryable<daDialogNotes.viewDialogNotesAll> GetAuthorizedList()
{
List<int> authorizedClients = al.GetClientIds();
daDialogNotes.NTS2001Entities context = new daDialogNotes.NTS2001Entities();
IQueryable<daDialogNotes.viewDialogNotesAll> m;
m = context.viewDialogNotesAlls.Where(x => (authorizedClients.Contains(x.Client_Id))).AsQueryable();
// error in line above
return m;
}
Here's an image of my view:
App.config for the provider:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="NTS2001Entities" connectionString="metadata=res://*/DialogNotes.csdl|res://*/DialogNotes.ssdl|res://*/DialogNotes.msl;provider=System.Data.SqlClient;provider connection string="data source=NTS-UAT;initial catalog=NTS2001;persist security info=True;user id=*******;password=*********;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
</configuration>
I'm running .net 4.5 on everything. The edmx is in another project file and I'm referencing the dll in my application. Googling around I see that people are getting this error when they're upgrading from .net 3.5 to 4.0, but this has always been running on 4.5.
Any ideas?

Categories

Resources