Saving pictures in my Mysql database in VB.NET - mysql

Good day stack overflow,
I am trying to save pictures in my mysql database, i think i will use BLOB correct?
I am planning to update my mysql database that is already hosted online to support uploading and displaying pictures in my project in vb.net,
I know the easiest way to do saving picture in mysql database is by saving the picture in a directory and putting the path only in the database, but how about for online database that is hosted in the internet and does not have a working directory? I mean just the database itself?
How can i optimized the time access for the picture to load?

Protected Sub UpLoadThisFile(ByVal upload As FileUpload)
If UpL1.HasFile Then
Dim fileName As String = Path.GetFileName(UpL1.PostedFile.FileName)
UpL1.PostedFile.SaveAs(Server.MapPath("~/AltImg2/") + fileName)
UpImag.ImageUrl = ("~/AltImg2/") + fileName
T8.Text = ("~/AltImg2/") + fileName
Else
T8.Text = "~/NOPic/noimage.jpg"
End If
End Sub
Protected Sub CheckImag()
If UpL1.HasFile Then
Dim ValidatFileTy As String() = {"bmb", "gif", "png", "jpg", "jpeg"}
Dim Ext As String = System.IO.Path.GetExtension(UpL1.PostedFile.FileName)
Dim isValidFile As Boolean = False
For i As Integer = 0 To ValidatFileTy.Length - 1
If Ext = "." & ValidatFileTy(i) Then
isValidFile = True
End If
Next
If Not isValidFile Then
MsgLbl.Visible = True
MsgLbl.ForeColor = Drawing.Color.Red
MsgLbl.Text = String.Join(",", ValidatFileTy)
Exit Sub
Else
UpLoadThisFile(UpL1)
End If
Else
UpLoadThisFile(UpL1)
End If
End Sub
and in button
Protected Sub BTAddNew_Click(sender As Object, e As EventArgs) Handles BTAddNew.Click
Try
CheckImag()
Insert()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
but how about for online database that is hosted in the internet and does not have a working directory?
yes you must use ~ ("~/AltImg2/").

Related

How can I get the usernames in the account?

I'm making a VB.Net application which connects to a MySql database.
My application has many Accounts, and each account has several Users. I want to show this information, but the application just shows the first user of each account.
This is the code:
Public Function id(Label2 As String) As Double
Using connection = Getconnection()
connection.Open()
Using commandid = New MySqlCommand
commandid.Connection = connection
commandid.CommandText = "SELECT *FROM player.player
Where player.account_id=" & testString & V
Dim read = commandid.ExecuteReader
If read.HasRows Then
While read.Read
ActivateUser.namecharacter = read.GetString(2)
ActivateUser.job = read.GetString(3)
End While
read.Dispose()
Return True
Else
MessageBox.Show(" no ")
Return False
End If
connection.Close()
connection.Dispose()
End Using
End Using
End Function
How can I fix this to show all the users in the account?
Just create you connection in the method where you use it. Get rid of GetConnection just use a class level variable for the connection string.
Don't open a connection until directly before you use it.
You can include the command in the same using block by adding a comma at the end of the first line. Commands also need to be disposed. The command constructor can take the CommandText and the Connection as parameters.
What datatype is account_id in the database? I am going to guess it is a string type. Is V a variable or is it meant to be the string "V"? I am going to guess a hardcoded string. Where does testString come from? I am going to guess Label2 (terrible non-descriptive name) is teststring.
Never concatenate strings for you sql. Always use parameters.
A reader also needs to be closed and disposed so use Using blocks. The whole idea of accessing the database is to get in and out as quickly as possible. Don't set properties of ActivateUser and never show a message box. The user could have gone to lunch and your connection is left flapping in the breeze.
You have the datatype of your function as Double but your return statements have Booleans. Won't work.
It is not necessary to close and dispose the connection. The End Using does that.
Private ConStr As String = "Your connection string"
Public Function id(Label2 As String) As DataTable
Dim dt As New DataTable
Using connection As New MySqlConnection(ConStr),
commandid As New MySqlCommand("SELECT *FROM player Where account_id= #TestString;", connection)
commandid.Parameters.Add("#TestString", MySqlDbType.VarChar).Value = Label2 & "V"
connection.Open()
Using reader = commandid.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Then back in the User Interface code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt = id(Label2.Text)
If dt.Rows.Count > 0 Then
ActivateUser.namecharacter = dt(0)(2).ToString
ActivateUser.job = dt(0)(3).ToString
Else
MessageBox.Show(" no ")
End If
End Sub
This makes a good separation of from your database code.

