invalid parameter while retrieving blob with c# - c#

i'm trying to retrieve a picture saved in the database in BLOB format
but it gives an Exception that the parameter of MemoryStream is invalid in this Line
pictureBox1.Image = System.Drawing.Image.FromStream(ms);
and this is the full code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
namespace InsertImage2
{
public partial class Form1 : Form
{
MySqlConnection myConn = new MySqlConnection("datasource=localhost;port=****;username=****;password=****;");
MySqlCommand cmd;
MySqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string query = "select * from images_database.images where id = '"+textBox1.Text+"';";
cmd = new MySqlCommand(query, myConn);
da = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
byte[] img = (byte[])dt.Rows[0][1];
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = System.Drawing.Image.FromStream(ms);
da.Dispose();
}
}
}

Related

Invalid Connection String on .Net Teradata connection

I am trying to connect Teradata using .Net with the below code.
But when I execute it, it throws an error stating Invalid connection string
on
TdDataAdapter adapter = new TdDataAdapter(cn.ConnectionString,cmd.CommandText);
Here's the complete code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Teradata.Client.Provider;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "URK";
connectionStringBuilder.Database = "DB";
connectionStringBuilder.UserId = "USERNAME";
connectionStringBuilder.Password = "PASSWORD";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
TdConnection cn = new TdConnection();
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
TdCommand cmd = new TdCommand("EXEC MACRONAME", cn);
TdDataReader reader = cmd.ExecuteReader();
TdDataAdapter adapter = new TdDataAdapter(cn.ConnectionString,cmd.CommandText);
DataSet ds = new DataSet();
adapter.Fill(ds);
myLabel.Text= ds.Tables[0].Rows[0]["event_id"].ToString();
cmd.Dispose();
cn.Close();
}
}
I tried using connectionStringBuilder.ConnectionString instead of the one used above but I still got the same error.
Just swap parameters
TdDataAdapter adapter = new TdDataAdapter(cmd.CommandText, cn.ConnectionString);
according to signature of TdDataAdapter constructor
public TdDataAdapter(
string commandText,
string connectionString
)
See docs

how to add database content to an asp.net page

