How to use the class SqlCeConnection in the Window Phone 7 application? - c#

I am developing window phone 7 application. I am new to the Window Phone 7 application development. I want to use the SQL server compact edition database in my application for database connectivity. So in my application I have created the database by right clicking the 'Data Connection' & Choosing the 'Add Connection' in Server Explorer. After that I have created the database by using the Create button in the opened window.Then I have tested my connection. It was successful. I have added that created database file in my application by right clicking on the Project Name & choosing the add existing item. The database file was added as the 'ExpenseManagerDB.sdf' I have created the tables for this database by using the Server Explorer. Now I want to programmatically do the database connectivity for my application. So I am using the following code
namespace ExpenseMgrMobAppl.Category
{
public partial class Category : PhoneApplicationPage
{
private void Submitbutton_Click(object sender, RoutedEventArgs e)
{
string conSTR = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\ExpenseManagerDB.sdf;Persist Security Info=False";
SqlCeConnection connection = new SqlCeConnection(conSTR);
SqlCeCommand cmd = new SqlCeCommand("select category_name form category where category_id=1", connection);
connection.Open();
textBlock1.Text = cmd.ExecuteScalar.ToString();
connection.Close();
}
}
}
But I am not finding any Namespace/Assembly for the SqlCeConnection class. I have also tried to add reference to the dll 'System.Data.SqlServerCE.dll' in my application. But the reference could not be added. What should I need do for database connectivity ? What I need to do to use the SqlCeConnection class in my application ? I am looking for thing from which I can use the SqlCeConnection class in my application ? Can you please provide me any solution or link through which I can resolve the above issue ? If I am doing anything wrong in above case then please guide me.

SQL CE is not available in this release of the tools.
The alternatives are storage behind a web service, 3rd party db sources like Sterling or local storage in files using for example XML and LINQ.

As Mick N says there are some 3rd party databases available for the phone. Have a look at
Perst (Commercial, but I believe free for non-commercial use)
Sterling
Windows Phone 7 Database
However my advice would be to think carefully about whether you really need a full relational database in your app on the phone. If you are just using it to store and retrieve data, binary serialized files are extremely efficient and lightweight.
Remember the phone is a very resource constrained environment. Whereas on the desktop we would immediately turn to a database for most data storage requirements because it makes our life easier. On the phone we need to be more careful and optimize for the environment - even if that makes our lives as programmers a little harder. A full database shouldn't necessarily be the first option when thinking about storing data.
That said if you have a data requirement that you feel warrants a full relational database then you should absolutely use one of the aforementioned DBs.

Related

Using Access database with C# on another computer

This feels like a dumb question but I am a bit confused. I am building a C# address book application (Windows Form) that adds, deletes, selects, and updates contacts to an Access database and I'm using DataGridView in the application to show the contacts. I follow the easy steps in connecting to an access database using the wizard, which is Add New Data Source --> Database --> DataSet, then for the Data source I use Microsoft Access Database File (OLE DB), and for the Database FileName, I pick a file on my computer, as shown below.
Now I am confused, because I have to present this on another computer?? Obviously, it won't have the same file address as the one I circled for my computer. Is there a different way to do this or something, I'm not sure what to do. I've heard something about mdb files, but I just have to run the executable file on their computers, so I don't know... I use Access 2016, but the computer I am presenting on uses 2013. Thanks
Okay, nevermind. I found out that I can simply edit the connection string code. I have to test it once in visual studio, then it works appropriately.
public Form1()
{
InitializeComponent();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Chris\Documents\mydb.accdb;
Persist Security Info=False;";
}
to
public Form1()
{
InitializeComponent();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\OtherComputer\Desktop\mydb.accdb;
Persist Security Info=False;";
}
Maybe you can put access DB file(.accdb) to your WebSite or Project.
and Database file name :
~/Book_Sample/Access_db1.mdb
If you use Access 2007~2013 (.accdb)
You need to install "Microsoft Access Database Engine Redistributable"
http://www.microsoft.com/en-us/download/details.aspx?id=13255

C# Project - InstallShield , MySql error when run after installation

