C# application deployment issue with .mdf database - c#

I am working on a C# database application for learning and I'm trying to deploy it on client machine and getting connection problem.
//NOTE: path and database variables have correct info because it works on my dev machine
"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" + path + "\\" + databaseName + ";Integrated Security=True"
I am using Install Shield for creating setup and tried Advance Installer also.
On the other test machine I have installed:
.Net Framework 4.5.2
SQLLocalDB.msi (x64 bit)
Lastly, I installed my deployed setup file and I was getting an Exception:
System.Data.SqlClient.SqlException (0x80131904). A network related or instance-specific error occured while establishing a connection to SQL server.
The server was not found or not accessible.
Localdatabase Runtime error occured.
I also tried these in Connection String: (found in similar question on stackoverflow)
localhost
localhost\\SQLExpress
.\\SQLExpress
But none of this work for me.
NOTE:
My LocalDB connection string is working on dev machine.
Using Visual Studio 2015 Enterprise
PS: What I am trying to learn is a way to create an installer which installs some per-requeisites like .Net Framework, LocalDB etc and can run database based application on client machines without installing SQL Server separately. I am not sure if the .mdf way is the good fit for this or not.

I would suggest you to use SQLite Database because the process and function are almost similar. And the deployment is super easy; it just requires few DLLs to make it work.
Guideline:
First you will need System.Data.SQLite library and then needs to add System.Data.SQLite.dll as a reference in your project. Keep in mind that SQLite.Interop.dll also needs to be in your executables directory but doesn’t need to be added as a reference in your project.
Moreover, if your application is targeting Any CPU it is likely that you will get an exception. So make sure to navigate to Project properties -> Build and set the Platform target to the bit version of the System.Data.SQLite.dll binary you have downloaded.
As you are beginner so here is the step by step guideline along with sample code.
Steps:
Navigate to: Tools > NuGet Package Manager > Manage NuGet Packages for Solution
Search For: SQLite
Select System.Data.SQLite (would be first result)
Click on Install
Import library
using System.Data.SQLite;
The connection is ready and here is the Sample Code:
System.Data.SQLite.SQLiteConnection.CreateFile("sqlite.db3");
using(System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=sqlite.db3")){
using(System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn)){
conn.Open();
cmd.CommandText = #"CREATE TABLE IF NOT EXISTS
[persons](
[id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[name] VARCHAR(50) NULL
)";
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO [persons] (name) values('Atlas')";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT * FROM [persons]";
using(System.Data.SQLite.SQLiteDataReader reader = cmd.ExecuteReader()){
while(reader.Read()){
MessageBox.Show(reader["name"].ToString());
}
conn.Close();
}
}
}
Tips:
always use try/catch block for database operations
If you don't prefer to use NuGet Package Manager then you can download library from here
Hope this helps! :)

Does one of these help?
Attach a database file on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=C:\MyFolder\MyDataFile.mdf;Database=dbname;
Trusted_Connection=Yes;
Attach a database file, located in the data directory, on connect to a local SQL Server Express instance
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname;
Trusted_Connection=Yes;

Related

Oracle 9i: ORA-01017: invalid username/password; logon denied

