How to protect a *.sdf (sqlCE file) with a password - c#

Is there a way to protect a *.sdf (sqlCE file) with a password or implement a similar security measure?
i try this:
if (!File.Exists(SDK))
{
SqlCeEngine engine = new SqlCeEngine("Data Source=" + SDK + "; Case Sensitive=True");
engine.CreateDatabase();
OpenConn();
SqlCeCommand CMD = new SqlCeCommand();
CMD = Conn.CreateCommand();
CMD.CommandText = "Create table MEN(Code int ,Fname nvarchar(50),Lname nvarchar(50))";
CMD.ExecuteNonQuery();
}
where to change to have password ?

Since SQL CE 2000 password protection is possible:
CREATE DATABASE "secure.sdf"
DATABASEPASSWORD '<enterStrongPasswordHere>'
more here and here

The Visual Studio 2010 extension SQL Server Compact Toolbox can be used to create a database with a password. Encryption of the database is handled automatically once the password is set. The only catch is you need to create a new database with a password using the extension; it cannot password protect existing .sdf files. If you need to keep your existing structure: backup your data and/or schema, and reapply to the new one.
A layered approach, like most security solutions, is typically best and can be applied here. It is important to check (and correct) the encryption state of the file on the operating system level as well. You could even go above and beyond by encrypting the actual .sdf file inside of your run-time.
A good article on that here.
Cheers

Depending on what kind of protection you are looking for, you can password protect your database as well encrypt it.
If you're going to take advantage of either of those options, I believe you have to create the database in SQL Server Management Studio rather than letting Visual Studio create one for you. Take a look at the following page for instructions (page is for Sql CE 4 but should apply to other versions as well):
Dean Hume - A Simple Guide to SQL Compact 4

Related

Insert data into Visual Studio LocalDB in ASP.NET C#

I have a Windows web application and have created a .mdf file in the App_Data folder and I am trying to insert data into the tables already created.
It is able to retrieve codes with a basic SELECT * statement, but I can't insert data, this is the code I have:
private void Update(string username)
{
SqlConnection con = new SqlConnection(#"MYSQLCONNECTION");
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string bcd = "INSERT INTO NameList(name) VALUES (#paraUsername)";
cmd = new SqlCommand(bcd, con);
cmd.Parameters.AddWithValue("#paraUsername", username);
cmd.ExecuteNonQuery();
list.Update();
con.Close();
}
This code has worked for me in the past, but this time round it does not work. There is no error shown, but the data is not inserted into the table.
This is how I call the method in side my button_click method:
Update(tbName.text);
What might be the problem?
Assuming you have a
AttachDbFileName=......
section in your connection string - then this is a known issue:
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. YourDatabase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=YourDatabase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.

How to connect database with C# executable file?

I am writing code for a small company that is all about purchase and sell. I wrote C# code with using external database (SQL Server 2014), now it's time to make the exe file of that code.
I tried my best but it doesn't work.
How can I connect SQL Server 2014 database files with my application so that when someone installs it on his computer he also got SQL Server connected with that application?
Hi actually we deploy code as setup file (.msi), you can create setup project using Wix or install-shield ( maybe other too,but these two are most popular and widely used)
You can do database deployment in two ways
1.) you can provide SQL script for generating SQL server and give instruction for generating Database from Script. It is simple and easy to do.
2.) Other way is provide option to create database from setup. It need some work, but it is more good way.
Now come to your question, you can provide some UI in setup that take input from user and connect to appropriate DB. Or create a UI for Updating configurations, and save configuration (connection string ) in some file ( ex: .ini or .config file).
Below are the some URL for creating Setup and connecting to Db using Wix:
WIXDataBase
installing-databases-using-wix
Creating-an-installer-using-Wix
using-wix-to-install-sql-databases-and-execute-sql-scripts
WiX Samples
Ideally you'd have a SQL server set up somewhere. If not you'll have to install sql server. In your app it's just a matter of setting up the connection string and running sql commands against it.
string connectionString = "Data Source=server //rest of connection string"
Then in c# you can do
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT TOP 100 * FROM SomeTable", con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1} {2}",
reader.GetString(0), reader.GetString(1), reader.GetString(2));
}
}
}
GetString can be changed to GetInt or whatever the datatable will be. This should be enough information to get you started. If you know the structure of the database its simple to put the results into your classes for the application.

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.

Save SQL DataSet to Local MDB File

