asp.net storing images - asp.net

It's me your junior programmer extraodinaire
I'm trying to display an image from my database but when I try to extract the file it only contains 6 bytes of data which causes my program to throw an error. My instructor informed me that the file is too small for an image, leading me to believe that I'm not storing it properly. I would be most gracious if someone could identify any code that might cause this to happen.
this is my function grabbing/storing the file
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim _image As Byte()
_image = FileUpload1.FileBytes
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
Dim dr As SqlDataReader
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
cmd.Connection = conn
cmd.CommandText = "Insert INTO mrg_Image(Image, UserId) VALUES('#image', #id)"
cmd.Parameters.AddWithValue("#image", FileUpload1.FileBytes)
cmd.Parameters.AddWithValue("#id", 4)
conn.Open()
dr = cmd.ExecuteReader
conn.Close()
'FileUpload1.SaveAs()
End Sub
conn.Open()
file_bytes is the variable that contains 6 bytes as oppose to a thousand+ which an image should have
Dim file_bytes As Byte() = cmd.ExecuteScalar()
Dim file_bytes_memory_stream As New System.IO.MemoryStream(file_bytes)
Dim file_bytes_stream As System.IO.Stream = DirectCast(file_bytes_memory_stream, System.IO.Stream)
Dim the_image As New System.Drawing.Bitmap(file_bytes_stream)
context.Response.ContentType = "image/jpg"
the_image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)
conn.Close()
End Sub

Try replacing '#image' with #image.
Also replace ExecuteReader with ExecuteNonQuery.
I wasn't aware of the FileBytes property, I've always done it so...
Dim _image(FileUpload1.PostedFile.InputStream.Length) As Byte
FileUpload1.PostedFile.InputStream.Read(_image, 0, _image.Length)

Try this
cmd.CommandText = "Insert INTO mrg_Image(Image, UserId) VALUES(#image, #id)"
cmd.Parameters.Add("#image", SqlDbType.Image)
cmd.Parameters("#image") = FileUpload1.FileBytes
cmd.Parameters.AddWithValue("#id", 4)
Edit
Removed ";" forgot this was vb
Edit2
Changed [] to (). again forgot my VB

Related

Asp.net multible table access vb.net

and good day..
I have a code of asp.net in vb.net and work fine for one table but i need to add multible table of( master and dr ) to code the data is the sum from the two table but its different. can anyone help me..thanks advance for all
Private Sub getData(ByVal user As String)
Dim dt As New DataTable()
Dim connectionString As String
Dim connection As OleDbConnection
connectionString = ConfigurationManager.ConnectionStrings("Data_For_netConnectionString").ToString
connection = New OleDbConnection(connectionString)
connection.Open()
Dim sqlCmd As New OleDbCommand("SELECT * from master WHERE UserID = #user", connection)
sqlCmd.CommandText = _
"SELECT name, manistry, university, send, card FROM master "
Dim sqlDa As New OleDbDataAdapter(sqlCmd)
sqlCmd.Parameters.AddWithValue("#user", user)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
TextBox1.Text = dt.Rows(0)("manistry").ToString
TextBox2.Text = dt.Rows(0)("university").ToString
TextBox4.Text = dt.Rows(0)("send").ToString
TextBox21.Text = dt.Rows(0)("card").ToString
name.Text = dt.Rows(0)("name").ToString
End If
connection.Close()
End Sub

Can't read data from SQL Server database

