How to connect to Oracle 11g in MVC3 - c#

I am having a problem to connect to oracle 11g and I have worked upon it for almost a day now. I am using C# and coding in an Mvc3 way.
I have the following connection string in web.config file
<add name = "VIPSoracleContext"
connectionString = "Data Source=localhost:1521/XE; User Id=SYS; Password=PSWRD;"
providerName="System.Data.OracleClient"/>
I even tried the following connection string again
<add name = "VIPSoracleContext"
connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=’wkkdmtk’)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME’vipstest’)));User Id=’myID’;Password=’PSWRD’;"
providerName="System.Data.OracleClient"/>
I still have the following error when creating a controller with read/write templates
error:
Unable to retrieve metadata for '...Models.person'.
A null was returned after calling the 'get_ProviderFactory' method on a store provider instance of type 'System.Data.OracleClient.OracleConnection'. The store provider might not be functioning correctly.
How can I successfuly connect to oracle 11g with code first? Can anyone please help.
Thanx in advnce!

I got it atlast guys!
Followed this tutorial:
http://www.youtube.com/watch?v=68tlel4iJdM
But be aware of the default constractor of the context class because if you don't controll it, you will get an error.
Follow this link to check what to take cure of with the default constractor:
Add Controller in MVC4 not working
especially the answer by Arnaldo237.
You will need ODP.net so that provider name Oracle.DataAccess.Client can work.
Enjoy your code at Home.... happy....

Related

How to change connexion string in a deployed Azure App

I have developed a website application under visual studio using the MVC Pattern and Entity Framework 6.
This web app was linked to a local database.
I've published the application on my azure acc. I also exported the database on Azure following this tutorial.
However, I can't find a way to link the online app to the migrated database.
No data is displayed on the app and when I try to check for the connexion string I get an error , the connexion string hasn't been updated and therefore the app is still trying to target my local database.
I would like to know if anyone might know how to solve this.
EDIT : The problem may be somewhere else, I apparently have two connexions , one for my migrated DB and one for my local db. Perhaps I need to remove the connexion string targetting my local DB but I don't know how to do that
Also, since the Migrated database is a copy from the local one I was using before, do I need to change anything in my Model,views or controller ?
EDIT2 : Thanks to the comment below I was able to override the false Connexion String. However my datas are still not displayed on my application and I haven't found yet what could have happend.
I suspect that my model is still the same model as the one used by the local database as it has the same name. Does anybody know how to change the model to the current model of the online database ?
Thanks.
Because you created your app with entity framework there should be a connection string defined in the web.config file pointing to the local database.
<connectionStrings>
<add name="MyContext" connectionString="..."
providerName="System.Data.SqlClient" />
</connectionStrings>
If you have published your Website as WebApp (App Service) then you can change the connection string for the database under the Application Settings pane on the WebApp Page.
You can override your connection string by creating a connection string settings entry with the name of the connection string in the web.config file.
(For the snippet above - MyContext)

Using() with insert command in c# doesn't work [duplicate]

