SQL Server CE Local Application issues - c#

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)

Related

C# .NET Core SQL Server Connectivity

Within my startup, I load a set of database connection strings from the appsettings.json file. The connection strings look as follows
"CoreConnectionString": "Server=localhost; Database=DBCore; Uid=someUserName; Pwd=somePW",
"IdentityConnectionString": "Server=localhost; Database=DBAuth; Uid=someUserName; Pwd=somePW"
What is the best way to encrypt this information so I don't show the actual user name and password?
Here's two suggestions to not expose your DB Password and Conn Strings:
Use a secret file in your computer, apart from your Solution. In Visual Studio 2022 you can do it by clicking your project. Just throw your connections strings there like in AppSettings.json.
Pro: Easy to use
Con: You can't deply it with your project or store it at github
Use Azure Key Valut to store all connection strings. Read this doc from Microsoft if it's your way to go.
Pro: No need for local files. Cloud stored Keys.
Con: Need a bot more configuration in your project and an Azure account.

ASP.NET and C#: connection string in web.config vs connection string stored on Azure

I have a web form developed in ASP.NET and C#. I am storing the connection string to a database in the web.config file like this:
<connectionStrings configSource="MySecrets.config" />
This points to a local file in the same directory as the solution. Debugging locally works, however it is not advisable to commit this file to source control to avoid exposing these secrets.
This article mentions that it is possible to store connection strings on Azure - in the Configurations section of an App Service. The article also says that it's possible to retrieve the connection strings in the code by doing:
dbConn = System.Configuration.ConfigurationManager.AppSettings("myConnStringName")
The article also mentions that "if the application setting(s) happen to already exist in your web.config file, Windows Azure Web Sites will automatically override them at runtime using the values associated with your website. Connection strings work in a similar fashion.
(This assumes that your connection strings are explicit in the web.config file, and if committed to source control, they would be exposed.)
However, in my code, I already have a line with:
dbConn = WebConfigurationManager.ConnectionStrings["myConnStringName"].ConnectionString
Questions:
1) How am I supposed to reconcile these two lines without declaring the same variable (dbConn) twice?
2) How can I not commit MySecrets.config to source control, but at the same time use it when I debug my app locally, while using the connection string stored on Azure when working with the published app?

Updating Connection String in DLL from Winforms - Linq to SQL

I developed a class library that uses Linq To Sql to communicate with a database.
When I added this I used Server Explorer to add a database and all the tables I want to talk to.
It then built a .dbml file for me.
In the "Designer" file I can see:
public TPDataContext() :
base(global::TPAPI.Properties.Settings.Default.TruePotentialConnectionString, mappingSource)
{
OnCreated();
}
If I update the "Linq to SQL" it regenerates a new designer.cs file
It stored the connection string in Settings.settings with the scope of "Application".
All functions just fine.
But, I have then added a winfoms project that needs to change this setting. So I added the following code:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings["TPAPI.Properties.Settings.TruePotentialConnectionString"].ConnectionString = txtConnectionString.Text;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("connectionStrings");
This updates the connection string in the dll but it only takes effect when the application is shutdown and restarted.
When I am upgrading clients it overwrites what the user had already entered when using it previously.
I cannot seem to work out the best way to:
Not overwrite previous user defined connection string when the app is upgraded.
Be able to save the new connection string and use it without having to stop/start the app.
Having had a read of other threads it appears that the dll shouldn't really have any "local" settings in it (?) and they should all be sent by the winforms app. But, I am unclear on how use Linq to Sql in the dll without it automatically looking/adding it's own connection string.
Can anyone help please?
Thanks
I have decided to rewrite all my DataContext calls to accept the connection string parameter.
I had to amend and test about 40 functions but now the connection string is stored in the winforms application as a user setting and overrides the default connection string generated by Linq to SQL.
So, now in my dll it now looks like
TPDataContext db = new TPDataContext(connStr);
HTH

Access denied for user 'root'#'localhost' (using password: YES) in Visual Studio

Kindly bear with me. I am a Microsoft SQL Server person with loads of Visual Studio experience, but I need to get something done using a MySQL database.
I am trying to create a little tool here that will allow our developers to quickly update database records, and I am using Visual Studio to create a small Windows Form to do this.
In a Microsoft SQL Server connection string, I could write something like this:
Server=myServerAddress;Database=myDataBase;User Id=username;Password=password;
In a MySQL connection string, there appear to be multiple other options, but the first one looks basically the same:
Server=myServerAddress;Database=myDataBase;Uid=username;Pwd=password;
When I attempt to open the MySQL connection from my PC, I get the exception listed in the title (actually, it shows the Uid value and the IP Address of my PC instead of localhost, but I am hoping more people will recognize the error easier this way):
public static void MySQLi_Connect() {
m_err = null;
var str = Properties.Settings.Default.ConnStr;
try {
m_conn = new MySqlConnection(Properties.Settings.Default.ConnStr);
m_conn.Open();
} catch (MySqlException err) {
ErrorLog("MySQLi_Connect", err);
}
}
I did a search, and it seems that the Uid on MySQL needs to be granted access from the specific IP Address that the connection is being made from.
Further, I found this on the mysql.com doc pages:
If you do not know the IP address or host name of the machine from which you are connecting, you should put a row with '%' as the Host column value in the user table. After trying to connect from the client machine, use a SELECT USER() query to see how you really did connect. Then change the '%' in the user table row to the actual host name that shows up in the log. Otherwise, your system is left insecure because it permits connections from any host for the given user name.
A few things:
It looks like I can connect to MySQL by using a % setting in the Uid jp2code, but MySQL says I need to change that back right away to remove system vulnerability.
Microsoft SQL Server did not seem to require this - or, if it did, I simply never was slapped in the face with this vulnerability issue like MySQL is doing.
Now, I ask:
If this is going to be a tool used by different developers on different PCs, is it common practice to turn the blind eye to this horrendous system vulnerability?
Is this not really as big of a concern as MySQL is making it appear?
What is the best way to continue with a Windows Forms application that needs to connect from various locations? Obviously, I do not want to continuously be adding more entries for a particular application every time another developer wants to use the tool or someone tries to run it from a different PC.
You can configure the security of your MySQL server as strong as you like, usually you dont connect users but applications. So if you have your root user without password in production environment is your fault. Usually developers have access to development environment, so this is not a big deal.
Of course try to have as many users as roles you need, for your example I think one user is enough. In production use a secure config file for save a secure password and set you mysqlserver restricted.
I was having the same issue and I found out that the password wasn't correct.
GO to your sql command line and type the code below:
mydb in the line below is the name of the database you are working on.
passwd in the line has to match the password you have in c# code so in your case "password"
grant all privileges on mydb.* to myuser#localhost identified by 'passwd';
Like OP says you can wildcard the hostname portion. I used this on our dev-server (not recommended for production servers):
update mysql.user set host = '%' where host='localhost';
Then I had to restart the server to make MySQL use it (propably I could just have restarted the MySQL service).

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.

Categories