Retrieving image from sql table using a file path, code error - c#

A nice chap called Darin kindly provided me with some code in order for me to retrieve an image by its file path.
However, when I attempt to execute the code, I receive a "NullReferenceException was unhandled by user code; Use the 'new' keyword to create an object instance" on the first var line.
The code can be found below:
var connectionString = ConfigurationManager.ConnectionStrings["SomeCN"].ConnectionString;
using (var cn = new SqlConnection("Data Source=STRSQL04;Initial Catalog=PDC;Integrated Security=True"))
using (var cmd = cn.CreateCommand())
{
cn.Open();
cmd.CommandText = "Select imageID from accounts where MemberID = FM00012";
cmd.Parameters.AddWithValue("FM00012",5);
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
var filepath = reader.GetString(0);
Image1.ImageUrl = filepath;
}
}
}
Can someone point out the error in my ways please?
Apologies as always for asking, what I suspect are, ridiculous questions.

You don't have a connection string called "SomeCN" (or whatever you're using for real) in your app config, so when you try to access the ConnectionString.ConnectionString parameter, it throws a nullref.
Can you post the contents of your app.config, or at least the ConnectionStrings element, so we can see?
Modifying application settings on MSDN (when you try it, you'll see one of the settings types in the dropdown of the settings editor is "ConnectionString").

Related

Usage of MySQL Parameter for creating new user

So I am using a MySQL Server version 8.0.16 and if I try to let dynamically create a new user, i do receive a Error message what says: >>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax. to use near '$password' at line 1<<.
What i can't understand, becouse if i replace the Parameters with the actual value and try it with the shell it works perfectly. I let my code connect as root so and checked if the connection is open what it is. So if I stepped into the code and checked if the parameters are correct everything looked fine. I also added >>'<< at the beginning and end of thext strings that should replace the parameters but it didn't changed the error or what happened.
public bool CreateNewUser(string name, string password, string host)
{
string query = "CREATE USER $name#$host IDENTIFIED BY $password;";
List<MySqlParameter> mies = new List<MySqlParameter>
{
new MySqlParameter("$name", name),
new MySqlParameter("$password", password),
new MySqlParameter("$host", host)
};
return InsertIntoQuery(query, mies);
}
//The InsertIntoQuery looks like this
private bool InsertIntoQuery(string sql, List<MySqlParameter> sqlParameters = null)
{
bool retBl = false;
try
{
using (var SqlConnection = new MySqlConnection(ConnectionStr))
{
SqlConnection.Open();
using (var cmd = new MySqlCommand(sql, SqlConnection))
{
if (sqlParameters != null)
foreach (var item in sqlParameters)
cmd.Parameters.AddWithValue(item.ParameterName, item.Value);
cmd.Prepare();
var retValNonQuery = cmd.ExecuteNonQuery();
retBl = (retValNonQuery > 0) ? true : false;
}
}
}
catch (Exception e)
{
MessageBox.Show("Error: " + e.Message);
}
return retBl;
}
I would expect it to create a new user but it doesn't.
No, for CREATE USER command I don't think you can pass command parameter likewise. Rather substitute the value as is like below using string interpolation syntax.
string query = $"CREATE USER '{name}#{host} IDENTIFIED BY {password}";
For an older C# version consider using string.Format()
string query = string.Format("CREATE USER '{0}'#'{1}' IDENTIFIED BY '{2}'",name,host,password);
Per OP's comment: You can't cause it's not a DML operation. If you are worried about SQL Injection probably cause input value is coming from user input then you will have sanitize it someway and moreover if you observe the input are quoted.
Again, I would suggest that this kind of admin operation should go in a DB bootstrap script and not in your application code.

Unable to query Oracle database via C# API

Good morning.
I am attempting to connect to an Oracle database I have set up. before I go into detail, here's the code:
//string was slightly altered.
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=name)));User Id = system; Password = mypass; ";
string toReturn = "D.BUG-";
using (OracleConnection oracleConnection = new OracleConnection(connectionString))
{
oracleConnection.Open();
using (OracleCommand oracleCommand = new OracleCommand())
{
oracleCommand.Connection = oracleConnection;
oracleCommand.CommandText = "SELECT lixo FROM lixeira WHERE lixo IS NOT NULL";
oracleCommand.CommandType = CommandType.Text;
using (OracleDataReader oracleDataReader = oracleCommand.ExecuteReader())
{
//This point IS reached!
while (oracleDataReader.Read())
//This point is never reached...
toReturn += oracleDataReader.GetString(0);
}
}
}
return toReturn;
Now, I know for a fact that connecting works, and I know for a fact that the table "lixeira" can be found; I have tested this by changing that name to another name, and getting the corresponding "i can't find that table" exception.
'ORA-00942: tabela ou visualização não existe'. (Table or View does not exist)
The issue is that this code is unable to read. The same query ran through SQL Developer works:
SQL Developer screenshot of the same query
So, I'm kinda at a loss as to why oracleDataReader.Read() just never works. Am I doing something wrong?
Make sure your user/password in the connection string is the correct one.
If a table doesn't exist but exists... it probably doesn't exist for your current user (= that user has not the necessary permissions)
Previous answer is correct, I am just adding another bit.
can you replace your query as following :
SELECT lixo FROM <table owner>.lixeira WHERE lixo IS NOT NULL
This will give more appropriate error of what you are missing.
Its probably a permission (grant select) issue.
Abhi

"The multi-part identifier could not be bound" sql, visual studio