Context
My appliction uses an SQL database from which it reads my datatables at start of my application. If the application would fail to connect to the SQL DB, I have a local Ms Access .MDB file. I have a separate thread that checks if the local database is outdated.
I have a DataTable which I obtain from my SQL connection --> Verified and working
I can connect to my Access database locally and read from it --> Verified and working
Issue/Question
I'm trying to update my local database by updating it with the DataTable I obtained from my SQL Connection.
public static void UpdateLocalDatabase(string strTableName, OleDbConnection MyConnection, DataTable MyTable)
{
try
{
if (CreateDatabaseConnection() != null)
{
string strQuery = "SELECT * FROM " + strTableName;
OleDbDataAdapter MyAdapter = new OleDbDataAdapter();
OleDbCommandBuilder MyCommandBuilder = new OleDbCommandBuilder(MyAdapter);
MyAdapter.SelectCommand = new OleDbCommand(strQuery, odcConnection);
MyAdapter.UpdateCommand = MyCommandBuilder.GetUpdateCommand();
MyConn.Open();
MyAdapter.Update(MyTable);
MyConn.Close();
}
}
catch { }
}
If I debug this snippet, all variables are what they should be:
strTableName = the correct name for my table
MyConn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyLocation;Persist Security Info=True;JET OLEDB:Database Password=MyPassword;"
MyTable = is the correct table that is also used further on by my application
This process runs through without an error and without using the catch but it does not touch my database, it just doesn't do a thing.
Am I dropping the ball here or just missing the obvious, I have no idea but I browsed many articles and apart for showing the MyAdapter.Update(), there doesn't seem to be much more to it.
Any help is welcome.
Thanks,
Kevin
Does your backup database have to be in access? because if you used SQL Compact Edition it'd be much easier to copy between the two?
Yes, it would either mean attaching it with your installer or just ensuring that all client machines have it pre-installed, it is free however.
if this is an issue then all you need to do (I think, not done it myself)
would be to go to your installer projects properties, click prerequisites and then tick SQL compact so that it will be installed before your application can be used, iv done this before with other frameworks and it just pops up a box with the install shield asking whether they want to download the necessary software and its just one click then it should be done for them.
Do you need a hand on using the compact database also?
One negative by the way is it does lack some higher end features but shouldn't affect average database work
EDIT
if you will be using sql CE you can easily make the databse in VS by clicking data and new data source then following the steps making sure to put sql CE when asked
if it works, you'll end up with an .sdf database
I provided a code snippet that fixed the issue on my related question here: Export SQL DataBase to WinForm DataSet and then to MDB Database using DataSet

INSERT from ASP.NET to MS Access

We are trying to build a Help Desk ticketing system just for intranet. Deciding upon the ASP .NET (C#) with Visual Studio 2008 Express (think we have a full version floating around if we need it). Nothing fancy, couple of pages grabbing NTLM information, system information and storing it along with their problem in a database. Goal is to make it simple, but instead of using our SQL Server 2000 back end, the admin wants me to use MS Access. I have the GridView and connections running smooth. Can pull select queries until my heart is content. However, tying in a couple variables with a text box on a submit button into say an INSERT statement.. well I don't even know where to begin with MS Access. Every internet example is in VB .NET plus seems to be hand coding what Visual Studio has already done for me in a few clicks.
Is MS Access going to be too hard for all we want to do? If not, where do we begin to simply submit this data into the tables?
Edit: After a bunch of playing around we have the OleDB working. It's not pretty, yes SQL Server would be awesome but, sometimes you just have to play ball.
Edit: Anyone looking for an actual coded answer, here you are. There has got to be others out there in the same boat.
string userIP = Request.UserHostAddress.ToString();
string userDNS = Request.UserHostName.ToString();
string duser = Request.ServerVariables["LOGON_USER"]; //NTLM Domain\Username
string computer = System.Environment.MachineName.ToString(); //Computer Name
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\helpdesk.MDB;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO ticketing ([user], [comp], [issue]) VALUES (#duser, #computer, #col3)";
cmd.Parameters.Add("#duser", OleDbType.VarChar).Value = duser;
cmd.Parameters.Add("#computer", OleDbType.VarChar).Value = computer;
cmd.Parameters.Add("#col3", OleDbType.LongVarChar).Value = TextBox1.Text;
cmd.ExecuteNonQuery();
conn.Close();
The admin is nuts. Access is an in-process database, and as such is not well suited for web sites where users will be creating or updating records.
But as far as creating INSERT queries go, Access is no harder than anything else. If you can't create INSERT queries for Access you'll probably have trouble with SQL Server as well.
I also suggest using SQL Server, but considering your problem:
What is your problem writing an INSERT query for Access ?
You should make use of the classes that you'll find in the System.Data.OleDb namespace:
OleDbConnection
OleDbCommand
Quick'n dirty code (not compiled whatsoever):
OleDbConnection conn = new OleDbConnection (connectionString);
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText= "INSERT INTO myTable (col1, col2) VALUES (#p_col1, #p_col2)";
command.Parameters.Add ("#p_col1", OleDbType.String).Value = textBox1.Text;
...
command.ExecuteNonQUery();
There are some caveats with the OleDb classes however (like adding the Parameters to the collection in the order that they occur in your SQL statement, for instance).
Don't bother with Access. Use SQL Server Express. There's also an admin tool for it that looks like the full blown SQL Server management tool.
Access has its place, and can usually do more than what most people give it credit for, but yes you want to use SQL Server in ones of its many forms (eg. SQL Server Express) or another proper "server" database for a web app like this.

Categories