Creating a Local DB for a WPF application - c#

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.

Related

C# application deployment issue with .mdf database

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;

#Functions does not exist in the current context

I know variations of this issue has been asked and answered. However, this is a specific case in which I have a Functions.cshtml page defined and I have successfully referenced functions found on that page. I've been able to successfully run my web site. However, VS 2015 periodically can't find the Functions.xyz reference when I recall the project in the IDE. Sometimes, I can copy the Functions.cshtml page to another location, then delete it from the project, close out VS, reopen VS and re-add Functions.cshtml back to the project. That in itself does not cause VS to now resolve the problem. I have to then open the Functions.cshtml in the IDE editor and select to build the web site. Then SOMETIMES, VS will then resolve the reference. However, I'm stuck now - VS is completely unable to resolve the reference and need new ideas on how to resolve it. Here is the code samples:
Functions.cshtml:
#Functions {
public static System.Data.DataSet qryGeneralExecute(string query)
{
using (SqlConnection cn = new SqlConnection(getConnectionString(false).ConnectionString))
using (SqlCommand cmd = new SqlCommand(query, cn))
{
SqlDataAdapter adapter;
System.Data.DataSet ds = new System.Data.DataSet();
cmd.CommandType = System.Data.CommandType.Text;
cn.Open();
adapter = new SqlDataAdapter(cmd);
adapter.SelectCommand = cmd;
adapter.Fill(ds);
cn.Close();
if (ds.Tables.Count > 0)
{
return ds;
}
return null;
}
}
}
Calling page:
{
bor_studinfoDataSet = Functions.qryGeneralExecute(query);
}
When I run the project, I get The name 'Functions' does not exist in the current context.
Any suggestions on resolving this?
Ok, here's what happened. Between the time my project was working and now was I went thru a process of correcting a completely unrelated SQL Server Management System (SSMS) issue with inability to log into a SQL instance under strict security circumstances. This involved uninstalling & re-installing SQL several times. In the course of correcting this issue, SQL Server Compact 4.0 was uninstalled though v3.5 was installed. Well evidently this somehow triggered this issue, including what I thought was the unrelated error "could not load file or assembly 'System.Web.Helpers', version=3.0.0.0 or one of its dependencies" but appears to be related. I solved this helpers error by doing an update via NuGet of Microsoft.AspNet.WebPages (found this solution by Bjorn here - Could not load file or assembly 'System.Web.Helpers, error on IIS 8 - thanks Bjorn). Once I corrected for this helpers error, this Functions error was solved but I then received the error "could not load file or assembly system.data.sqlserverce, version=4.0.0.0 or one of its dependencies". Searching for its solution, I was led to Could not load file or assembly 'System.Data.SqlServerCe, Version=4.0.0.0. From there, I then proceeded to download and install MS SQL Compact v4.0 and this last error was eliminated. The project now compiles and I can run my app.

Could not load file or assembly 'Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342'

I have installed oracle 11 g r 2 in the server, and I downloaded ODAC112040Xcopy_64bit and installed the .net components.
I copied Oracle.DataAccess.dll that exists in this location Oracle_Folder\odp.net\bin\4 to the bin folder inside my Visual Studio project
When I executed my code, I got this exception:
An unhandled exception of type 'System.BadImageFormatException' occurred in TestOracleConnection.exe
Additional information: Could not load file or assembly 'Oracle.DataAccess, Version=4.112.4.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. An attempt was made to load a program with an incorrect format.
My code is:
public string CallCardDetails(string CallCardNo)
{
//initialize
using (DataSet ds = new DataSet())
{
//connect
using (OracleConnection conn = new OracleConnection("User Id=oraDB;Password=ora;Data Source=CCT"))
{
// Oracle uses : for parameters, not #
string query = "SELECT idcard from CallCardTable where idcard= :pCallCardNo";
// Let the using block dispose of your OracleCommand
using (OracleCommand cmd = new OracleCommand(query, conn))
{
// Note: be careful with AddWithValue: if there's a mismatch between the .NET datatype of
// CallCardNo and the idcard column you could have an issue. Cast the value you provide
// here to whatever is closest to your database type (String for VARCHAR2, DateTime for DATE, Decimal for NUMBER, etc.)
cmd.Parameters.Add(":pCallCardNo", CallCardNo);
conn.Open();
// Again, wrap disposables in a using or use try/catch/finally (using will dispose of things in case of exceptions too)
using (OracleDataAdapter dA = new OracleDataAdapter(cmd))
{
dA.Fill(ds);
return ds.GetXml();
}
}
}
}
}
Okay, I'm going to suggest the following based on my experience with ODP.NET:
Your system is attempting to load the 64 bit Oracle DLL, and can't because the application is running in 32 bit mode. Try setting your application to explicitly be 64 Bit. Alternatively, install the 32 bit ODP.Net drivers and see if those work any better.
Had a similar problem some time ago...
Referring to this question here:
Try to set your projects 'Platform target' to 'x86' and not 'Any CPU'.
Hope this helps!
This is how I resolved it:
Install-Package ODP.NET4 -Version 4.112.3
Check that target framework of the dll and your project match.The file location you posted shows you took it from Oracle_Folder\odp.net\bin\4 the bin folder for 4 version. Look if there is the req dll in bin\4.5 that maybe what you need. As this exception can also occur if you add dlls to your project whose target framework do not match.
Also, clean your solution before placing the dll in bin folder. :)
I usually use the NuGet packages for ODP.net, they work fine. You can find them here.
This is all you need to build your solution, you do not need to install any drivers.
In order to use the Oracle Data Prover for .NET (ODP.NET) Version 4.112.4.0 64bit following conditions must apply:
Target Framework is 4.0 or higher
Architecture must be x64 or AnyCPU (in case of an 64bit Windows, which is most likely the case)
An 64-Bit Oracle Client version 11.2 is installed on your PC and on the target machine
Find some more information in this anser: The provider is not compatible with the version of Oracle client

C# SQLite database connection WPF Crash

Hi All hopefully someone can help me.
I have written a small WPF app which reads the password of a SQL database and shows it on screen for the user. It works fine on the SQL DB but we have changed to use SQLite and while it works fine on my machine (on which I hav written the program) but when I give the .exe file to a user the program will crash on them, as soon as they click a button to OpenFileDiaglog() (this is so the user can select the database to retrive the password)
After some trial and error (of commenting out parts of the code) it would seem to crash when it hits this line.
SQLiteConnection Dbcon = new SQLiteConnection("Data Source= " + Myfile);
but in the event viewer on the machine i am trying to run the program on the error is
Description: The process was terminated due to an unhandled exception
Exception info: System.IO.FileNotFoundException
I have tried to use the .exe file on a few different machines (vista, xp, win 7) all of which have the .net framework 4.0 installed on them.
Like I say all works perfrect on my machine only when it is moved does the error come up.
Any help would be greatly appricated
Because yu must adjust your path of your database on user machine, you have false path on your DataSource when you deploy
Data Source= Path of your databse
I suggest you this code
"Data Source=" + System.IO.Path.Combine(System.IO.Path. GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase), YourFile)
Same problem but this didn't fix it for me. The problem for me was my main app was in .net 4 and the sql lite dll is .net 2 so add useLegacyV2RuntimeActivationPolicy="true" as an attribute to the startup tag in app.config.

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.

Categories