Why do some forms suddenly lose functionality? - mysql

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

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.

DIsplay real time SQL data on web form

I am working on a small project but currently stuck in the process and your help would be much appreciated.
I am trying to display data from one of my SQL tables onto web form (asp), which will effectively be updating as long as data is being entered into the table.
I have managed to get it to work by using the META Tag which refreshes the page every 2 seconds, but I know this is not an ideal way of doing it. It was advised to me to update the web form only from server to client when there is a new inserted value, however I do not know how to approach this.
Please see below to my current code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Label1.Text = "Cache Refresh:" & _
Date.Now.ToLongTimeString
SqlDependency.Start(GetConnectionSTring())
Using connection As New SqlConnection(GetConnectionSTring())
Using Command As New SqlCommand(GetSQL(), connection)
Dim Dependency As New SqlCacheDependency(Command)
Dim NumberOfMinutes As Integer = 3
Dim Expires As Date = _
DateTime.Now.AddMinutes(NumberOfMinutes)
Response.Cache.SetExpires(Expires)
Response.Cache.SetCacheability(HttpCacheability.Public)
Response.Cache.SetValidUntilExpires(True)
Response.AddCacheDependency(Dependency)
connection.Open()
GridView1.DataSource = Command.ExecuteReader()
GridView1.DataBind()
End Using
End Using
End Sub
Private Function GetConnectionSTring() As String
Return "Data Source=xxxxxxxxx; Initial Catalog=Test; User ID=xxx; Password= xxx;"
End Function
Private Function GetSQL() As String
Return "SELECT ProductCode, ProductName, Cost FROM dbo.OrderTempTable"
End Function
Thank you for your input.
I think you have to check the DB every certain time.
THIS is for PHP but the idea is the same.
HERE another example.

Saving pictures in my Mysql database in VB.NET

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/").

How do you restrict what kind of data can be input into a Textbox for Visual Basic?

I have created a simple Windows Forms Application through Visual Studio 2013, with two text boxes and a button, which I linked to a database in MySql through MySql connector. What it does is after I input a product id and status number for a product that is found in table A, clicking the button would transfer certain columns for that product's row from table A to table B, and then the original row in table A after the data is transferred would be deleted. This is done by calling a stored procedure from that MySql database that uses the values inputted in the text boxes as parameters. Here's the code for the app below so far.
**
Imports MySql.Data.MySqlClient
Imports test_mysql_connection
Public Class Form1
Dim cmd As New MySqlCommand
Dim connection As New MySqlConnection("Database=****;" & _
"Data Source=****;" & _
"User Id=****;Password=****")
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connection.Open()
cmd.Connection = connection
cmd.CommandText = "StoredProcedureC"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#p_product_id", TextBox1.Text)
cmd.Parameters("#p_product_id").Direction = ParameterDirection.Input
cmd.Parameters.AddWithValue("#p_mission_status", TextBox2.Text)
cmd.Parameters("#p_mission_status").Direction = ParameterDirection.Input
cmd.ExecuteNonQuery()
MessageBox.Show("successfully relocated!")
TextBox1.Clear()
TextBox2.Clear()
connection.Close()
End Sub
End Class
**
As the app currently stands though, even though it successfully performs the task I want it to do, I could literally input anything in those boxes, even if they have nothing to do with anything found in table A, and I would still get the message "successfully relocated!" even if nothing from table A is being transferred to table B. I especially don't want to be able to enter the product id and mission number of something from table A that has already been transferred to B and deleted from A. So I'm wondering about how I can restrict what I can input into these text boxes, and perhaps add a few error messages if a product id and mission status that is inputted isn't found on table A. Thanks for any feedback beforehand!
The simplest way is indicated below. Alternatively you could handle the textbox.Validating event and cancel anything that isn't numeric.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
connection.Open()
if not IsNumeric(TextBox1.Text) then Msgbox("Must be a number") : return
cmd.Connection = connection
cmd.CommandText = "StoredProcedureC"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#p_product_id", TextBox1.Text)
cmd.Parameters("#p_product_id").Direction = ParameterDirection.Input
cmd.Parameters.AddWithValue("#p_mission_status", TextBox2.Text)
cmd.Parameters("#p_mission_status").Direction = ParameterDirection.Input
dim rows = cmd.ExecuteNonQuery()
if rows <> 0 then
MessageBox.Show("successfully relocated!")
else
MessageBox.Show("no matching rows.")
end if
TextBox1.Clear()
TextBox2.Clear()
connection.Close()
End Sub

How do I loop Through Each Records in SQL server with Time Gap

I am making a CMS portal for my company which will fetch records from SQL server using ASP.NET:
My problem is that when I fetch values it only shows the last one. But my need is that it should display one by one values with say 5-10 seconds gap in between here is my code:
Imports System
Imports System.Data.Sql
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Dim connectionString As String = "Data Source=soemserv;Initial Catalog=data;User Id=master; Password=hushotn;"
Dim conn As New SqlConnection(connectionString)
Public Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
conn.Open()
Dim comm As New SqlCommand("select Queue,[Timing(IST)],[Status at],TAT,[Staffing at] from DTD_LCD_Queue_Status", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
While reader.Read()
lblQueueName.Text = reader("Queue").ToString.Trim
lblTimingIST.Text = reader("Timing(IST)").ToString.Trim
lblStatusAt.Text = reader("Status at").ToString.Trim
lblTAT.Text = reader("TAT").ToString.Trim
lblStaffingAt.Text = reader("Staffing at").ToString.Trim
End While
End Sub
End Class
How do I loop though each record I tried Do and Loop but its not working...
Thanks in advance!
EDIT
One Step Ahead with no LUCK!!!!
I have written this code but still getting the last row only
For I As Integer = 0 To 15
lblTemp.Text = I.ToString
Dim comm As New SqlCommand("select Queue,[Timing(IST)],[Status at],TAT,[Staffing at] from DTD_LCD_Queue_Status where SrNo='" + lblTemp.Text + "';", conn)
Dim reader As SqlDataReader = comm.ExecuteReader
While reader.Read()
lblQueueName.Text = reader("Queue").ToString.Trim
lblTimingIST.Text = reader("Timing(IST)").ToString.Trim
lblStatusAt.Text = reader("Status at").ToString.Trim
lblTAT.Text = reader("TAT").ToString.Trim
lblStaffingAt.Text = reader("Staffing at").ToString.Trim
Thread.Sleep(2000)
End While
Next
Note I have dynamically given rows i.e 0 to 15
Please guide me!!
Only the last values are printed because : you are fetching a group of rows(data) through the readr and in first iteration of the while loop the first rows(data) are copied to the controls then for the second iteration the contents in the controls are over written with the second row. This will happens in each iteration hence only the last data are displayed.
- This can be avoided by using
Group of controls which are dynamically created(but not practical and good)
using DataGridView(grid) to display the items How to do this
**The method you ware suggested (using Timer) is also possible but it is not a good programming practice only the last values ware displayed all the others flashed for a duration of 5-10 seconds **