I get the following exception when I try to connect to my Oracle 9i database from my Visual Studio 2017 application:
ORA-01017: invalid username/password; logon denied
Code:
var connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=myServerName)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SID=mySID)));User Id = myUsername; Password = myPassword";
var con = new OracleConnection(connectionString);
con.Open();
Same problem when :
using same code with System.Data.OracleClient assembly
trying to add a new Data Connection via Server Explorer in Visual Studio.
I tried setting System\CurrentControlSet\Control\Lsa\FIPSAlgorithmPolicy\Enabled to 0 with no luck.
When I use SQL Developer I am able to connect to the same database with same credentials and perform any query.
Any idea ?
Database: Oracle 9i
Visual Studio : 2017
I found the answer.
remove any associated plugin in Visual Studio
execute uninstall.bat from your ODAC downloaded folder
remove any associated tool in Windows Add or Remove Program
Remove remaining Oracle folders (in C:\, C:\ProgramFiles, ...)
Make sure there is no remaining Oracle reference in GAC, otherwise delete them.
The latest compatible version of Oracle provider is Oracle version + 2 (9+2=11), meaning the maximum version I had to install was 11.2.0.4. After installing this version and compile my code in x64 (Any CPU or x32 won't load the DLL) evrything was working.

Building a C# WinForms application with a local Db

I am trying to build my first .exe from a c# winforms project. I am using the Flexera Installing Shield. So far I can build and install it and it runs successfully on the same machine where I am developing. In this project I am using a local db. I can also install it on another machine, but as soon as I`m trying to access the Db via a button it complains. I think it has something to do with the connection string. At least it complains at the line where I am trying to access the Db with:
Error 26 - Error Locating Server/Instance Specified
Here is my obviously wrong connection string:
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=""C:\Users\idiot\Documents\Visual Studio 2013\Projects\Vis\Vis\LocalDbVisTest.mdf"";Integrated Security=True";
Thank you for any help or hint in advance!
Instead of using an absolute path for your connection string, use
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\LocalDbVisTest.mdf;Integrated Security=True
The reason your program cannot find the database is because it is looking in
C:\Users\idiot\Documents\Visual Studio 2013\Projects\Vis\Vis\LocalDbVisTest.mdf
Which, presumably, doesn't exist on your client's machine.
You can manually set your DataDirectory by using AppDomain.CurrentDomain.SetData("DataDirectory", path). You can get the path of your executable by using AppDomain.CurrentDomain.BaseDirectory

Creating a Local DB for a WPF application

I have an application and I want to create a DB in the same folder as the application. I looked into SQLite for .NET 4.0 everything looked fine untill I got an exception "Could not load file or assembly 'System.Data.SQLite, Version=1.0.88.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139' or one of its dependencies. An attempt was made to load a program with an incorrect format." The SQLite works with a console .NET application. I dont want to use SQL Server at all. Is there an alternative other than XML files?
SQLite is a great choice for the scenario you describe. Giving up on SQLite because you could not include it correctly seems like the wrong conclusion. Reference it through NuGet and you are fine. The library needs SQLite.Interop.dll which you might not have included correctly. You might also have included something like the x64 version when you are running under x86 (see this for details). Use it through NuGet and you should be OK.
Here is the quick setup I got working in under 5 minutes:
Created console application (VS Express 2012 for Desktop, .NET v4, Any CPU, Debug)
Installed via NuGet
Used the following code
Works like a charm!
Code sample:
string dataSource = "SQLiteDemo.db";
SQLiteConnection connection = new SQLiteConnection();
connection.ConnectionString = "Data Source=" + dataSource;
connection.Open();
SQLiteCommand command = new SQLiteCommand(connection);
command.CommandText = "CREATE TABLE IF NOT EXISTS beispiel ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name VARCHAR(100) NOT NULL);";
command.ExecuteNonQuery();
command.CommandText = "INSERT INTO beispiel (id, name) VALUES(NULL, 'Test-Datensatz!')";
command.ExecuteNonQuery();
command.Dispose();
connection.Dispose();
I found one more solution to this issue. The problem was with the platform (x86/x64). I got the source code of Sqllite v1.0.88 and opened the VS 2010 solution file. I noticed that the target was mixed platforms by default. I changed it to any CPU and built the System.Data.SQLite.2010 project. I referenced this dll in my project and I did not have an issue with x86/x64 platform. One dll worked for both.

the microsoft.ace.oledb.12.0 provider is not registered on the local machine

I have the following program in which i want to insert the values in MS-Access.I am getting the error "the microsoft.ace.oledb.12.0 provider is not registered on the local machine"
I have already installed the database engine as per suggestion of some developers, still i am getting the error.
I am writing the code on Vista machine with VS-2008 and MS-Access-2007.
Please help me to resolve the error
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbConnection con;
OleDbCommand cmd;
private void btnSubmit_Click(object sender, EventArgs e)
{
try
{
con = new OleDbConnection("Provider=Microsft.ACE.Oledb.12.0;Data Source=C:\\Users\\Satish\\Documents\\Testing.accdb");
con.Open();
string cmdText = "Insert Into UserDetail (UsrName,Age,Address,MobileNo) Values ('" + txtName.Text.ToString().Trim() + "','" + txtAge.Text.ToString().Trim() + "','" + txtAddress.Text.ToString().Trim() + "','" + txtMobile.Text.ToString().Trim() + "')";
cmd = new OleDbCommand(cmdText, con);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Try changing the advanced compile configuration to x86.
This is usually because you have a 64bit operating system.
in VS2008
Build -> Configuration Manager -> Active Solution Platform: -> New -> Type or select the new platform -> x86 - > OK
edit:
Try the following:
go to
C:\Windows\SysWOW64
open odbcad32.exe
if you cannot find excel in the list just click on Add and add it
You can register you assembly with RegSrv32
Because you use COM, and COM must be regsitered.
Link : http://msdn.microsoft.com/en-us/library/ms859484.aspx
RegSrv32 permit you to register your COM in register base (microsoft.ace.oledb.12.0 provider)
I have had this problem before when I have deployed an application on a User's machine that has Office 2003 installed rather than Office 2007. It sounds to me like the version of Office on your machine isn't installed correctly.
One possible work around is to change your Provider to a previous version like Microsoft.ace.oledb.4.0 and see if the same error persists.
The first thing you need to check is your build configuration of your application.
If you have built your project under x86 platform, then in order to
resolve you issue you should install the following packages on your
machine:
In order to use the 'Microsoft.ACE.OLEDB.12.0' provider you must
install the Microsoft Access Database Engine 2010 Redistributable
first, this installation is available at:
http://www.microsoft.com/download/en/details.aspx?id=13255 .
After the installation has complete, try running you application, if this
solves the issue great, if not, continue to step 2.
This next step is an unexplained workaround, which works for Office
2010, even though it is the Data Connectivity Components of Office 2007. I am not quite sure why this works, but it does and this has been proven to work in almost all cases. You need to install the 2007 Office System Driver: Data Connectivity Components, this installation is available at:
http://www.microsoft.com/download/en/confirmation.aspx?id=23734 .
After this installation is complete, try running your application, this should resolve the issue.
If you are trying to run an application built under x64 or AnyCPU
platform, I would recommend first validating that it runs as expected
under the x86 platform. In the event that it does not run under that
x86 platform, perform the steps in the first part and validate that
it runs as expected.
I did read that the MS Access drivers including the OLEDB Database
driver works only under the x86 platform and is incompatible under
the x64 or AnyCPU platform. But this appears to be untrue. I
validated my application was running when building x86, then I
installed the Access Database Engine using the passive flag.
First download the file locally You can download the installation
here: http://www.microsoft.com/en-us/download/details.aspx?id=13255
Installing using the command prompt with the '/passive' flag. In
the command prompt run the following command:
'AccessDatabaseEngine_x64.exe /passive'
After these 2 steps I managed to run my application after building in
x64 or AnyCPU build configuration. This appeared to solve my issue.
Note: The order of the steps seems to make a difference, so please follow accordingly.

How to set proper path to TNSNAMES file in C# application?

I have a program in C# that use ODP.NET dlls:
oci.dll, ociw32.dll, Oracle.DataAccess.dll,
orannzsbb11.dll, oraocci11.dll, oraociicus11.dll,
OraOps11w.dll.
I've got 2 computers. First with whole ODAC package installed, and second without that package. But I have all required dlls in my exe directory, so ODAC is not a problem I think.
The difference between these computers is the path to the TNSNAMES file.
First: C:\app\OraHome_1\Network\admin\
Second: C:\Oracle\product\11.2.0\client_1\network\admin
On the first computer, the program works fine. But on the second one with the same connection string, I get the error:
cannot open connection (ORA-12154)
Using SQL Plus I can connect on both computers. How can I show my program the proper path to the tnsnames.ora file?
You can set the TNS_ADMIN environment variable programmatically. See this page for a step by step. That is if you wanted to change to a specific TNS_NAMES.ORA file. The Oracle Client must still be installed on the client machine.
From ConnectionStrings - without using TNS:
Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort))(CONNECT_DATA=(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;
EDIT: Added 3rd option
Please see this question which could aid you in finding the current location of the client's TNS_NAMES.ORA file - which you could open and modify if you wish (add your own connection if it doesn't exist)
You don't need to care about the path of your TNSNames file: it'll be automatically discovered by the library itself... once you have it installed. That's the key point: distributing the dll within your project is not enough. You need to install ODP.Net on the machine that need to use it: actually the installation simply create a few registry entry, and one of them point to the right oracle dir (in which the library can find out the tnsnames when needed).
Morover, as someone pointed out, you don't need a tnsnams file at all. You could write everything needed inside the connection string.
Here's one I use in my environment:
Data Source= (DESCRIPTION =
(ENABLE = BROKEN)
(ADDRESS_LIST =
(LOAD_BALANCE = ON)
(FAILOVER = ON)
(ADDRESS = (PROTOCOL = TCP)(Host =por10srv-a)(Port = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = por10.gruppo.autostrade.it)
(FAILOVER_MODE =
(TYPE = SELECT)
(METHOD = BASIC)
(RETRIES = 10)
(DELAY = 3)
)
)
);User ID=npa_collaudo;Password=npa_collaudo;
You don't need to install ODP.NET (or for that matter the Oracle Client) as you seem to have the required DLLs for a local distributable inline oracle client. In your case it's possible to have the TNSNAMES.ORA file located in the same folder as your executable and your specialised "inline oracle client" will pick it up from there. Otherwise the oracle client local to your application will try to pick it up from any client installed on the machine.

Categories