I'm having a problem when I'm reading data from a SQL Server database. The main thing is that I want to read the data from the database and display the data in a Label control. But the concern is that it can't read data to it. I will show you the code snippet and any comments/suggestions are gladly considered.
Option Explicit On
Imports System.Data
Imports System.Data.OleDb
Partial Class ViewDetail
Inherits System.Web.UI.Page
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim InstructorID As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
InstructorID = Request.QueryString("Instructor_ID")
Integer.TryParse(lblID.Text, InstructorID)
con = New OleDbConnection("Provider=SQLNCLI11;Data Source=ARIES-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SchoolDB")
con.Open()
cmd = New OleDbCommand("SelectData", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", InstructorID)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
lblID.Text = dr("Instructor_ID").ToString
lblFirstname.Text = dr("FirstName").ToString
lblLastname.Text = dr("LastName").ToString
lblAddress.Text = dr("Address").ToString
lblContact.Text = dr("Contact_Number").ToString
End While
End If
dr.Close()
cmd.Dispose()
con.Close()
End Sub
End Class
This line seems to be totally wrong
Integer.TryParse(lblID.Text, InstructorID)
This lines takes the current value in the lblID.Text at the Page_Load event and tries to set the value of InstructorID. But your code seems to want this value from the QueryString passed that contains the real value.
If you are certain the the QueryString contains a valid integer then remove that line and add
InstructorID = Convert.ToInt32(Request.QueryString("Instructor_ID"))

How to delete data in database using grid view in vb.net

I'm a beginner in vb.net. Currently I'm develop a simple application by using a grid view. however, I'm facing a problem in deleting the data. When I click delete button, it keep adding the blank line. and this blank line is affected my database also. and this blank line also can't be deleted from database manually.
here my code behind
`Imports System.Data.SqlClient
Imports System.Drawing
Imports System.Data
Imports System.Configuration
Imports System.Linq
Partial Class test2
Inherits System.Web.UI.Page
Dim AMS As String = System.Web.Configuration.WebConfigurationManager.ConnectionStrings("AMS").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Me.BindData()
End If
End Sub
Private Sub BindData()
Dim dt As DataTable = New DataTable
Dim strConnString As String = ConfigurationManager.ConnectionStrings("AMS").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Dim strQuery As String = "SELECT * FROM ModuleDetail"
Using cmd As SqlCommand = New SqlCommand(strQuery)
Dim sda As SqlDataAdapter = New SqlDataAdapter
cmd.Connection = con
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Sub
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Dim IsDeleted As Boolean = False
Dim ModuleID As String = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Value.ToString())
Dim ModuleName As Label = CType(GridView1.Rows(e.RowIndex).FindControl("lblModuleName"), Label)
Dim SubModule As Label = CType(GridView1.Rows(e.RowIndex).FindControl("lblSubModule"), Label)
Dim strConnString As String = ConfigurationManager.ConnectionStrings("AMS").ConnectionString
Using con As SqlConnection = New SqlConnection(strConnString)
Using cmd As SqlCommand = New SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = "DELETE FROM ModuleDetail WHERE ModuleID=#ModuleID"
cmd.Parameters.AddWithValue("#ModuleID", ModuleID)
cmd.Connection = con
con.Open()
IsDeleted = cmd.ExecuteNonQuery() > 0
con.Close()
GridView1.DataSource = cmd
GridView1.DataBind()
End Using
End Using
If IsDeleted Then
lblMsg.Text = "'" & SubModule.Text & "' details has been deleted successfully!"
lblMsg.ForeColor = System.Drawing.Color.Green
BindData()
Else
lblMsg.Text = "Error while deleting '" & SubModule.Text & "' details"
lblMsg.ForeColor = System.Drawing.Color.Red
End If
End Sub
`
I have try a few code from others sources but it shows the same logic error which keep adding the blank line. I hope you guys can help me to solve the issue.
Though it might not relevant to your problem context, but I have observed a couple of issues from your code:
1) It seems you are binding grid twice after row delete.
2) Try commenting following lines since you already calling BindData() whithin IsDeleted flag check.
GridView1.DataSource = cmd;
GridView1.DataBind();
3) You are assigning the 'Command' object: cmd to the Grid's datasource which is not correct. Check your BindData(...) method how you need to bind Grid actually.

NullReferenceException - Object reference not set to an instance of an object

I am trying to run this code below. It was working previously, but when I added a second datareader, it stopped. Can anyone tell me what's wrong ?
Protected Sub btnSearchUser_Click(sender As Object, e As EventArgs) Handles btnSearchUser.Click
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim searchComm As String = "SELECT * FROM users WHERE username LIKE #username"
Dim user_id_select As New Integer
Dim searchSQL As New SqlCommand
conn.Open()
searchSQL = New SqlCommand(searchComm, conn)
searchSQL.Parameters.AddWithValue("#username", txtUserSearch.Text)
Dim datareader As SqlDataReader = searchSQL.ExecuteReader()
While datareader.Read
lstUsers.Items.Add(datareader.Item("username"))
End While
datareader.Close()
conn.Close()
Dim conn2 As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True")
Dim selectComm As String = "SELECT user_id FROM users WHERE username=#username_selected"
Dim selectSQL As New SqlCommand
conn2.Open()
selectSQL = New SqlCommand(selectComm, conn2)
selectSQL.Parameters.AddWithValue("#username_selected", lstUsers.SelectedItem.Text.Trim)
Dim datareader2 As SqlDataReader = selectSQL.ExecuteReader()
While datareader2.Read
If datareader2.HasRows Then
user_id_select = datareader2("user_id")
lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text
ElseIf datareader2.HasRows = False Then
lblInvalidUsername.Visible = True
datareader2.Close()
End If
End While
conn2.Close()
End Sub
Hi,
I'm gettin a NullReference exception on lblUserSelected.Text = "Selected: " + lstUsers.SelectedItem.Text whenever I enter a username in txtUserSearch and click search, it was working previously.. I don't know what happened..
Can anyone tell me whats wrong?
I assume you're getting the NullReferenceException on this line:
selectSQL.Parameters.AddWithValue("#username_selected", lstUsers.SelectedItem.Text.Trim)
since you haven't specified the SelectedItem of the recently filled ListBox. To select the first item you could use this code:
While datareader.Read
lstUsers.Items.Add(datareader.Item("username"))
End While
If lstUsers.Items.Count <> 0 Then lstUsers.SelectedIndex = 0
You are also not handling the case that there are no usernames in the database, then the ListBox is empty and has no selected-item.