I have a project in C# which is created in Visual Studio 2013. I want to create an installer using Install Shield free version. I created an installer and trying to run it on other computer but, when I run it and trying to log into program, I have problems about mysql database. Error message is:
Unhandled exception has occured in you application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.
Cannot connect.
If I click on details button, I have a serie of errors which refers on Mysql. Example:
System.Exception: Cannot connect ---> MySql.Data.MySqlClient.MySqlException: Unable to connect to any of the specified MySQL hosts.
at MySql.Data.MySqlClient.NativeDriver.Open()
at MySql.Data.MySqlClient.Driver.Open()
at MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings)
at MySql.Data.MySqlClient.MySqlPool.GetPooledConnection()
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver()
at MySql.Data.MySqlClient.MySqlPool.GetConnection()
at MySql.Data.MySqlClient.MySqlConnection.Open()
at simulator.ConnConfig.getConnection()
simulator is the name of the project. ConnConfig is a class where is the connection and getConnection() is a function from ConnConfig which return connection. II tried to install on another computer .NET Framework 4.5.2, SQL Server, but also didn't worked.
In my project, I use localhost server where I have a database with 2 tables. My question is, is there any possibility to add that localhost database to installer and use it on another computer? And what redistributables requires this operation? Also, I have installed on computer .NET Framework 4.5, Sql Server 2012..but when I try do add them in InstallShield via Redistributables, but it keeps saying that Needs to be downloaded. Why?
UPDATE
I have this Class where I make the conenction. But I receive error: Additional information: Illegal characters in path. at that line:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SQLite;
namespace simulator
{
class ConnConfig
{
private static string conn = "Data Source=c:\aplicatie.db;Version=3;Password=myPassword;";
public static SQLiteConnection connect = null;
private ConnConfig()
{
}
public static SQLiteConnection getConnection()
{
SQLiteConnection connect = null;
try
{
connect = new SQLiteConnection(conn);
connect.Open();// here I receive the error
return connect;
}
catch (SQLiteException e)
{
throw new Exception("Cannot connect", e);
}
}
}
}
UPDATE 3
In that class I make the connection to database. In the other forms I just use tables and their data. For connection to program, I use a login form which uses this class to getConnection(). I created that database by adding an ADO.NET in simulator project. And with that, it comes those 2 tables that I already have in localhost server. So, Is ok if I have to create another empty database with new tables, but where to include that code or how to use it, because I don't get how that script works..where should I put it?
If your database is going to be installed on each client and your tables are not massive you might want to look at something lighter like SQLite which doesn't need any installation just the dlls and is very fast and efficient and only runs when your program does.
As for for the Needs to be Downloaded issue, it seems you have not setup your prerequisite correctly, you an correct this by following the steps in this article
Adding InstallShield Prerequisites, Merge Modules, and Objects to Basic MSI and InstallScript MSI Projects
You might want to look into determining if MySQL is the right solution for you.
SQLite vs MySQL vs PostgreSQL: A Comparison Of Relational Database Management Systems
And to see the limitations of SQLite SQLite
Because honestly seems like overkill to install MySQL on every system. If you had one server with MySQL on the network, okay. But on every system seems like a bad idea.
As far as connecting to an SQLite database here is a List of Connection Strings for SQLite
See this topic on how to create Databases and tables Create SQLite Database and table
My guess is your program doesn't bundle up the database alongside the setup upon deployment. This may be due to the fact that you didn't mark your database as a Data File in the Project Files. Try this, right click on your project name in Solution Explorer and select Properties from Menu. From the horizontal tabs click on the Publish Tab. Under Install Mode and Settings click the Application Files button. A dialog box appears with all Application files. Set your database Publish Status to Data File from the drop down on the corresponding cell. This way your database will be bundled together with the setup upon publishing. Hope this helps.
You can access SQLite via ODBC.

Local Database with Visual Studio 2012