I have an ASP.NET application which runs fine on my local development machine.
When I run this application online, it shows the following error:
Format of the initialization string does not conform to specification starting at index 0
Why is this appearing, and how can I fix it?
Check your connection string. If you need help with it check Connection Strings, which has a list of commonly used ones.
Commonly used Connection Strings:
SQL Server 2012
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;
SQL Server 2005
Standard Security
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Trusted Connection
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Connection to a SQL Server instance
The server/instance name syntax used in the server option is the same for all SQL Server connection strings.
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;Password=myPassword;
MySQL
Standard
Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Specifying TCP port
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
Oracle
Using TNS
Data Source=TORCL;User Id=myUsername;Password=myPassword;
Using integrated security
Data Source=TORCL;Integrated Security=SSPI;
Using ODP.NET without tnsnames.ora
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
This might help someone..
My password contained a semicolon so was facing this issue.So added the password in quotes. It was really a silly mistake.
I changed the following :
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password=pass;word" providerName="System.Data.SqlClient" />
to
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='pass;word'" providerName="System.Data.SqlClient" />
Set the project containing your DbContext class as the startup project.
I was getting this error while calling enable-migrations.
Even if in the Package Manager Console I selected the right Default project, it was still looking at the web.config file of that startup project, where the connection string wasn't present.
Check your connection string like I forget to add services.AddDbContext<dbsContext>(options => options.UseSqlServer("Default"));
It causes the error and here when I add Configuration.GetConnectionString, then it solves the issue
like now the connection is:
services.AddDbContext<dbsContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
works fine (This problem is solved for .net core)
Make sure that your connection string is in this format:
server=FOOSERVER;database=BLAH_DB;pooling=false;Connect Timeout=60;Integrated Security=SSPI;
If your string is missing the server tag then the method would return back with this error.
I had the same problem. Locally the site ran fine, but on azure it would fail with the message above.
turns out the problem was setting the connectionstring in the ctor, like this:
public DatabaseContext()
{
Database.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;
}
Does NOT work, this will:
public DatabaseContext() : base("db")
{
}
Beats me..
Referencing the full sp path resolved this issue for me:
var command = new SqlCommand("DatabaseName.dbo.StoredProcedureName", conn)
I removed &quot at the end of the connection string and it worked
Instead of
App=EntityFramework"
Used
App=EntityFramework;
Set DefaultConnection as below
<add name="DefaultConnection" connectionString="data source=(local);initial catalog=NamSdb;persist security info=True;user id=sa;password=sa;MultipleActiveResultSets=True;App=EntityFramework;" providerName="System.Data.SqlClient" />
Note : In connectionString Do not include :
|x| Metadata info : "metadata=res://*/"
|x| Encoded Quotes : """
I solved this by changing the connection string on the publish settings of my ASP.NET Web Api.
Check my answer on this post: How to fix error ::Format of the initialization string does not conform to specification starting at index 0::
I had the same error. In my case, this was because I was missing an closing quote for the password in the connection string.
Changed from this
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password" providerName="System.Data.SqlClient" />
To
<add name="db" connectionString="server=local;database=dbanme;user id=dbuser;password='password'" providerName="System.Data.SqlClient" />
In my case, I got a similar error:
An unhandled exception was thrown by the application. System.ArgumentException: Format of the initialization string does not conform to specification starting at index 91.
I change my connection string from:
Server=.;Database=dbname;User Id=myuserid;Password=mypassword"
to:
Server=.;Database=dbname;User Id=myuserid;Password='mypassword'"
and it works, I added single quotes to the password.
In my case the problem was in the encoding of the connection string.
In local it worked without problems, but when installing it in a production environment it showed this error.
My application allows to set the connection string using a form and when the connection string was copied from local to production, invisible characters were introduced and although the connection string was visually identical at the byte level it was not.
You can check if this is your problem by following these steps:
Copy your connection string to Notepad++.
Change the codification to ANSI. In Menu Encoding>Encode to ANSI.
Check if additional characters are included.
If these characters have been included, delete them and paste the connection string again.
Got this problem with SQLite in aspnetcore. I wrote
"DefaultSQLiteConnection": "MyBlog.db"
instead of
"DefaultSQLiteConnection": "Data Source = MyBlog.db"
My generated password contained few characters that were valid in AWS RDS, but for some reason my .NET app could not handle it. The solutions that worked for me, was to generate new password without characters like ` (backtick).
In my case, it was...
index: 58
but what ended up happening was the password generated had a single quote in it. SQL Server accepted that, but my connection string had trouble parsing it. Hope this saves someone at least a few minutes, because it cost me an hour to two before I relized what was going on. cheers
Hope this helps someone in the future. My connection string had blank values wrapped in double quotes, e.g. User ID="". So to resolve it I had to escape the double quotes.
Dim ConString = "Data Source=MYSERVER;User ID="";Initial Catalog=Northwinds..."
ConString = ConString.Replace("""", """""")
This also happens when you copy a web page from one solution to another, then you run your solution and find out that it has a different connection string name in the webconfig. Then you carelessly change the name of the connection string in the properties panel in the design view of the page.
Better to just change it in the code portion instead of the design.
My problem was I added database logging code to my constructor for a DB object, and this seemed to cause havoc on my azure deployment profile.
FYI - I simplified this example, in the real code this was turned off in production (but still in the code)
public class MyDB : DbContext
{
public MyDB()
{
this.Database.Log = x => { Debug.WriteLine(x); };
}
}
I had typo in my connection strings "Database==PESitecore1_master"
<add name="master" connectionString="user id=sa;password=xxxxx;Data Source=APR9038KBD\SQL2014;Database==PESitecore1_master"/>
I had the same problem and finally I managed to resolve it in the following way:
The problem was in the connection string definition in my web.config.
<add name="DefaultConnection" connectionString="DefaultConnection_ConnectionString" providerName="System.Data.SqlClient"/>
The above worked perfect locally because I used a local Database when I managed users and roles. When I transfered my application to IIS the local DB was not longer accessible, in addition I would like to use my DB in SQL Server. So I change the above connection string the following SQL Server DB equivalent:
<add name="DefaultConnection" connectionString="data source=MY_SQL_SERVER; Initial Catalog=MY_DATABASE_NAME; Persist Security Info=true; User Id=sa;Password=Mybl00dyPa$$" providerName="System.Data.SqlClient"/>
NOTE: The above, also, suppose that you are going to use the same SQL Server from your local box (in case that you incorporate it into your local web.config - that is what exactly I did in my case).
I had the same issue, came to find out that the deployment to IIS did not set the connection strings correctly. they were '$(ReplacableToken_devConnection-Web.config Connection String_0)' when viewing the connection strings of the site in IIS, instead of the actual connection string. I updated them there, and all worked as expected
I copied and pasted my connection string configuration into my test project and started running into this error. The connection string worked fine in my WebAPI project. Here is my fix.
var connection = ConfigurationManager.ConnectionStrings["MyConnectionString"];
var unitOfWork = new UnitOfWork(new SqlConnection(connection.ConnectionString));
My problem wasn't that the connection string I was providing was wrong, or that the connection string in the app.config I thought I was using was wrong, but that I was using the wrong app.config.
For the one other unfortunate soul that is managing a legacy webforms application that uses an inline sqldatasource, along with connection strings stored in web.config, then you may get this error if you access your connection string like <%APSDataConnectionString%> instead of
<%$ ConnectionStrings:MyConnectionString %>. This happened to us when upgrading .NET from 3.5 to 4.x.
<asp:DropDownList ID="ddl" runat="server" DataSourceID="SqlDataSource1"
DataTextField="value" DataValueField="id"></asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="select id, value from a_table">
</asp:SqlDataSource>
In my case the problem was that on the server, a different appsettings.json file was used by the application.
I had this error too and was able to solve it as follows:
I previously wrote the connectionstring to the appsettings.json into a section that I created (ConnectionsStrings (notice the extra "s") and tried to connect to my database which caused the error. It was an ASP.NET CORE application and so I wanted to connect to it with the .GetConnectionString Method (details on that here). It seems that this method implicitly searches for a connectionstring in the "ConnectionStrings"-section, which didn't exist. When I changed/corrected it to "ConnectionStrings" it worked as expected.
I had the same problem spent an entire day. The error indicates Connection string issue for sure as index 0 is connection string. My issue was in the Startup class. I used:
var connection = Configuration["ConnectionStrings:DefaultConnection"];
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer("connection"));`
which is wrong instead use this:
services.AddControllersWithViews();
services.AddApplicationInsightsTelemetry();
services.AddDbContextPool<Models.PicTickContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
and my problem was solved.
I had this error and it turned out that the cause was that I had surrounded a (new) tableadapter with a Using/End Using. Just changing the tableadapter to stay live for longer (duration of class in my instance) fixed this for me. Maybe this will help someone.
Sometimes the Sql Server service has not been started. This may generate the error. Go to Services and start Sql Server. This should make it work.
As I Know, whenever you have more than 1 connection string in your solution(your current project, startup project,...), you may confront with this error
this link may help you
click

Using a SQL Server Database File from a Class Library in C#

So I have a basic 3-tier application:
Data Access
Business Logic
Presentation
My Data Access layer is a class library, and I'm using Entity Framework and a SQL Server Database File
Say my solution is structured as such
MySolution
\MySolution.Data
\MySolution.Data\App_Data\MySolutionDB.mdf
\MySolution.BusinessLogic
\Presentation
The problem I am trying to solve is that I need to get a folder relative path to the database for the connection string because this project will not always be deployed in into the same folder structure, therefore it is imperative that the connection string is created dynamically based on the relative path.
Could someone offer some assistance on this. please?
P.S. I tried this, but it's not working:
string.Format("Data Source=(LocalDB)\v11.0;AttachDbFilename={0}\\MySolutionDB.mdf;Integrated Security=True", AppDomain.CurrentDomain.GetData("DataDirectory"))
EDIT: Getting this error message, which may be unrelated to the issue...
Connection to the database failed. The connection string is configured
with an invalid LocalDB server name. This may have been set in
'global.asax' by a pre-release version of MVC4. The default connection
factory is now set in web.config so the line in 'global.asax' starting
with 'Database.DefaultConnectionFactory = 'should be removed. See
http://go.microsoft.com/fwlink/?LinkId=243166 for details
Thanks to wdosanjos for pointing out my stupid mistake.
string.Format("Data Source=(LocalDB)\v11.0;AttachDbFilename={0}\\MySolutionDB.mdf;Integrated Security=True", AppDomain.CurrentDomain.GetData("DataDirectory"))
I did not escape \v11.0; it should have been \\v11.0;

Using Npgsql provider with OLE database connection

So I have the following connection string which is causing me issues. I am attempting to write an application which is capable of being database agnostic (difficult but not impossible) and I have come to testing it on PostgreSQL however I cannot seem to get an OLE connection to work with it. From what I have seen it is entirely possible.
I got everything working using a specific class for PostgreSQL but this used the Npgsql types rather than generic OLE types.
E.g.
private NpgsqlCommand m_postgreSQLDatabaseCommand;
Instead of
private OleDbCommand m_oleDatabaseCommand;
This is not acceptable in my circumstances.
I tried simply changing the connection string to use the Npgsql provider but I am not sure if I am using it correctly. I get the error below:
Connection String:
<add name="ApplicationPostgresDefault"
connectionString="Server=127.0.0.1;Port=5432;
Database=myDatabase;
User Id=myUser;
Password=myPass;
Provider=Npgsql"
/>
Error:
The 'Npgsql' provider is not registered on the local machine.
What can be done to solve this?
If I get the provider in there correctly will I be able to communicate with PostgreSQL as I was with Npgsql objects?
The local machine doesn't have the provider installed.
I would suggest using a native client rather than OleDb anyway:
http://npgsql.projects.postgresql.org/
http://connectionstrings.com/Providers/npgsql
that's your choose
Are you missing a ; after Npgsql ?

WCF & Entity Framework & SQL Server - "The underlying provider failed on Open"

I am successfully running tests through the the WCF Test Client, until I try to pull in data with Entity Framework.
To make sure I'm not doing anything stupid, I downloaded the sample code from this tutorial, which is doing something similar: http://www.codeproject.com/KB/WCF/WCFandEF.aspx
...and when I run it, I get the same error in a similar place:
var productEntity = (from p in context.ProductEntities
where p.ProductID == id
select p).FirstOrDefault();
The error is
The underlying provider failed on Open.
I can open the database fine from a "normal application" with the same connection string, it seems to be specific accessing the DB from the WCF test client.
Research here and on Google for "The underlying provider failed on Open." usual indicates that it's a connection string problem, but I'm pretty sure it's not in this case.
So now I expect it's some sort of permissions problem.
I am using SQL Server and Windows 7, with visual studio 2010.
I have been banging my head since yesterday, so any help or protective head gear appreciated.
Edited to include connection string
<add name="NorthwindEntities"
connectionString="metadata=res://*/Northwind.csdl|res://*/Northwind.ssdl|res://*/Northwind.msl;provider=System.Data.SqlClient;provider
connection string="Data Source=localhost;Initial Catalog=Northwind;User ID=sa;MultipleActiveResultSets=True""
providerName="System.Data.EntityClient" />
This error means 100% a problem in your connection string.
A good way to create a surely working connection string is to create a new(dummy) project, add an Entity Framework Data Model to it, select "Generate Model from Database", select your required connection, and click "Test Conntection" to be sure it works.
Make sure ""Save entity conection settings in App.Config as:..." is ticked.
Than, in you web/app.Config, you have a Connection String you can copy+paste to your own project
Have you tried inserting the database password into the connection string?
It worked for me.
Reference:
http://stack247.wordpress.com/2011/03/02/entity-framework-exception-the-underlying-provider-failed-on-open/
Well I had the same error for days... actualy for two days and Yes I found the solution Alhamdulillah..
As for me... I had Windows Authentication set on my Entity Service Connection.. So What I did was I went to IIS 7 Application Pool Advanced Settings for the web service... Changed the Identity from 'ApplicationPoolIdentity' to 'Network Service' and I setup my current user name and password as well.
I might face some other issues later on, still I would say a Good Start :-)!
I was remove "integrated security=True;" solved this way.

Categories

Resources