How to read Arabic text from varchar column? - c#

I have sqlite database who store Arabic text in varchar field
I used this code,but when try to read the value question mark is appear instead character
SQLiteConnection con = new SQLiteConnection("Data Source=Quran.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("SELECT Qtxt FROM tblQTxt'", con);
con.Open();
SQLiteDataReader dr = cmd.ExecuteReader();
dr.Read();
textBox1.Text = dr["Qtxt"].ToString();
dr.Close();
con.Close();
I used "DB Browser for SQLite" fro opening database
when try to view field as binary mode and then export as text I will see the true character
how can read this filed truly?

SQLiteConnection con = new SQLiteConnection("Data Source=Quran.sqlite;Version=3;");
SQLiteCommand cmd = new SQLiteCommand("SELECT Qtxt2 FROM tblQTxt where Sore='1' and Aye='1'", con);
SQLiteDataAdapter dAdapter = new SQLiteDataAdapter(cmd);
DataSet dSet = new DataSet();
dAdapter.Fill(dSet);
if (dSet.Tables[0].Rows.Count == 1)
{
Byte[] data = new Byte[0];
data = (Byte[])(dSet.Tables[0].Rows[0]["Qtxt2"]);
MemoryStream ms = new MemoryStream();
ms.Write(data, 0, data.Length);
ms.Position = 0;
StreamReader reader = new StreamReader(ms,Encoding.GetEncoding(1256));
string text = reader.ReadToEnd();
textBox1.Text = text;
}

Related

C# MySqlConnector next query in the same connection

I have the following code:
string myConnection = "server=localhost;database=test;uid=test;password=test";
string query = "SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
try
{
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
MySqlCommand command = new MySqlCommand(query, myConn);
MySqlDataAdapter adapter = new MySqlDataAdapter(command);
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
MySqlDataReader myReader;
myReader = command.ExecuteReader();
while (myReader.Read()) {
orderNumber = myReader.GetString(1);
myReader.Close();
string queryOrder = "SELECT id_order, id_carrier FROM ps_orders WHERE id_order=28329";
MySqlCommand commandOrder = new MySqlCommand(queryOrder, myConn);
MySqlDataReader myReaderOrder;
myReaderOrder = commandOrder.ExecuteReader();
idCarrier = myReaderOrder.GetString(1);
printDocument1.Print();
}
I have a problem because the second query string queryOrder doesn't work. The query is Ok but variable "idCarrier" doesn't accept any value.
I don't believe you can attach another reader to a connection, when one is already open and processing records. You must retrieve all your records first, i.e. ToList() or Dataset, or use a secondary connection for the second reader.
To make your life easier, consider using Dapper or Linq2Db, two awesome micro-ORMs.
Try it like this:
using(var connection = new MySqlConnection("server=localhost;database=test;uid=test;password=test") {
connection.Open();
int orderNumber = 0;
using (var command = connection.CreateCommand()) {
command.CommandText = #"SELECT label_type, label, quantity FROM system_printserver WHERE print=0";
DataTable data = new DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
var reader = command.ExecuteReader();
printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
if(reader.Read()) {
orderNumber = Convert.ToInt32(reader.GetString(1));
}
}
using(var command = connection.CreateCommand()) {
command.CommandText = string.format(#"SELECT id_order, id_carrier FROM ps_orders WHERE id_order={0}",orderNumber);
var reader = command.ExecuteReader();
if(reader.Read()){
printDocument1.Print();
return reader.GetString(1);
}
}
}

How to add an image into SQL Server database and retrieve it as in Gridview in ASP.net, C#

I'm developing an admin panel and a web service but how to add an image data into SQL Server database and retrieve it in admin panel in GridView? Everything adds fine, shows fine except the images. I'm using HTML Input (file) control. No errors just image is not displaying but lblTest shows accordingly.
And how to make my Button can ADD and Refresh so user can see the new data instantly.
Thank you!
Here is my C# code:
protected void Page_Load(object sender, EventArgs e)
{
showSplash();
}
string connStr = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
Int32 fileLength = 0;
protected void ButtonTest_Click(object sender, EventArgs e)
{
HttpPostedFile uploadFile = FileLogo.PostedFile;
fileLength = uploadFile.ContentLength;
if (fileLength == 0)
{
string filePath = Server.MapPath(#"\icon\no-photo-icon.jpg");
string fileName = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
fileLength = (Int32)fs.Length;
Byte[] fileByteArr = new Byte[fileLength];
fs.Read(fileByteArr, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArr);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
lbltest.Text = "added fine with no file";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
else
{
Byte[] fileByteArray = new Byte[fileLength];
Stream streamObject = uploadFile.InputStream;
streamObject.Read(fileByteArray, 0, fileLength);
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("insert into SPLASH (VersionNumber, SplashLabel,LoginID) values (#VersionNumber,#SplashLabel,#LoginID)", conn);
cmd.Parameters.AddWithValue("#VersionNumber", txtVnum.Value);
cmd.Parameters.AddWithValue("#SplashLabel", txtSpLabel.Value);
cmd.Parameters.AddWithValue("#LoginID", txtYourID.Value);
cmd.Parameters.AddWithValue("#ImageData", fileByteArray);
cmd.Parameters.AddWithValue("#ImageContentType", "image/jpg");
cmd.Parameters.AddWithValue("#ImageSize", fileLength);
lbltest.Text = "added fine";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
}
private void showSplash()
{
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("select * from SPLASH", conn);
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(rdr);
GridViewAddSplash.DataSource = dt;
GridViewAddSplash.DataBind();
conn.Close();
conn.Dispose();
cmd.Dispose();
}
My other related question links:
Ajax tabContainer:

How to count total number of rows of an access database table?

string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\Users\yogi\Documents\mydb.mdb";
string cmdstr = "select * from quant_level1";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
con.Open();
OleDbDataReader reader = com.ExecuteReader();
reader.Read();
DataSet data = new DataSet();
int i = data.Tables["quant_level1"].Rows.Count;
Label2.Text = i.ToString();
use
string cmdstr = "SELECT COUNT(*) FROM quant_level1";
With com.ExecuteScalar()
using(OleDbConnection conn = new OleDbConnection(constr))
using(OleDbCommand command = new OleDbCommand(cmdstr, conn))
{
conn.Open();
int count = (int)command.ExecuteScalar();
}
ExecuteScalar returns the first column of the first row in the result set returned by the query, here it give you row count.
you can use OleDbDataReader as you try in your code sample. but need to change the logic bit.
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("select * from quant_level1", con))
{
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(myReader);
int count = dt.Rows.Count;
}
}
Why you fail!
You have created data set but you haven't load data to dataset using your DataReader. So you will get zero row count at the end.
Looks like that you want to fill your DataSet and count the rows later:
DataSet data = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(com);
da.Fill(data);
int i = data.Tables[0].Rows.Count;
Label2.Text = i.ToString();
If you just want to count the rows, you can change the query to SELECT COUNT(*) FROM quant_level1 and get the return value like this:
int i = (int) com.ExecuteScalar();
Label2.Text = i.ToString();
You should do something like this:
Select count(*) from quant_level1
Change the command syntax executescalar to retrieve a single value
CommandText = "SELECT COUNT(*) FROM region";
Int32 count = (int32) ExecuteScalar();
Hope this can enlighten you a bit

Image from SQL Server Table to asp.net image control

SqlCommand cmd = new SqlCommand("select top 1(CMTID),COMMENT,HEADING from FTAB ORDER BY CMTID DESC", conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read() == true)
{
lblHead.Text = sdr["HEADING"].ToString();
lblData.Text = sdr["COMMENT"].ToString();
}
conn.Close();
That is the code for normal data value retrieve from table now I want to get picture from SQL Server that is saved as Binary data that code mention in bottom. So I want to retrieve picture into an Image control of asp.net; please guide me.
if (FileUpload1.HasFile)
{
conn.Close();
String SqlQery;
SqlQery = "select max(CMTID) from FTAB";
SqlCommand cmdid = new SqlCommand(SqlQery, conn);
conn.Open();
MaxID = (int)(cmdid.ExecuteScalar()) + 1;
conn.Close();
byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile myimg = FileUpload1.PostedFile;
myimg.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
SqlCommand cmd = new SqlCommand("insert into FTAB (CMTID, IMAGEDT, COMMENT, DATETM, HEADING) values (#imgid, #image, #comment, #datetm, #heading)", conn);
SqlParameter imgid = new SqlParameter("#imgid",SqlDbType.Int);
imgid.Value = MaxID;
cmd.Parameters.Add(imgid);
SqlParameter uploading = new SqlParameter("#image", SqlDbType.Image);
uploading.Value = img;
cmd.Parameters.Add(uploading);
SqlParameter cmtt = new SqlParameter("#comment", SqlDbType.NVarChar);
cmtt.Value = RadTextBox3.Text;
cmd.Parameters.Add(cmtt);
SqlParameter dttm = new SqlParameter("#datetm", SqlDbType.DateTime);
dttm.Value = DateTime.Now;
cmd.Parameters.Add(dttm);
SqlParameter hhding = new SqlParameter("#heading", SqlDbType.NVarChar);
hhding.Value = RadTextBox8.Text;
cmd.Parameters.Add(hhding);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
lblHead.Text = "Image uploaded";
}
else
{
lblHead.Text = "No file selected";
}
Try this
SqlCommand cmd = new SqlCommand("select IMAGEDT from FTAB", new SqlConnection("your connection string"));
object data = cmd.ExecuteScalar();
byte[] imgBytes = (byte[])data;
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
string filePath = Server.MapPath("temp") + "//" + "img"+DateTime.Now.Ticks.ToString()+".png";
FileStream fs = File.Create(filePath);
fs.Write(imgBytes, 0, imgBytes.Length);
fs.Flush();
fs.Close();
img.ImageUrl = filePath;
But I would say this isn't the best way to do it, you should save your uploaded images as files as in your website and save the path of that file in your database.
yogi's answer is correct in principle, but requires a web server directory "temp" and write access on an IIS directory.
You can also solve the problem using an image handler as explained in another SO question. Database retrieval is done in the same way, but the rendering happens from a stream, rather than a temp file.

Retrieving an image from SQL Server

I wrote this code but faced an exception that said: Parameter Not Valid.
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM tbl";
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
byte[] barrImg = (byte[])dt.Rows[1]["image"];
MemoryStream mstream = new MemoryStream();
mstream.Write(barrImg, 0, barrImg.Length);
mstream.Seek(0, SeekOrigin.Begin);
img.Image = Image.FromStream(mstream);
mstream.Close();
The exception is:
Parameter is not valid.
in the Image.FromStream line of code.
I checked the value that in datatable was assigned to the image field. It was System.Byte[]. I traced the code. Every thing seems to be correct. But it does not work.
I searched around this problem. Another site preferred to set mstream.Position = 0. But that does not work.
I stored my image by this code.If it maybe that I saved this wrong!
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = connstr;
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
string sql = "INSERT INTO tbl (name, family, image) VALUES ('name', 'family', '{0}')";
sql = string.Format(sql, Image.FromFile("test.jpg"));
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
conn.Close();
new code to save the image:
public byte[] ReadFile(string sPath)
{
byte[] data = null;
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
data = br.ReadBytes((int)numBytes);
return data;
}
and :
private void cmdSave_Click(object sender, EventArgs e)
{
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
byte[] imageData = ReadFile("test.jpg");
SqlConnection CN = new SqlConnection(connstr);
string qry = "insert into tbl (name, family, image) VALUES ('name', 'family', '{0}')";
qry = string.Format(qry, imageData);
SqlCommand SqlCom = new SqlCommand(qry, CN);
CN.Open();
SqlCom.ExecuteNonQuery();
CN.Close();
}
Um, that's not going to work.
Your code that "stores" the image, well, doesn't really do what you think it does.
It is putting the value "test.jpg" into the image field. That isn't the binary image data; only the filename.
So, when you go to pull it back out the Image.FromStream(mstream) call is going to blow chunks because the value "test.jpg" is not an image.. ergo: the parameter is not valid
Here is an example of what you need to be doing to actually put the image into the database:
http://www.codeproject.com/Articles/21208/Store-or-Save-images-in-SQL-Server
You close the stream then try to pull an image from the stream, hence the error "cannot access a closed stream."
Try swapping the order of your last two lines:
img.Image = Image.FromStream(mstream);
mstream.Close();
using (MemoryStream mstream = new MemoryStream((byte[])dt.Rows[1]["image"]))
{
img.Image = Image.FromStream(mstream);
}
Would simplify things. I suspect your problem would be you need to call mStream.Flush() after write and before the seek.
To put an image in to a database, one way is.
string connstr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
using(SqlConnection conn = new SqlConnection(connstr))
{
using (SqlCommand comm = new SqlCommand(conn))
{
comm.CommandText = "INSERT INTO tbl (name, family, image) VALUES (#name,#family,#Content)";
comm.Parameters.Add(new SqlParameter("name",DbType.String,"Fred"));
comm.Parameters.Add(new SqlParameter("family",DbType.String,"Flintstone"));
using(FileStream fs = new FileStream("FredWilmaBamBamAndDino.jpg",FileMode.Open,FileAccess.Read))
{
comm.Parameters.Add(new SqlParameter("content",DbType.Image,fs));
}
cmd.ExecuteNonQuery();
}
}
Notice it puts the content of teh file in the database. Since in the case of a jpg that content is most definitely not a string, use a parameterised query. Which youi should be doing anyway, develop a good habit.
You also need to suss out using, your code was leaking resources all over the place.

Categories