Copying data from one table to another (along with some other data)

Is possible to transfer data from one table into an empty table along with a other data? Is it possible to do that with a single SQL statement? What I've tried so far produces no errors but the data from the original table is not transferred to the empty table.
I've include my code below and I'd appreciate any advice. I suspect there's a problem with the database connection, but I am still new to programming and I can't see the problem.
Imports System.Data.SqlClient
Public Class uploadSuccess
Inherits System.Web.UI.Page
Dim con As SqlConnection
Dim cmd As SqlCommand
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
con = New SqlConnection("Data Source=127.0.0.1; User Id=user;Password=pass;Initial Catalog=catalog;")
con.Open()
cmd = con.CreateCommand()
cmd.Connection = con
Dim intCount As Int32
Dim getReceipt As Int32
Dim femtocellrow As Int32
Dim noreceipt As Int32
Dim username As String
Dim client As String
Dim comName As String
noreceipt = Session("recNo")
username = Session("username")
comName = Session("compName")
'Response.Write("noreceipt" & noreceipt)
cmd.CommandText = "SELECT COUNT(*) AS RETURNCOUNT FROM dbo.tempTable"
intCount = cmd.ExecuteScalar
' Response.Write("count " & intCount)
cmd.CommandText = "SELECT noDevices FROM dbo.Receipt WHERE receiptNo= #noreceipt"
cmd.Parameters.AddWithValue("#noreceipt", noreceipt)
getReceipt = cmd.ExecuteScalar
'Response.Write("receipt " & getReceipt)
cmd.CommandText = "SELECT COUNT(*) AS RETURNCOUNT FROM dbo.femtocell WHERE receiptNo= #norec"
cmd.Parameters.AddWithValue("#norec", noreceipt)
femtocellrow = cmd.ExecuteScalar
'Response.Write("femrow " & femtocellrow)
cmd.CommandText = "SELECT clientID FROM dbo.Receipt WHERE companyName=#comName"
cmd.Parameters.AddWithValue("#comName", comName)
client = cmd.ExecuteScalar
'Response.Write("client " & client)
con.Close()
Dim rowsAffected As Integer = 0
Dim myConnectionString As String = "Data Source=192.168.18.30; User Id=sa;Password=google;Initial Catalog=femtocell;"
Dim myConnection As New SqlConnection(myConnectionString)
If (femtocellrow < getReceipt) & (intCount < femtocellrow) Then
'Dim myQuery As String = "SELECT ([uploadID],[clientID],[receiptNo],[compName],[state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate],[compName]) INTO dbo.femtocell (username,client,noreceipt,comName,[State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]) FROM dbo.tempTable"
' Dim myQuery As String = "INSERT INTO dbo.femtocell ([uploadID],[clientID],[receiptNo],[compName],[state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate],[compName]) VALUES (SELECT 'username','client','noreceipt','comName',[State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]FROM dbo.tempTable"
Dim myQuery As String = "INSERT INTO dbo.femtocell ([state],[town],[district],[siteAddress],[latitude],[longitude],[type],[serialNo],[man],[model],[pwr],[appNo],[manAntenna],[modelAntenna],[height],[gain],[emission],[bhaul],[strucType],[covType],[cov],[spectBand],[txFreq],[rxFreq],[bw],[regFee],[uspArea],[commDate]) SELECT [State],[Town],[District],[Site_Address],[Latitude],[Longitude],[Equipment_Type],[Equipment_Serial_No],[Equipment_Man],[Equipment_Model],[Equipment_Pwr_Mw],[Equipment_App_No],[Antenna_Man],[Antenna_Model],[Antenna_Height_m],[Antenna_Gain_Db],[antenna_emission],[Bhaul],[Struc_Type],[Cov_Type],[Cov_m],[Spect_Band],[Tx_Freq_MHz],[Rx_Freq_MHz],[Bw_KHz],[Reg_Fee_RM],[USP_area],[Comm_Date]FROM dbo.tempTable"
Dim myCommand As New SqlCommand(myQuery, myConnection)
Try
myConnection.Open()
rowsAffected = myCommand.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex.Message)
Finally
myConnection.Close()
End Try
Else
Dim message As String = "Number of devices submitted is invalid."
Dim sb As New System.Text.StringBuilder()
sb.Append("alert('")
sb.Append(message)
sb.Append("');")
ClientScript.RegisterOnSubmitStatement(Me.GetType(), "alert", sb.ToString())
End If
End Sub
End Class
Maybe one of these will help:
SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE
sqlauthority.com
copy all rows of a table to another table
stackoverflow.com
C# – Bulk copying data into MS SQL Server with DataTables
myadventuresincoding.wordpress.com

Resources