Uploading images to database using the BLOB throwing exception

I've been attempting to adapt part of this procedure that I found online (can't remember where now!). I've been trying to use this to upload images to a MYSQL database using BLOB data type.
Public Sub SQLUpload()
Dim connection As New MySqlConnection(ConnectionImage)
Dim command As New MySqlCommand("INSERT INTO Images (File, FileName, FileSize) VALUES (#Picture, 'Name1', 'Size1')", connection)
'Create an Image object.'
Using picture As Image = Image.FromFile("C:\DIR\Pictures\Person.jpg")
'Create an empty stream in memory.'
Using stream As New IO.MemoryStream
'Fill the stream with the binary data from the Image.'
picture.Save(Stream, Imaging.ImageFormat.Jpeg)
'Get an array of Bytes from the stream and assign to the parameter.'
command.Parameters.AddWithValue("#Picture", SqlDbType.VarBinary).Value = stream.GetBuffer()
End Using
End Using
connection.Open()
Try
command.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
connection.Close()
End Sub
Above is the current sub routine. Whenever this is executed, the routine operates fine until it gets to:
Command.ExecuteNonQuery()
It throws the error:
Unable to cast object of type System.Byte[] to type System.IConvertible
I'm pretty sure this happens because of the fact that the bytes from the image are returned as an array however the memory that they are saved to does not support an array? This was just gathered from reading I've done elsewhere online.
However, as this is not all my code I am frankly not sure what the problem is. Can anyone see what is wrong with it?
Many Thanks
Where you have
SqlDbType.VarBinary ' <-- this is Sql Server DB type
use
MySqlDbType.Blob
Like this
Dim file() As Byte = ' set your file
Dim p As MySqlParameter = new MySqlParameter("#Picture", MySqlDbType.Blob, file.Length)
p.Value = file
command.Parameters.Add(p)
As it mentioned by others, you don't need to "Save" your file - just read it into byte array. My code would look something like below:
Public Sub SQLUpload()
Try
Using conn As New MySqlConnection(connString)
' Parametarize entire sql string
Dim sql As String =
"INSERT INTO Images (File, FileName, FileSize) VALUES (#Picture, #name, #size)"
Using cmd As New MySqlCommand(sql, conn)
Dim fileName As String = "C:\DIR\Pictures\Person.jpg"
Dim file() As Byte = File.ReadAllBytes(fileName)
cmd.Parameters.AddWithValue("#Picture", MySqlDbType.Blob).Value = file
cmd.Parameters.AddWithValue("#file", MySqlDbType.VarChar).Value = fileName
cmd.Parameters.AddWithValue("#size", MySqlDbType.Int32).Value = file.Length
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Success")
Catch ex As Exception
MessageBox.Show(ex.ToString())
End Try
End Sub

Why do some forms suddenly lose functionality?