I am just learning c# and sql server. This question has been asked a couple of times but the solutions posted don't seem to help me.
I have a table called "LoginInfo" that has a user's "email" and "pass".
In visual studio i have this method that checks a users login information
private boolean dbQueryLogin(string email, string password)
{
string com = "SELECT pass FROM LoginInfo WHERE email = XXXXX#yahoo.com";
SqlCommand command = new SqlCommand(com, conn);
SqlDataReader reader = command.ExecuteReader();
return reader.GetString(0).Equals(password);
}
This keeps on throwing the error "Additional information: The multi-part identifier "XXXX.edu" could not be bound."
The syntax looks right to me, is there anything i'm missing??
The clue is in the error message:
The multi-part identifier "XXXX.edu" could not be bound.
That strongly suggests that the problem isn't with identifying your table - it's with the bit that ends with "edu", which seems like to be an email address.
The immediate problem is that you've forgotten to quote a value. The deeper problem is that you should be using parameterized SQL anyway, to avoid SQL injection attacks, conversion problems and unreadable code. Given that the value you've given in the same code isn't the same as what's in the error message, I suspect you really have code like:
string sql = "SELECT pass FROM LoginInfo WHERE email = " + email;
Don't do that. Use parameterized SQL instead:
private boolean dbQueryLogin(string email, string password)
{
string sql = "SELECT pass FROM LoginInfo WHERE email = #email";
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(sql))
{
command.Parameters.Add("#email", SqlDbType.NVarChar).Value = email;
using (var reader = command.ExecuteReader())
{
// FIXME: What do you want to do if
// there are no matches?
reader.Read();
return reader.GetString(0) == password;
}
}
}
}
This still isn't good code though:
Don't store plain-text passwords in a database
Handle the case where there are no results
Don't build your own authentication system at all; use an existing one written by people with more experience in securing data

C# MySql.Data.MySqlClient.MySqlException Error for no reason

For the past month I've been getting data with a C# program in tandem with a company's API. Just yesterday all the sudden it would no longer work, even though I haven't changed the code at all. Here's the code:
public string GetMatchCode()
{
//this could be loaded from config file or other source
string connectString = "Server=123.123.1.23;Database=blah_users;Uid=blah_data;Pwd=blahblah;";
string sql = "SELECT MAX(match_id) FROM `data_blah`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
return command.ExecuteScalar().ToString();
}
}
And I get this error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: Access denied for user 'blah_data'#'cpe-86-80-21-54.san.res.rr.com' (using password: YES)
Any idea what could have happened and how to fix it? The only thing I think could've happened is that my support ticket dealing with node.js compatibility was executed wrong by support employees. Thanks!
Your db user's permission has failed. The user may have been removed; the permissions may have been modified. Contact the db owner.
So it looks like you are not authenticating: Either incorrect credentials or server needs a different method. Try disabling "sslmode" like below:
public string GetMatchCode()
{
//this could be loaded from config file or other source
string connectString = "Server=123.123.1.23;Database=blah_users;Uid=blah_data;Pwd=blahblah;sslmode=none;";
string sql = "SELECT MAX(match_id) FROM `data_blah`";
using (var connect = new MySqlConnection(connectString))
using (var command = new MySqlCommand(sql, connect))
{
connect.Open();
return command.ExecuteScalar().ToString();
}
}
That should do it
string sql = "SELECT MAX(match_id) FROM `data_blah`";
Isn't it supposed to be " ' " instead of " ` " surrounding "data_blah"?

Retrieving images using a file path stored in a sql database (nearly there!)

Ok, I think I am close to making a break through on this.
I have the following code that should, theoretically, populate an image using the file path through a sql database
public void Image1_Load(object sender, EventArgs e)
{
////Code to retrieve logo image from tblMemberLogo - Currently does not work!!!
var connectionstring = ConfigurationManager.ConnectionStrings["PDCConnectionString"].ConnectionString;
using (var cn = new SqlConnection("Data Source=STRSQL04;Initial Catalog=PDC;Integrated Security=True"))
using (var cmd = cn.CreateCommand())
{
cn.Open();
cmd.CommandText = "SELECT LogoFilePath FROM tblMemberlogo WHERE MemberID = '123'";
//cmd.Parameters.Add("123", "5");
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
var filepath = reader.GetString(0);
Image1.ImageUrl = filepath;
Label2.Text = filepath;
}
}
}
}
Now, I know I am close as the Label2 brings back the appropriate file path for Member 123. However, Image1 still possesses the dreaded red cross.
The source code for this Image control is simply the following.
Image ID="Image1" runat="server" Height="71px"
Width="400px" onload="Image1_Load"
I will buy whoever helps me get this over the finish one a nice big pint as I am on the verge of having (another) breakdown!!!
Please find below the output html.
img id="Image1" src="file:c:\online%20reporting\SQL%20Solutions\Member%20Logo\123.GIF" style="height:71px;width:400px;border-width:0px;"
Unfortunately, you can't use a "file:" URL as the src of an image. What you need to do is turn that path into a valid HTTP URL.
So if your images are in "c:\online reporting\SQL Solutions", you should add a virtual directory in IIS under your site root that points there, maybe call it "/logos" or something, then you can go:
String fileName = Path.GetFileName(reader.GetString(0));
Image1.ImageUrl = "/logos/" + fileName;
If your web root is already running in, say, "c:\online reporting", it's even easier -- you can skip the virtual directory and just use "/SQL%20Solutions/" as the beginning of the URL.
Depending on the Url you may need to use ResolveClientUrl or Server.MapPath
Image1.ImageUrl = ResolveClientUrl(filepath);
OR
Image1.ImageUrl = Server.MapPath(filepath);
I am not sure how your data is stored but in most cases when assigning images server side you need to make sure its relative to the website.
Do this using :
Image1.ImageUrl = Server.MapPath(filepath);

Categories

Resources