I am a total beginner at VB.NET so you may need to bear with me but I need to edit this code behind so that a null value is passed to my database for the 'imageurl' field. The front end is a web form where a user can enter details of a book, with the option of uploading a book cover.
I want to change my code so that if the file upload dialog does not fulfil hasFile, the GUID string generated in the database will be a NULL value (this is so I can have a 'no image available' image using the NullImageUrl property in ASP.)
This is what I've tried to implement so far, but intellisense is telling me that "Value of type String cannot be converted to 'System.GUID'.
Code Behind:
Imports System.Data.OleDb
Partial Public Class addBook
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btn_submission_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_submission.Click
Dim noFile As String = Nothing
Dim myGUID = Guid.NewGuid()
Dim newFileName As String = myGUID.ToString() & ".jpg"
Dim fileLocationOnServerHardDisk = Request.MapPath("img/thumb") & "/" & newFileName
If fu_picture.HasFile Then
fu_picture.SaveAs(fileLocationOnServerHardDisk)
Else
myGUID = noFile
End If
Dim oleDbConn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim SqlString As String = "Insert into booklist(Title,Author,PublicationDate,Pages,Publisher,Blurb,imgurl,AverageRating)
Values (#f1,#f2,#f3,#f4,#f5,#f6,#f7,#f8)"
Dim cmd As OleDbCommand = New OleDbCommand(SqlString, oleDbConn)
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#f1", tb_booktitle.Text)
cmd.Parameters.AddWithValue("#f2", tb_bookauthor.Text)
cmd.Parameters.AddWithValue("#f3", tb_bookpubyear.Text)
cmd.Parameters.AddWithValue("#f4", tb_bookpages.Text)
cmd.Parameters.AddWithValue("#f5", tb_publisher.Text)
cmd.Parameters.AddWithValue("#f6", tb_blurb.Text)
cmd.Parameters.AddWithValue("#f7", "img/thumb/" & newFileName)
cmd.Parameters.AddWithValue("#f8", rbl_Stars.SelectedValue)
oleDbConn.Open()
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep("2000")
Response.Redirect("~/addedrecord.aspx")
End Sub
Protected Sub rbl_Stars_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles rbl_Stars.SelectedIndexChanged
End Sub
End Class
Please tell me if I'm completely wrong in my line of thinking!
EDIT: At this present moment, even if a file is not uploaded, a guid string + jpg suffix are generated in the database table even if the image itself doesn't exist
You should pass DBNull.Value to your db if you fail the requirement
cmd.Parameters.AddWithValue("#f7", _
if(fu_picture.HasFile, "img/thumb/" & newFileName, DbNull.Value)
The ternary operator allows you to test the flag HasFile just when you create the parameter.
If it is false you set the parameter value to DBNull.Value. If HasFile is true you can build the correct path to your imagefile. Of course this removes the necessity to assign Nothing to myGuid in the code before.
Related
I have file upload and upload link button and submit button .. so when i select file and click on upload then file name display in label and when i again click on browse file and select file and click on upload then file name again save in label so means multiple file name display in label i.e.
abc.docx
def.docx
.. and so on ..
now i try to save these files in database with different record means if these files save in database table then look like this
ID DocumentName DocumentPath
1 abc.docx /downloads/abc.docx
2 def.docx /files/def.docx
for this i try this
sp
alter procedure spupload_file
#DocumentName varchar(100),
#Doctype tinyint
as
insert into DocDownloads (DocumentID,DocumentName,DocType)
select (select max(DocumentID) from DocDownloads )+ROW_NUMBER() over(order by #DocumentName),#DocumentName,7
code
Protected Sub LinkButton1_Click(sender As Object, e As EventArgs) Handles LinkButton1.Click
uploadmultiple_file(fileUpEx.FileName)
End Sub
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
'Label4.Text = ("<b>File: </b>" + uploadedfile.FileName)
Label4.Text += String.Format("{0}<br />", uploadedfile.FileName)
Next
End If
End Sub
Protected Sub pb_Add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles pb_submit.Click
Dim strKeyName() As String = {"DocumentName", "DocType"}
Dim objKeyVal() As Object = {Label4.Text,7}
structDb = objDataSet.ExecSP("tbl", "spupload_file", strKeyName, objKeyVal)
If structDb.intCode = 0 Then
Label5.Text = structDb.strMessage
Label5.CssClass = "error"
Exit Sub
End If
End Sub
when i try this ... this shows record in database table like
1 abc.docx<br />def.docx<br />
where as i want like this
1 abc.docx
2 def.docx
Index was outside the bounds of the array.
and how i insert also document path
any help ?
UPDATED
ok according to #Andy Reid
i try this
For Each file As HttpPostedFile In ListBox1.Items
Dim DocumentName As String = file.FileName
Dim strKeyName() As String = {"DocumentName", "DocType"}
Dim objKeyVal() As Object = {DocumentName, 7}
structDb = objDataSet.ExecSP("tbl", "spupload_file", strKeyName, objKeyVal)
Next
If structDb.intCode = 0 Then
Label5.Text = structDb.strMessage
Label5.CssClass = "error"
Exit Sub
End If
but this shows error
An exception of type 'System.InvalidCastException' occurred in DecibelCRM.dll but was not handled in user code
Additional information: Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to type 'System.Web.HttpPostedFile'.
Using a listbox instead of the Label4, if dataset DocumentID is AutoIncrement
Protected Sub UploadLinkButton_Click(sender As Object, e As EventArgs) Handles UploadLinkButton.Click
uploadmultiple_file(FileUpEx.FileName)
End Sub
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
'Add each PostedFile to list Box instead of using label
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
FilesListBox.Items.Add(uploadedfile.FileName)
Next
End If
End Sub
Protected Sub pb_Add_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton.Click
Dim objDataSet As New objDataSet 'Or whatever you have
Dim DocType as Integer = 7
'Gets each file from FilesListBox to insert them into objDataSet
For Each file As HttpPostedFile In FilesListBox.Items
Dim DocumentName as String = file.FileName
'Because the DocumentID is AutoIncrement, you don't need to enter it here
objDataSet.DocDownloads.AddDocDownloadsRow(DocumentName, DocType)
Next
End Sub
This will be for the data table, it should put each PostedFile as a new Row into DocDownloads. Upon doing some more research, the full path isn't accessible due to security reasons
Your code:
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
'Label4.Text = ("<b>File: </b>" + uploadedfile.FileName)
Label4.Text += String.Format("{0}<br />", uploadedfile.FileName)
Next
End If
End Sub
Try
Public Sub uploadmultiple_file(filename As String)
If fileUpEx.HasFiles Then
Try
For Each uploadedfile As HttpPostedFile In fileUpEx.PostedFiles
Label4.Text += uploadedfile.FileName & vbCRLF
'Possibly something like: "Label4.Text += uploadedfile.FullPath & vbCRLF" for the document path
Next
Catch ex as Exception
'Whatever exception handling code
End try
End If
End Sub
I am learning ASP.Net development & trying to create Web application where ListView data should get filter selection done in ComboBox. I have made ListView & bind it with my database table & tried to put ComboBox filter but getting this error
(System.Web.HttpException: Request is not available in this context) in output .
VB Code
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Partial Class VB
Inherits System.Web.UI.Page
Dim query As String
Dim strArea As String = Request.QueryString("Country")
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindListView()
End If
End Sub
Private Sub BindListView()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand()
cmd.CommandText = "SELECT CustomerId, ContactName, Country FROM Customers"
cmd.Connection = con
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
lvCustomers.DataSource = dt
lvCustomers.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub OnPagePropertiesChanging(sender As Object, e As PagePropertiesChangingEventArgs)
TryCast(lvCustomers.FindControl("DataPager1"), DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, False)
Me.BindListView()
End Sub
Protected Sub country_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles country.SelectedIndexChanged
Try
If country.SelectedValue <> "All" Then
query = "Select CutomerId, Contact Name, Country from Customers where Country like '%" + strArea + "%' order by rank;"
End If
Dim cmd As New SqlCommand(query)
Dim da As New SqlDataAdapter(cmd)
Dim table As New DataTable
Catch ex As Exception
End Try
End Sub
End Class
Request read-only property belongs to Page class and inherited class members are available only within the members of the class which inherits it(VB in your case). Change your code like this:-
Partial Class VB
Inherits System.Web.UI.Page
Dim query As String
Dim strArea As String = String.Empty
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindListView()
End If
strArea = Request.QueryString("Country")
End Sub
Also, Please note it will be better to check if any value exists within your query string variable before assigning it.
My code that sets up a ServerReport object on a web forms page, and then renders the report from SSRS to a pdf. Parameter and report name is passed by URL.
Private Sub Page_Load(sender As Object, e As EventArgs)
Dim reportname As String
'Dim parameter(0) As ReportParameter
reportname = Request("reportname").ToString
Dim v As New ReportViewer
v.ProcessingMode = ProcessingMode.Remote
Dim serverreport As New ServerReport
serverreport = v.ServerReport
serverreport.ReportServerUrl = New Uri("http://xxxxxx:80/ReportServer")
serverreport.ReportPath = "/Reports/Aramid/Sheeter/" & reportname
Select Case reportname
Case Is = "NomexBlockCard" 'Or "NomexBlockLabel" Or "NomexInternalLabel"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramBlock", Request("paramBlock").ToString, False))
serverreport.SetParameters(paramList)
Case Is = "NomexRoutingData"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramWO", Request("paramWO").ToString, False))
serverreport.SetParameters(paramList)
End Select
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
Save(serverreport, "C:\WebReports\" & reportname & ".pdf")
'now print
Response.Redirect("reports.ashx?fileName=" & reportname)
End Sub
Public Sub Save(ByVal sr As ServerReport, ByVal savePath As String)
Try
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim deviceInfo As String
Dim bytes As Byte()
deviceInfo = "True" '<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>"
bytes = sr.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Using Stream As New FileStream(savePath, FileMode.Create)
Stream.Write(Bytes, 0, Bytes.Length)
Stream.Close()
End Using
Catch ex As Exception
End Try
End Sub
The report renders and saves as a pdf but the parameter value does not seem to be getting used in the report.
I have confirmed over and over that there is a value in paramBlock.
I don't know what I am doing wrong.
Am I missing a step or something?
Ryan
As your report is being rendered and saved, I'm assuming the credentials are set up correctly.
You can use the ServerReport.GetParameters function before saving the report to check what the parameters (and their values/properties) actually are.
Also, make sure you're setting every parameter required by the report (even those hidden or internal), and that every parameter value is within the allowed values of the parameter (if limits are set).
If the problem doesn't lie in passing the parameters, you might want to take a look at the report itself and how it handles its parameters.
From your recent comment about a "Parameter validation failed" error, it sounds like your issue is not with your calling code structure, but rather matching the parameters to the report definition.
The most common issue is hidden or internal parameters which you are ignoring. You need to carefully review the parameter design in SSRS Report Designer, and make sure your passed parameters comply with what it expects.
Consider following suggestions. It might help you to resolve your issue. After considering every point, you can try your code
Place following code just above the Select Case reportname statement line
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
You can also try changing code line
serverreport.ReportServerCredentials = New ReportViewerCredentials(user name here, password here, "CORE")
To
ServerReport.ReportServerCredentials.NetworkCredentials = System.Net.CredentialCache.DefaultCredentials
If your report has default parameters, then remove default parameters and test your code
And also remove exception handling from your method
Public Sub Save(ByVal sr As ServerReport, ByVal savePath As String)
You can try following code:
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim reportname As String = Request("reportname").ToString
'Dim parameter(0) As ReportParameter
Dim v As New ReportViewer
v.ProcessingMode = ProcessingMode.Remote
Dim ServerReport As ServerReport
ServerReport = v.ServerReport
serverreport.ReportServerUrl = New Uri("http://xxxxxx:80/ReportServer")
serverreport.ReportPath = "/Reports/Aramid/Sheeter/" & reportname
ServerReport.ReportServerCredentials.NetworkCredentials = System.Net.CredentialCache.DefaultCredentials
Select Case reportname
Case Is = "NomexBlockCard" 'Or "NomexBlockLabel" Or "NomexInternalLabel"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramBlock", Request("paramBlock").ToString, False))
serverreport.SetParameters(paramList)
Case Is = "NomexRoutingData"
Dim paramList As New Generic.List(Of ReportParameter)
paramList.Add(New ReportParameter("paramWO", Request("paramWO").ToString, False))
serverreport.SetParameters(paramList)
End Select
Save(serverreport, "C:\WebReports\" & reportname & ".pdf")
End Sub
Public Sub Save(ByRef sr As ServerReport, ByVal savePath As String)
Try
Dim warnings As Warning() = Nothing
Dim streamids As String() = Nothing
Dim mimeType As String = Nothing
Dim encoding As String = Nothing
Dim extension As String = Nothing
Dim deviceInfo As String
Dim bytes As Byte()
deviceInfo = "True" '<DeviceInfo><SimplePageHeaders>True</SimplePageHeaders></DeviceInfo>"
bytes = sr.Render("PDF", Nothing, mimeType, _
encoding, extension, streamids, warnings)
Using Stream As New FileStream(savePath, FileMode.Create)
Stream.Write(bytes, 0, bytes.Length)
Stream.Close()
End Using
Catch ex As Exception
End Try
End Sub
Maybe this is not the case, but I remember that Parameters value can be lost during PostBack.
So I would try a syntax like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.Page.IsPostBack Then
'your code to setup and print report
End If
End Sub
If this solution doesn't work please provide the code used in Report Definition.
I worked on a VB.NET project and I have a problem in how to connect between tables.
I have access database [database1]
tables : T1 , RequestDetails
T1: U_ID Name Address Phone
RequestDetails: U_ID RqNo Requestport country_of_request RqMethod
On first page, the user should enter his information Name Address Phone. When a buttom is clicked, this data is inserts into the database and navigates to the second page.
On the second page, the user should complete entering his data based on the U_ID
I have 3 dropdownlists: Requestport, country_of_request, and RqMethod
Andd also when a button is clicked, it should insert data and go next.
Everything's ok; I worked on each page in separate. Now I want to make connection between U_ID in T1 and RequestDetails to make data connected from page 1 and page 2.
I don't know how to explain problem I hope every thing was clear.
My code for page 1 :
I build connection class to do connection staff
Imports System.Data
Imports System.Data.OleDb
Imports System
Public Class connection
Dim str As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hp\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\bin\Database1.accdb"
Dim con As New OleDbConnection(str)
Public Sub Insert(ByVal Name As String, ByVal Address As String, ByVal Phone As String)
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim adp As New OleDbCommand("insert into T1 values(" & GetMaxID() & ",'" & Name & "','" & Address & "','" & Phone & "') ", con)
adp.ExecuteNonQuery()
con.Close()
End Sub
Public Function GetMaxID() As Integer
Dim x As Integer = 1
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim adp As New OleDbCommand("select max(ID) from T1", con)
Try
x = adp.ExecuteScalar
Return x + 1
Catch ex As Exception
Return x
End Try
End Function
End Class
Then in the button :
Public Class _Default
Inherits System.Web.UI.Page
Dim x As New connection
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 EventArgs) Handles Button1.Click
x.Insert(TextBox1.Text, TextBox2.Text, TextBox3.Text)
Response.Redirect("~/ReqDetails.aspx")
End Sub
End Class
There is no problem here.
In the second page in the button:
Imports System.Data
Imports System.Data.OleDb
Imports System
Public Class shipmentDetails
Inherits System.Web.UI.Page
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 EventArgs) Handles Button1.Click
Dim str As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\hp\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\bin\Database1.accdb"
Dim con As New OleDbConnection(str)
con.Open()
Dim Command As New OleDbCommand("INSERT INTO RequestDetails( Requestport," & "country_of_request," & "RqMethod,")VALUES(#Requestport,#country_of_request,#RqMethod)", con)"
Command.Parameters.Add(New OleDbParameter("#Requestport", Requestport.SelectedItem.Text))
Command.Parameters.Add(New OleDbParameter("#country_of_request", country_of_request.SelectedItem.Text))
Command.Parameters.Add(New OleDbParameter("#RqMethod", RqMethod.SelectedItem.Text))
)
Command.ExecuteNonQuery()
con.Close()
Label1.Text = "Thank You. Your transaction was successful."
Label1.Visible = True
End Sub
End Class
Here is the problem:
If I fill the data and click next it shows me an error because U_Id not fill and it should not null
That means it should read u_id from the page 1...How can I do it?
This looks like VB.NET code within an ASP project. If that's the case, I'd ask you to at least put that in the tags, but you can also use POST to send the U_ID to page two.
If this is a pure VB.NET application opening a second window you should be able to make the second window a child of the parent, make a global public variable called U_ID and be able to call parent.U_ID (Parent should ideally be the name of your original form.). I think ideally you can use the parent call in ASP as well, but I've never tried it myself.
I would have actually asked for some clarification, but I can't seem to do that just yet. If you'd care to confirm which of the two it actually is then I could edit in a little sample code if you need.
EDIT:
Here is something considerably easier than the HTTP Post methodology. For reference, read The msdn article.
Create the following in the main form.
Public ReadOnly Property U_ID() As Integer
Get
Return ID
End Get
End Property
Then append your one function like this (It's about the easiest way I can figure this to work:
Public ID as Integer
Public Function GetMaxID() As Integer
Dim x As Integer = 1
If con.State = ConnectionState.Closed Then
con.Open()
End If
Dim adp As New OleDbCommand("select max(ID) from T1", con)
Try
x = adp.ExecuteScalar
ID=x+1
Return x + 1
Catch ex As Exception
Return x
End Try
End Function
Now you have a public variable your second page can read like this:
<%# PreviousPageType VirtualPath="~/SourcePage.aspx" %>
Public U_ID as Integer = PreviousPage.U_ID
Try that. You should be able to access the previous page's U_ID.
I am currently doing a project on web service for wine. I have the wine table with wineName and wineType. Also I have the search function implemented in the webservice coding as well as a separate webform to call the function of the search function
I have the following code for performing search in the search service:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim selectSql As String = "SELECT * From Wine WHERE WineType='" & searchName + "'"
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(selectSql, con)
Dim ds As New Data.DataSet
con.Open()
selectAdapter.Fill(ds, "Wine")
con.Close()
Return ds
End Function
As for the webform, it's just a simple page with textbox labeled as searchName, a button and a gridView1 tied to ObjectDataSource.
This is the coding i have for webform:
Partial Class Search
Inherits System.Web.UI.Page
Dim searching As searchwine.Service = New searchwine.Service
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If searchName.Text = "" Then
lblDisplayError.Text = "Can't search empty field!"
Else
Dim ds As DataSet = searching.Search(searchName.Text)
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
GridView1.Visible = True
lblDisplayError.Visible = False
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lblDisplayError.Text = ""
GridView1.Visible = False
End Sub
End Class
Everything seems fine, but i have the following error when i want to do a search:
System.NullReferenceException: Object reference not set to an instance of an object. at Service.Search(String searchName)
Can anyone help me out please?
I've looked through your code a couple times and I can't see what's causing the NullReferenceException. My best guess is that it couldn't find a connection string name "ConnectionString" in your web.config file, but even that doesn't quite seem to fit.
I can suggest some improvements to your search code. Hopefully you'll at least get a better error message out of this:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim ds As New Data.DataSet()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(connectionString), _
cmd As New SqlCommand("SELECT * From Wine WHERE WineType= #SearchName", con)
'I had to guess at the exact length and type of the field here
cmd.Parameters.Add("#SearchName", SqlDbType.VarChar, 50).Value = searchName
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(cmd, con)
selectAdapter.Fill(ds, "Wine")
End Using
Return ds
End Function
But in the end I expect you'll need to step through the method and see exactly which line above throws the exception.
Looks like you are missing a New
Dim ds As DataSet = searching.Search(searchName.Text)
Should be...
Dim ds As **New** DataSet = searching.Search(searchName.Text)