I am creating a application and I want to use a local database stored on the clients local machines. I am debating over if I should use SQLITE or is there something in Visual Studio to help me. The other thing is that I want to create the database programmatically in the users directory when the application is launched.
I am see a few things online but the articles were all about SQL Server stuff and that is not want I want to do with this application. All data will need to be stored on the local machine.
You can use SQL Server Compact, which has tooling in Visual Studio. It's syntax-compatible with SQL Server, but stores its data in a local file, which you can create on the fly (at app startup, for example).
You can create the SQLite database on the fly with the libraries provided from their website. I have used it in many projects for my personal code, as well as it being used in some of the internal architecture of Data Explorer (IBM Product). Some sample C# to create a database file:
if (!Directory.Exists(Application.StartupPath + "\\data"))
{
Directory.CreateDirectory(Application.StartupPath + "\\data");
}
SQLiteConnection conGlobal;
if (!File.Exists(dbGlobal))
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";New=True;Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
firstRun = true;
}
else
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
}
try
{
conGlobal.Open();
}
catch (Exception)
{
//do stuff
}
Simply initiating a connection to the file will create it if the new=true is passed as the connection string. Then you can query it and get results just like you would any database.
You also have the ability to password protect the database files to prevent access to them from just opening them with an SQLite-Shell or a different SQLite DB viewer.
For more info on the pragma statements that are being passed in the connection string, see the following: http://www.sqlite.org/pragma.html
I'm not sure about programmatically (that's probably what you meant, right?) creating the database, but SQL Server Compact Edition has served me well in the past for simple apps. It's embedded and even runs in medium trust.

C# windows application set up on different machines and all work on one SQL Server 2008 database

I have created a desktop application with SQL Server 2008 as backend. I want to use this database from my application that is installed on a number of machines.
What are the requirements for that application to connect to the centralized database.?
It is pretty simple, You want the architecture as Client-Server model were the server has the database .Hence you need to have MS SQLserver 2005 or higher versions and create database connect it to sqlserver. Grant permission for the clients to access the database.
From visual studio side:
Add the above created .mdf(database file) as the new data source.
Data-->Add new Data Source , and follow the steps in the wizard[p.s the type of connection has to be sql sever type ]
while doing this a connection string will be created by VS. Use tht connection string to access from the client side.
This link would be useful : http://msdn.microsoft.com/en-us/library/sxds9ett(v=vs.80).aspx
To keep the connection string in its resources, ofcourse.
Resources are:
Doubleclick on project's Properties (at solution explorer).
Then Settings tab.
If there is no default setting file, create it by clicking the long link label.
Add a setting like "ConnectionString" with the value like "Data Source = ..." whatever.
Then you can run your sql scripts like:
SqlConnection conn =
new SqlConnection(Properties.Settings.Default.ConnectionString);
And go on.

SQL Server CE Local Application issues

I'm here for a trouble with SQL Server CE in a C# application.
This is a really simple question, at first I was trying to do an INSERT into a table, but it didn't do it, so I searched and the solution was to put the literal string to connect to the database.
try
{
cnTrupp.Open();
SqlCeCommand com = new SqlCeCommand("INSERT INTO tipo_venta(nombre) VALUES (#nombre)", cnTrupp);
com.Parameters.AddWithValue("#nombre", pNombre);
com.ExecuteNonQuery();
com.Dispose();
}
catch (SqlCeException e)
{
LogFile log = new LogFile(e.Message);
}
finally
{
cnTrupp.Close();
}
After that with the literal string, I was wondering, when I deploy the app, how I'm supposed to change that connection string? so it points to the actual database in the new computer
The comments on "Paul Sasik"'s post talk about the Data Source=|DataDirectory|\example.sdf entry in the app.config file of your application.
For the sake of completeness: This |DataDirectory| part is a macro that expands automatically to the folder where your application is running and should not be hardcoded. If you want to change the folder, you may use the following line in Program.cs:
AppDomain.CurrentDomain.SetData("DataDirectory", <New Folder>);
At least this is true for desktop applications. As mobile applications (in VS 2005 and 2008) don't support the same configuration mechanism, you have to create the connection string manually there.
Make use of the .NET app.config file. This is a VB article but will get you started.
.NET config files are fairly easy to work with but with information like a db connection, you might want to consider encrypting the string in the config file. Or at least the password. That is if security is a concern. Many times it's not. Especially on mobile devices which are inherently unsecure (at least in the WinCE world... up to CE5 v.6)

Categories