Please someone help me - I have a problem.
I'm trying to code an alternate database for a program I am writing in C#. You see on the website I managed to do it with an if..
This is my php code:
//database connection
$conexion = #mysqli_connect("localhost","todo","todo","dbdaq");
//if mainserver connection is not made then it connects to secondary server
if (!$conexion){
$conexion = mysqli_connect("192.168.0.12","todo","","dbdaq");
}
And that works in PHP, but when I try to write something like that in C#, I can't manage to do it.
Here is my database connection class in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data;
using MySql.Data.MySqlClient;
namespace ComunicacionCSharp
{
class ConexionBD
{
public static MySqlConnection ObtenerConexion()
{
MySqlConnection Conectar = new MySqlConnection("Server =localhost; database = dbdaq ; Userid = root; password =");
return Conectar;
}
}
}
NOTE: this class is called from my main GUI interface.
namespace ComunicacionCSharp
{
public partial class Login : Form
{
MySqlConnection conn = ConexionBD.ObtenerConexion();
public string usuario;
public Login()
{
InitializeComponent();
}
}
}
Can someone please help me? I use to have another version of the database connection with an error message if the connection is not found, but I left coding in C# for a while and could not find that piece of code anymore, and I don't remember how to do it :(
mysqli_connect returns a handle to an open connection and in your C# code you pass an unopened connection. You must change a bit your code, something like this:
public static MySqlConnection ObtenerConexion()
{
MySqlConnection Conectar = null;
try
{
Conectar = new MySqlConnection(yourFirstConnectionString);
Conectar.Open();
}
catch
{
try
{
Conectar = new MySqlConnection(yourSecondConnectionString);
Conectar.Open();
}
catch{ }
}
return Conectar;
}
Remember to check the connection wherever you use it, if both connections fail it will return null.
Related
I'm following along with a Tim Corey tutorial on making a Tournament Tracker WinForm app (this one at this point, in case it helps - https://preview.tinyurl.com/yxmyz8h6)
I've gotten to the point where we are starting to hook up the class library to SQL using some NuGet packages - namely Dapper, System.Data.SqlClient & System.Configuration.ConfigurationManager.
So far the project is split across two namespaces, the class library that holds all the models and data access classes (TrackerLibrary) & the form UI (TrackerUI). I was under the impression from the tutorial that these references only need to exist in the class library and not in the UI (as TrackerLibrary is where Tim directed us to add them)
But without them referenced in the TrackerUI - a FileNotFoundException shows up for all three when you run the code. However, that doesn't happen to him in the tutorial.
The SQL connection string is set up in the App.Config file of the TrackerUI and looks like this...
<connectionStrings>
<add name="Tournaments"
connectionString="Server=localhost;Database=TournamentTracker;Trusted_Connection=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
There is a class in TrackerUI called CreatePrizeForm that has a button click method to validate the form a user completes and then turn that data into a model and pass that model into SQL...
using System;
using System.Windows.Forms;
using TrackerLibrary;
using TrackerLibrary.Models;
namespace TrackerUI
{
public partial class CreatePrizeForm : Form
{
public CreatePrizeForm()
{
InitializeComponent();
}
private void createPrizeButton_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
PrizeModel model = new PrizeModel(
placeNameValue.Text,
placeNumberValue.Text,
prizeAmountValue.Text,
prizePercentageValue.Text);
GlobalConfig.Connection.CreatePrize(model);
placeNameValue.Text = "";
placeNumberValue.Text = "";
prizeAmountValue.Text = "0";
prizePercentageValue.Text = "0";
}
GlobalConfig class handles deciphering whether we are saving to SQL or saving to a Text File as per the imaginary client requirements for the tutorial and grabs the connection string, which looks like this...
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using TrackerLibrary.DataAccess;
using System.Data.SqlClient;
using Dapper;
public static class GlobalConfig
{
public static IDataConnection Connection { get; private set; }
public static void InitializeConnections(DatabaseType db)
{
if (db == DatabaseType.Sql)
{
SqlConnector sql = new SqlConnector();
Connection = sql;
}
else if (db == DatabaseType.TextFile)
{
TextConnector text = new TextConnector();
Connection = text;
}
}
public static string CnnString(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
The IDataConnection interface looks like this...
using System;
using System.Collections.Generic;
using System.Text;
using TrackerLibrary.Models;
namespace TrackerLibrary.DataAccess
{
public interface IDataConnection
{
PrizeModel CreatePrize(PrizeModel model);
}
}
And the CreatePrize method looks like this...
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using TrackerLibrary.Models;
public class SqlConnector : IDataConnection
{
public PrizeModel CreatePrize(PrizeModel model)
{
using (IDbConnection connection = new
System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString("Tournaments")))
{
var p = new DynamicParameters(); // Dapper object
p.Add("#PlaceNumber", model.PlaceNumber);
p.Add("#PlaceName", model.PlaceName);
p.Add("#PrizeAmount", model.PrizeAmount);
p.Add("#PrizePercentage", model.PrizePercentage);
p.Add("#id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute("dbo.spPrizes_Insert", p, commandType: CommandType.StoredProcedure);
model.Id = p.Get<int>("#id");
return model;
}
The error occurs when the code reaches here...
GlobalConfig.Connection.CreatePrize(model);
With the following exception...
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Data.SqlClient, Version=4.6.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.'
When I installed the System.Data.SqlClient NuGet package into the TrackerUI's references - it errors at the same point as before but this time it talks about Dapper...
System.IO.FileNotFoundException: 'Could not load file or assembly 'Dapper, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.'
Then if you then install Dapper into TrackerUI references, it gets past the GlobalConfig.Connection.CreatePrize call into SqlConnector.cs and errors on the using (IDbConnection connection = new System.Data.SqlClient.SqlConnection... line below...
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using TrackerLibrary.Models;
namespace TrackerLibrary.DataAccess
{
public class SqlConnector : IDataConnection
{
public PrizeModel CreatePrize(PrizeModel model)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString("Tournaments")))
{
var p = new DynamicParameters(); // Dapper object
p.Add("#PlaceNumber", model.PlaceNumber);
p.Add("#PlaceName", model.PlaceName);
p.Add("#PrizeAmount", model.PrizeAmount);
p.Add("#PrizePercentage", model.PrizePercentage);
p.Add("#id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute("dbo.spPrizes_Insert", p, commandType: CommandType.StoredProcedure);
model.Id = p.Get<int>("#id"); //Pulls ID from the p variable that represents the id of the record in the database
return model;
}
With another FileNotFoundException...
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.'
Adding references within the TrackerUI namespace to Dapper, System.Data.SqlClient and System.Configuration.ConfigurationManager resolves the exceptions and enables the program to write to SQL no problem. I just wanted to clear up whether that was what I needed to do by default or whether I've missed something earlier and the TrackerUI namespace shouldn't feature references to them. Just don't want to get into bad habits.
Sorry if I've missed any important detail - kinda new to this and have tried to be as thorough as possible but let me know if there is anything else I need to provide.
Thank you for your clarification and help in advance!
I am making a small game in Unity and I'm in need of a database. I tried using SQLite database because that seemed to be recommended by the web.
Now I'm having troubles with actually connecting to the local database via c#.
I implemented the Data in SQLite .dll's.
I am trying to get 1 name from the database that I created using SQLite developer.
Below is my DataConnection class, which I use to connect to the database.
using UnityEngine;
using System.Collections;
using System.Data;
using Mono.Data.SqliteClient;
public class Dataconnection : MonoBehaviour {
private string _constr = #"Data Source=C:\Program Files (x86)\SharpPlus\SqliteDev\GameDatabase.db;Version=3;";
private IDbConnection _dbc;
private IDbCommand _dbcm;
private IDataReader _dbr;
public Dataconnection()
{
}
public Dataconnection(string constring)
{
_constr = constring;
}
public string ExcecuteQuery(string SQL)
{
string output = "";
try
{
_dbc = new SqliteConnection(_constr);
_dbc.Open();
_dbcm = _dbc.CreateCommand();
_dbcm.CommandText = SQL;
_dbr = _dbcm.ExecuteReader();
}
catch
{
}
while (_dbr.Read())
{
output = _dbr.GetString(0);
}
_dbc.Close();
return output;
}
}
Then I call the following method from another class:
datacon.ExcecuteQuery("SELECT name FROM employee WHERE empid = 1;");
I get the following errors when running the code:
So I'm guessing it has something to do with a 32/64 -bit mismatch or is there something wrong with creating an instance of a script like this?:
private Dataconnection datacon;
void Start()
{
datacon = new Dataconnection();
}
Happy to receive any help at all. I'm familiar with using database, just new to SQLite.
It says it cannot load the native sqlite.dll because you have there 64 bit version and it needs 32 bit
Place this in your app folder https://www.sqlite.org/2015/sqlite-dll-win32-x86-3081001.zip
Please fill that empty catch on line 38 with a throw;
as there is an exception hidden there which is the true cause of the null reference.
You could also post your connection string so I could make this answer better.
I got it working now. The problem was my that one of the SQLite .dll's was still 32bit. I did this tutorial over again and searched google for the 64bit .dll files and now it's working.
Problem
I installed and configured a ApacheDS server running ldap. This was a huge step forward for me in teaching myself ldap. However, the following C# console code returns the following error:
System.DirectoryServices.Protocols.LdapException {"The supplied credential is invalid"}
My code is to use this sample code to authenticate a sample user.
Code
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleLdapAuthentication
{
class Program
{
static void Main(string[] args)
{
RunLdap run = new RunLdap("localhost", "organization", 635, "hderp", "spaceballs1234");
bool result = run.ValidateCredentials();
if(result)
{
Console.WriteLine("Authentication Succeeded");
}
else
{
Console.WriteLine("Authentication Failed");
}
}
}
}
SampleLdapAuthentication.cs
using System;
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace SampleLdapAuthentication
{
public class RunLdap
{
private static string _domainController;
private static string _domain;
private static int _port;
private static string _userName;
private static string _userPassword;
//Constructor. Takes the domain controller, domain, port, username, and password and then calls Ldap Method to run authentication
public RunLdap(string domainController, string domain, int port, string userName, string userPassword)
{
_domainController = domainController;
_domain = null;
_port = port;
_userName = userName;
_userPassword = userPassword;
}
public bool ValidateCredentials()
{
LdapDirectoryIdentifier ldi = new LdapDirectoryIdentifier(_domainController, _port);
NetworkCredential networkCredential = new NetworkCredential(_userName, _userPassword, _domain);
try
{
//We use using so we dispose the object as soon as it goes out of scope
using (LdapConnection connection = new LdapConnection(ldi))
{
//connection.SessionOptions.SecureSocketLayer = true;
connection.AuthType = AuthType.Kerberos;
connection.Bind(networkCredential);
//Not sure what this is doing
}
return true;
}
catch(LdapException ldapException)
{
return false;
}
return false;
}//End of ValidateCredentials
}
}
LDAP Server Details
Notes
The following are worth noting in what I am doing:
I followed this tutorial in creating the server and DIT.
According to my understanding ApacheDS supports keberos out of the box now, so my authentication type should be fine. That is, AuthType
It fails on connection.Bind() method
I am thinking maybe there is something wrong with how I am entering in the credentials and that my C# code is fine. That is why I included the server AD information. I am new to LDAP and using it to authenticate users, so I appreciate your help.
You're not using the distinguished name of the user. When you create your NetworkCredential object, you should be using the distingushed name of the user, in this case, cn=Herp Derp,ou=users,o=organization instead of hderp. The LDAP doesn't know where to look for hderp without the o and ou values.
I am using C# and the Entity Framework to access a MySQL database.
I am grabbing the results of a stored procedure, and trying to turn them into a list of objects, However whenever it comes to the part what references a table through a one to many relationship, it fails with the error
There is already an open DataReader associated with this Connection which must be closed first.
The code I am using is here:
using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CarHireCommon.DataObjects;
namespace CarHireServer
{
public class DatabaseHandler
{
protected static DatabaseHandler instance;
protected carhireEntities1 Entities;
public static DatabaseHandler GetInstance()
{
if (instance == null)
instance = new DatabaseHandler();
return instance;
}
public DatabaseHandler()
{
Entities = new carhireEntities1();
}
public List<AvailableAssets> GetAvailableAssets(DateTime startDate, DateTime endDate)
{
ObjectResult<asset> res = Entities.GetAvailableAssets(startDate, endDate);
List<AvailableAssets> list = new List<AvailableAssets>();
foreach(var assetRes in res)
{
AvailableAssets asset=new AvailableAssets();
asset.id = assetRes.id;
asset.Comment = assetRes.comments;
asset.Make = assetRes.make;
asset.Model = assetRes.model;
asset.Fuel = assetRes.fuel;
asset.LongTerm = assetRes.longterm;
// This is the line that errors:
asset.Category = assetRes.category.categoryname;
list.Add(asset);
}
return list;
}
}
}
I have allready told it which table the Stored Procedure returns, and the other variables access correctly.
I have also tried doing it the long way with:
var cat = from b in Entities.categories where b.id == assetRes.category_id select b;
asset.Category = cat.FirstOrDefault<category>().categoryname;
However the thing still exceptions with the exact same error.
I found C# Entity Framework: There is already an open DataReader associated with this Connection which must be closed first which will probably help you exactly with this question.
GL!
I am trying to develop a simple application with a simple SQLite database. I am new to C# so I may have missed something obvious. When I run the following code, it returns the error:
SQL logic error or missing database.No such table: Customer
(edit: Yes I have created that table within the database, I performed/confirmed this using the sqlite command prompt
Here is my code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace TestPersonDatabase
{
public partial class DBconnection : Form
{
SQLiteDatabase sqliteDb = new SQLiteDatabase();
public DBconnection()
{
InitializeComponent();
}
// Using SQLite
private void btnInsert_Click(object sender, EventArgs e)
{
Dictionary<String, String> data = new Dictionary<String, String>();
data.Add("CustomerId", this.fieldInsertId.Text);
data.Add("FirstName", this.fieldInsertFName.Text);
data.Add("LastName", this.fieldInsertLName.Text);
data.Add("MobileNumber", this.fieldInsertDob.Text);
try
{
sqliteDb.Insert("Customer", data);
}
catch(Exception error)
{
MessageBox.Show(error.Message);
}
}
}
class SQLiteDatabase
{ String dbConnection;
public SQLiteDatabase()
{
dbConnection = "Data Source=" + (global::TestPersonDatabase.Properties.Resources.database);
}
public bool Insert(String tableName, Dictionary<String, String> data)
{
String columns = "";
String values = "";
Boolean returnCode = true;
foreach (KeyValuePair<String, String> val in data)
{
columns += String.Format(" {0},", val.Key.ToString());
values += String.Format(" '{0}',", val.Value);
}
columns = columns.Substring(0, columns.Length - 1);
values = values.Substring(0, values.Length - 1);
try
{
this.ExecuteNonQuery(String.Format("insert into {0}({1}) values({2});", tableName, columns, values));
}
catch (Exception fail)
{
MessageBox.Show(fail.Message);
returnCode = false;
}
return returnCode;
}
Obviously the code above is two different classes put together. Just made it easier for you to read.
It seems like it cannot find the database file. But I appear to have linked it up correctly (its in the solution resources). Any help would be very much appreciated as I am a bit stumped! Thanks :)
You never opened your sql connection try:
dbConnection.Open(); //Initiate connection to the db
It doesn't look like you've created the table.
Before you input any data you'll need to create the table using something like:
this.ExecuteNonQuerySQL("CREATE TABLE Customers(CustomerID INTEGER PRIMARY KEY, sPassword TEXT, CustomerName TEXT);");
Once you've created the table the insert code you have should work fine.