Hey I'm trying to add database info into my webpage. This is the code I am trying.
using System;
using System.Windows;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
namespace DatabaseAddDemo
{
public partial class Content : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["key"] != null)
{
try
{
SqlConnection sqlConn = new SqlConnection(#"Data Source=officedev1;Initial Catalog=TestDatabase;User ID=sa;Password=Password11;pooling='true';Connect Timeout=3000; Max Pool Size=200;MultipleActiveResultSets='true'");
SqlCommand cmdPreWork = new SqlCommand(#"select * from CKEditor_Table where #ID = #key", sqlConn);
string key = Request.QueryString["keys"].ToString();
contentLiteral.Text = key;
cmdPreWork.Parameters.Add("#Information", SqlDbType.Char).Value = key;
Console.WriteLine(contentLiteral);
SqlDataAdapter daPreWork = new SqlDataAdapter(cmdPreWork);
DataTable dtPreWork = new DataTable();
daPreWork.Fill(dtPreWork);
Grid.DataSource = dtPreWork;
Grid.DataBind();
}
catch (Exception ex)
{
lblError.Text = "Could not open connection";
}
}
}
}
}
Whenever I try to display the information, I get the lblError text, telling me I could not open the connection. I'm not sure what to do. Please help.
You should be able to DEBUG this as stated in the comments. But in your code your select query expects a [Key] parameter and you are passing a [Information] parameter.
Change it as below:
SqlCommand cmdPreWork = new SqlCommand(#"select * from CKEditor_Table
where #ID = #key", sqlConn);
cmdPreWork.Parameters.Add("#key", SqlDbType.Char).Value = key;

Why do i keep getting a blank form C#

I have a login_form and an admin_form. whenever I try to login I keep getting an empty form. why do I keep getting it?
this my login_form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class login_form : Form
{
public login_form()
{
InitializeComponent();
}
private void login_button_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("Select Count(*) from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "' and Role='" + comboBox1.Text + "'", con);
DataTable dt = new System.Data.DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
SqlDataAdapter sda1 = new SqlDataAdapter("Select Role from Table_1 where FullName='" + username_text.Text + "' and Password='" + password_text.Text + "'", con);
DataTable dt1 = new System.Data.DataTable();
sda1.Fill(dt1);
if (dt1.Rows[0][0].ToString() == "Administrator")
{
admin_form ss = new admin_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Committee")
{
committee_form ss = new committee_form();
ss.Show();
}
if (dt1.Rows[0][0].ToString() == "Secretary")
{
secretary_form ss = new secretary_form();
ss.Show();
}
}
}
}
}
and this is my admin_form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace InternationalStudentsSociteySmartSystem
{
public partial class admin_form : Form
{
SqlConnection conn = new SqlConnection("Data Source=TAREK-PC;Initial Catalog=ISSSS_DB;Integrated Security=True");
SqlCommand command;
string imgLoc;
SqlDataReader myReader;
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
}
private void button1_Click(object sender, EventArgs e)
{
welcome_text.Text = "Welcome!";
try
{
string sql = "SELECT Image FROM Table_1 WHERE FullName='" + admin_name_text.Text + "'";
if (conn.State != ConnectionState.Open)
conn.Open();
command = new SqlCommand(sql, conn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
byte[] img = (byte[])(reader[0]);
if (img == null)
admin_picturebox.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
admin_picturebox.Image = Image.FromStream(ms);
}
}
else
{
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show(ex.Message);
}
}
private void admin_form_Load(object sender, EventArgs e)
{
admin_picturebox.SizeMode = PictureBoxSizeMode.StretchImage;
}
private void register_committee_button_Click(object sender, EventArgs e)
{
register_committee_form rcf = new register_committee_form();
rcf.Show();
}
}
}
as you can see I also have to other forms which are committee_form and secretary_form (which they work just fine) but I didn't write their code yet. so I figured the problem is with admin form...
I appreciate the help, thanks.
You are calling the admin_form constructor that doesn't take any parameters. In that constructor the call to InitializeComponent is missing. So your admin_form is totally blank
You should add the call to InitializeComponent also to the parameterless constructor of admin_form.
public admin_form(string username)
{
InitializeComponent();
}
public admin_form()
{
// TODO: Complete member initialization
InitializeComponent();
}
As a side note, not related to your actual problem. Your code that access the database is vulnerable to Sql Injection hacks. And you will have a lot of problems to parse your input data. You should start immediately to use a parameterized query approach instead of string concatenation

Access DB not displaying in DataGridView in C#

This is driving me nuts. I've seen other responses to this type of question but it hasn't helped. I created a simple Access db and want to display the tables in a datagrid. I've created something similar which worked yet when I try it with this, it won't display. How can I check if the connection is actually working? Code being used is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace CAStock
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataTable dTable = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
string sqlStr = "SELECT * FROM Products";
updateDataGrid(sqlStr);
}
private void updateDataGrid(String pSqlStr)
{
string connStr = "Provider = Microsoft.ACE.OLEDB.12.0;" + "Data Source = Stock.accdb";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(pSqlStr,connStr);
dTable.Clear();
dAdapter.Fill(dTable);
dAdapter.Dispose();
dgvStock.DataSource = dTable;
}
}
}

Error in adapter.fill function

I am a beginner programmer.
I wrote the following code that shows an error in "adapter.fill(dt) ??????
this code must do the following steps:
1-connect to my dataset that has two fields :UserID,TrackID (2916 fields) 2-Read the dataset line by line and put the UserId of each recored to a url(instead of ). 3-Search through the webpage 4-if it finds the TrackId (exactly the same) which is related to UserId, add 1 to counter.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Net;
namespace test2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\hidden.accdb";
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from hidden.accdb";
DataTable dt = new DataTable();
//To read data from dataset
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
//Store the UserID
adapter.Fill(dt);
int UserID=0,TrackID=0;
int counter=0;
foreach(DataRow row in dt.Rows)
{
string url = "http://abcd/<userid>?groups=<userid>";
var test = url.Replace("<userid>", Convert.ToString(row["UserID"]));
System.Diagnostics.Process.Start(url);
string client = (new WebClient()).DownloadString("http://abcd/UserID?groups=UserID");
if (client.ToLower() == (Convert.ToString(TrackID).ToLower()))
{
counter++;
}
int ave = counter / 2916;
MessageBox.Show("Average" + counter);
}
conn.Close();
}
}
}
This is invalid:
"Select * from hidden.accdb"
hidden.accdb should be table name that contains the UserID and TrackID columns. not access database file name

Categories