once in a while in this application I have been working on a form will suddenly lose all of it's functionality with the database and I am forced to erase all of the work I have done on it and completely re-build it.
For instance adding a new entry to the database; I can hit Add New which calls bindingsource.addnew() enter all of the required information into the text boxes, hit save then when I close and re-open the form nothing is displayed in the datagrid. If I go directly to the table in the SQL Database nothing has been added here either?
It seems to escalate suddenly, when I edit an entry in a table then save it it does not update. After that I cannot add rows to it but it will let me delete rows and save that?
Tablename.bindingsource.addnew()
Tablename.bindingsource.endedit()
Tablename.tableadapter.update(datasetname.tablename)
This is what I have used for adding rows and saving new entries plus edits to the data source for some time now. Is there something I need to be watching out for otherwise?
Private Sub createnew()
'' CREATE AND SAVE NEW ENTRY
CalibratedEquipmentBindingSource.AddNew()
dateaddedlbl.Text = datelbl.Text
CalibratedEquipmentBindingSource.EndEdit()
Calibrated_EquipmentTableAdapter.Update(MacroQualityDataSet.Calibrated_Equipment)
End Sub
Private Sub savebtn_Click(sender As Object, e As EventArgs) Handles savebtn.Click
Try
Dim accountname As String = "macroqc"
Dim acocuntkey As String = My.Settings.Storagekey1
Dim creds As StorageCredentials = New StorageCredentials(accountname, acocuntkey)
Dim account As CloudStorageAccount = New CloudStorageAccount(creds, useHttps:=True)
Dim client = account.CreateCloudBlobClient()
Dim container As CloudBlobContainer = client.GetContainerReference(My.Settings.smallequipmentcertscontainername)
container.CreateIfNotExists()
Dim blob As CloudBlockBlob = container.GetBlockBlobReference(My.Settings.ticketsource)
Using FileStream = System.IO.File.OpenRead(My.Settings.ticketsource)
blob.UploadFromStream(FileStream)
filenamelbl.Text = My.Settings.ticketsource
'' GET HTTPS: PATH OF BLOB
''blob.Uri.AbsoluteUri & blob.Uri.AbsolutePath
End Using
Catch ex As Exception
MessageBox.Show("Sorry an error has occured while uploading your file: " & Environment.NewLine & ex.ToString, "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
If datelbl.Text.Length > 3 Then
dateeditedlbl.Text = datelbl.Text
End If
CalibratedEquipmentBindingSource.EndEdit()
Calibrated_EquipmentTableAdapter.Update(MacroQualityDataSet.Calibrated_Equipment)
gridcolors()
MsgBox("Save Complete!")
End Sub
End Class

how to backup my sql database in vb.net

i want the user of my vb application to be able to backup and restore the database (MySQL) onto a storage medium. my problem is that i dont want to specify 'c:\ in the code because i want the application to be able to locate the dumb file whether it is created on drive c or not. below is the code i used but when i installed it on another machine, it had its windows and program files on D:. it turns out that i have to check the drive letter of every machine, change it in the code before i publish the application to allow backup which i dont want to do that. i want it do be universal. thus whether the dump file is on driver C, G or whatever. any help. below is the code i used.
Dim cmd As String
Private Sub cmdBackup_Click()
Screen.MousePointer = vbHourglass
DoEvents
cmd = Chr(34) & "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqldump" & Chr(34) & " -uroot -psecretpswd --routines --comments db_name > c:\MyBackup.sql"
Call execCommand(cmd)
Screen.MousePointer = vbDefault
MsgBox "done"
End Sub
There is a complied DLL called MySqlBackup.NET. Actually it is an alternative to MySqlDump.
Features
Export/Import Table's Structures & Rows
Export/Import Stored Procedures, Functions, Triggers, Events, Views
Custom Tables and Rows Export.
Able to apply encryption to the process.
Export BLOB and save as files.
Gather SQL Syntax errors during Import process.
Export/Import will report progress. Enable the usage of progress bar.
Able to execute in Synchronous or Asynchronous mode.
Export/Import To/From Zip File.
For more info, see the link below,
MySqlBackup.NET - MySQL Backup Solution for C#, VB.NET, ASP.NET
Edited: Code Examples Added
Backup a MySql Database
Dim con As String = "server=localhost;user=root;pwd=1234;database=test;"
Dim file As String = "C:\backup.sql"
Dim mb As New MySqlBackup(con)
mb.ExportInfo.FileName = file
mb.Export()
Restore a MySql Database
Dim con As String = "server=localhost;user=root;pwd=1234;database=test;"
Dim file As String = "C:\backup.sql"
Dim mb As New MySqlBackup(con)
mb.ImportInfo.FileName = file
mb.Import()
Usually this commands are built using parameters external to the application, not hard coding path to MySqlDump, Database Name and path to destination folder.
Your code should be changed to something like this
Private Sub cmdBackup_Click()
Screen.MousePointer = vbHourglass
DoEvents
Dim mySqlDumpCmd = ConfigurationManager.AppSettings("PathToMySqlDump")
Dim dbName = ConfigurationManager.AppSettings("DatabaseToBackup")
Dim destPath = ConfigurationManager.AppSettings("DestinationPath")
cmd = Chr(34) & mySqlDumpCmd & Chr(34) & " -uroot -psecretpswd --routines --comments " +
dbName & " > " & destPath
Call execCommand(cmd)
Screen.MousePointer = vbDefault
MsgBox "done"
End Sub
and your application.config file contains these values
<?xml version="1.0"?>
<configuration>
<configSections>
.......
<appSettings>
<add key="PathToMySqlDump" value="C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqldump.exe"/>
<add key="DatabaseToBackup" value="db_name"/>
<add key="DestinationPath" value="C:\MyBackup.sql"/>
</appSettings>
.......
In this way you read the key information from the config file of your application. If the need arises you can easily change the information used by the command without touching anything in your application
Use this code. It works for me.
I had such a problem and then found this article
"http://www.experts-exchange.com/Programming/Languages/.NET/Q_27155602.html"
Example was in C#. I manually converted it into vb.net and add converting into 'utf8'.
Imports System.Text
Public Class Form1
Dim OutputStream As System.IO.StreamWriter
Sub OnDataReceived1(ByVal Sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs)
If e.Data IsNot Nothing Then
Dim text As String = e.Data
Dim bytes As Byte() = Encoding.Default.GetBytes(text)
text = Encoding.UTF8.GetString(bytes)
OutputStream.WriteLine(text)
End If
End Sub
Sub CreateBackup()
Dim mysqldumpPath As String = "d:\mysqldump.exe"
Dim host As String = "localhost"
Dim user As String = "root"
Dim pswd As String = "Yourpwd"
Dim dbnm As String = "BaseName"
Dim cmd As String = String.Format("-h{0} -u{1} -p{2} {3}", host, user, pswd, dbnm)
Dim filePath As String = "d:\backup\fieName.sql"
OutputStream = New System.IO.StreamWriter(filePath, False, System.Text.Encoding.UTF8)
Dim startInfo As System.Diagnostics.ProcessStartInfo = New System.Diagnostics.ProcessStartInfo()
startInfo.FileName = mysqldumpPath
startInfo.Arguments = cmd
startInfo.RedirectStandardError = True
startInfo.RedirectStandardInput = False
startInfo.RedirectStandardOutput = True
startInfo.UseShellExecute = False
startInfo.CreateNoWindow = True
startInfo.ErrorDialog = False
Dim proc As System.Diagnostics.Process = New System.Diagnostics.Process()
proc.StartInfo = startInfo
AddHandler proc.OutputDataReceived, AddressOf OnDataReceived1
proc.Start()
proc.BeginOutputReadLine()
proc.WaitForExit()
OutputStream.Flush()
OutputStream.Close()
proc.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
CreateBackup()
End Sub
End Class

access vba get cyrillic text from ini file into database

2012/08/31 : Updated my Post
searched all the web for it, found pieces but nothing really helped so i turn to you.
Information about environment:
Programming language is VBA / Access 2003
Data will be read from existing ".ini" File
Data should be inserted into Access Database
Now to my Problem:
I've got a ini file with information inside an ini file. The file looks something like this:
[product_details]
product_description=my product description
product_name=my product
product_price=11.0
product_sku=myproduct2012
these information are saved into "products.ini", when open in notepad or notepad++ it will be displayed correct and can be inserted into my access database and i can display these information in my form
but now someone wants to have something like this:
[product_details]
product_description=мое описание продукта
product_name=мой продукт
product_price=11.0
product_sku=произведение2012
when loading these information via GetINIValue the Value will be saved into Database as unreadable text.
edit: also in Notepad / Notepad++ it is displayed correct, so the cyrillic chars are transferred correct into the ini-file
I really tried many things (using UNICODE Version of GetINIValue, get Code of Char etc., check if Cyrillic text) nothing helped.
What it should do:
I need help to get the Value from this ini entry no matter what language (in this case, English, German, french, Russian are just enough)
Hope someone could help me.
Edit: I've tried Remou's Testing with this Peace of Code open it up by following:
Dim SQL As String
Dim strValue As String
strValue = GetValueOf("product_details","product_description","C:\cyrillic.txt")
SQL = "UPDATE [products] SET [product_description]='" & strValue & "' WHERE [product_id]=23;"
CurrentDb.Execute SQL,dbseechanges
Heres the Code of my Function to read out the Specific Line i need:
Public Function GetValueOf(ByVal Section As String, ByVal Entry As String, ByVal File As String)
Dim fs As New FileSystemObject
Dim ts As TextStream
Dim temp As String
Dim response As String
Dim intresponses As String
Dim SectionFoundBegin As Boolean
Dim SectionFoundEnd As Boolean
Dim DoNext As Boolean
Dim Parse() As String
Dim Finished As Boolean
SectionFoundBegin = False
SectionFoundEnd = False
Set ts = fs.OpenTextFile(File, ForReading, , TristateTrue)
response = ""
intresponses = 1
Finished = False
Do
DoNext = False
temp = ts.ReadLine
If (Not Finished) Then
If (temp = "[" & Section & "]") And Not DoNext Then
SectionFoundBegin = True
DoNext = True
End If
If ((InStr(1, temp, "[") > 0) And (SectionFoundBegin)) And Not DoNext Then
SectionFoundEnd = True
DoNext = True
End If
If (SectionFoundBegin And Not SectionFoundEnd) And Not DoNext Then
If (InStr(1, temp, "=") > 0) Then
Parse = Split(temp, "=")
If (Parse(0) = Entry) Then
While (intresponses <= UBound(Parse))
response = response + Parse(intresponses)
intresponses = intresponses + 1
Wend
DoNext = True
Else
DoNext = True
End If
Else
DoNext = True
End If
End If
End If
Loop Until ts.AtEndOfStream
GetValueOf = response
End Function
What i need:
Something like:
"UPDATE [products] SET [product_description]='мое описание продукта' WHERE [product_id]=23;"
What i get:
"UPDATE [products] SET [product_description]='??? ???????? ????????' WHERE [product_id]=23;"
UPDATE:
Well now i really your help:
I've inserted the following Code:
Public Function GetUnicodeValueOf(ByVal Section As String, ByVal Entry As String, ByVal File As String)
Dim fs As Object
Dim ts As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Dim temp As String
Dim strResponse As String
Dim intResponses As Integer
Dim SectionFoundBegin As Boolean
Dim SectionFoundEnd As Boolean
Dim DoNext As Boolean
Dim Parse() As String
Dim Finished As Boolean
On Error GoTo Error_GetUnicodeValueOf
SectionFoundBegin = False
SectionFoundEnd = False
Set ts = fs.OpenTextFile(File, ForReading, , TristateTrue)
strResponse = ""
intResponses = 1
Finished = False
Do
DoNext = False
temp = ts.ReadLine
If (Not Finished) Then
If (temp = "[" & Section & "]") And Not DoNext Then
SectionFoundBegin = True
DoNext = True
End If
If ((InStr(1, temp, "[") > 0) And (SectionFoundBegin)) And Not DoNext Then
SectionFoundEnd = True
DoNext = True
End If
If (SectionFoundBegin And Not SectionFoundEnd) And Not DoNext Then
If (InStr(1, temp, "=") > 0) Then
Parse = Split(temp, "=")
If (Parse(0) = Entry) Then
While (intResponses <= UBound(Parse))
strResponse = strResponse + Parse(intResponses)
intResponses = intResponses + 1
Finished = True
Wend
DoNext = True
Else
DoNext = True
End If
Else
DoNext = True
End If
End If
End If
Loop Until ts.AtEndOfStream
Exit_GetUnicodeValueOf:
GetUnicodeValueOf = strResponse
Exit Function
Error_GetUnicodeValueOf:
ActionLogging "Fehler beim Parsen der Datei '" & File & "'"
Resume Exit_GetUnicodeValueOf
End Function
by using this file (saved as UTF-8 without BOM) on my Harddisc:
[product_details]
manufacturer_name=
product_id=50
sku=BU-01722
set=4
type=simple
type_id=simple
color=11
ean=
name=Колесникова
description=[LANGTEXT] Колесникова Е.В Я считаю до двадцати [Рабочая тетрадь] 6-7л
short_description=[KURZTEXT] Колесникова Е.В
old_id=
weight=1.0000
news_from_date=
news_to_date=
status=1
url_key=kolesnikova
url_path=kolesnikova.html
visibility=4
gift_message_available=2
required_options=0
has_options=0
image_label=
small_image_label=
thumbnail_label=
created_at=2012-06-25 07:58:29
updated_at=2012-07-27 09:06:24
price=2.0000
special_price=
special_from_date=
special_to_date=
cost=
tax_class_id=2
minimal_price=
enable_googlecheckout=1
meta_title=
meta_keyword=
meta_description=
is_recurring=0
recurring_profile=
custom_design=
custom_design_from=
custom_design_to=
custom_layout_update=
page_layout=
options_container=container2
and i need to have:
[LANGTEXT] Колесникова Е.В Я считаю до двадцати [Рабочая тетрадь] 6-7л
from INI-Key: description
into my access database.
First it works as it should but now when i'm loading a file that is saved with "TriStateTrue"
everything ends up in : ?????????????????????????????????????????????
in one line.
With TriStateMixed, everything is parsed well except of the cyrillic text which comes like
КолеÑникова Е.Ð’ Я Ñчитаю до двадцати [Ð Ð°Ð±Ð¾Ñ‡Ð°Ñ Ñ‚ÐµÑ‚Ñ€Ð°Ð´ÑŒ] 6-7л
i searched the sourcecode and didn't found the error.
FILE is UTF-8 without BOM (coming from selfwritten Web API for Magento)
Using Access 2003
Need to get Cyrillic Text into my Database where also German / English Texts could be inside the File
Long time ago, i asked this Question and finally got the answer, but because of the lack of time i didn't managed to "Answer myself" here and for other who might have these problems.
First of all, about the Read-Problem:
The Edit from my Question with TryStateTrue was the Right answer, this was the correct line which was needed to load
But now there's the Catch:
The Rules in VBA(6 or lower) are simple:
What will be saved in an String will be stored as ASCII Value. So every Char which is not an ASCII Code will be thrown away and saved as "?"
How did i managed to save those Data?
I Managed to save those Data by using an selfwritten Tool in C# (.NET) which can Handle UTF-8 Strings and can Connect to the Database.
Save Section + Key in List or set as Executable Parameters and where you will "UPDATE" the Value
e.g.:
[product_details]\name;productsTableName;productsNameField;IdentKeyField;IdentKeyValue
open Executable with Arguments or without and load the List
Connect to the desired Access-Database
Read the Section\Key-Value and Send to the Database directly by UPDATE-STATEMENT
e.g:
"UPDATE [productsTableName] SET [productsNameField]='" + ValueFromSectionKey + "' WHERE [IdentKeyField]=IdentKeyValue
Disconnect Database
Close Program
The Result:
a little bit slower at first because writing down what Huge List of Informations
also Writing down everything inside the Database, also with Errors (?????? instead of считаю) secures that if your file is ASCII-"readable" you didn't forget anything
beautiful UTF-8-Encoded and Readable Text inside an Access 2003 Database
The Pros about this Method
outsourced and expendable Tool, when written correctly it can be used for other projects too
understanable Code in Access (you write down informations, and after everything was listed you open up a Program which process these)
very fast when optimized (read the Length and split the list into multiple workers which update the database simultanously)
The Cons about this Method
outsourced
no possibility to save directly into a variable inside VBA(6 or lower)
external tool could be blocked by firewall
before "updating" Database there is unreadable Text inside the Database
more Update-Calls on Database as directly
user-typos inside list or Text containing the delimiter may let the UPDATE statement fail.
Hope i could help.