Insert document name & document path in vb.net - asp.net

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

Related

join between two tables from access database in two different page in vb.net

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.

Handling events of dynamically created controls in asp.net

I have a button which is not created dynamically. When I click on that button the number of lines in a textbox are counted. I store that in the variable called count. Depending on value of count I create buttons in panel.
Up to now it is working properly.
Now the click event of those buttons is not firing.
I have tried to google my question. But everywhere I got the same answer. Create the controls in Page_Init event. But how is it possible? I am getting the value of count from a textfile's lines, and that value of count decides how many button will be created in the panel.
Dim btnAllow As New Button
btnAllow.Text = "Allow"
btnAllow.ID = "btA" & x
AddHandler btnAllow.Click, AddressOf btnAllow_Click
btnAllowList.Add(btnAllow)
tdAllow.Controls.Add(btnAllow)
The code for btnAllow_Click
Protected Sub btnAllow_Click(ByVal sender As Object, ByVal e As System.EventArgs)
For x As Integer = 0 To btnAllowList.Count - 1
If sender.ID.SubString(3) = btnAllowList(x).ID.Substring(3) Then
Dim lineCount = IO.File.ReadAllLines(PendingRequestsPath).Length
Dim reader As New System.IO.StreamReader(DocumentViewersPath)
Dim allLines As New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
Dim DocumentViewerAlreadyExists As Boolean = False
For i As Integer = 0 To lineCount - 1
If ReadLine(i, allLines) = lblRequestorsList(x).Text Then
DocumentViewerAlreadyExists = True
Exit For
End If
Next
If DocumentViewerAlreadyExists = False Then
Dim Writer As System.IO.StreamWriter = IO.File.AppendText(DocumentViewersPath)
Writer.WriteLine(lblRequestorsList(x).Text)
End If
Dim line As String = ""
Dim r As IO.StreamReader = IO.File.OpenText(PendingRequestsPath)
Dim strFile As New ArrayList
While r.Peek <> -1 ' Loop through the file
line = r.ReadLine 'Read the next available line
' Check to see if the line contains what you're looking for.
' If not, add it to an ArrayList
If Not line.Contains(lblRequestorsList(x).Text) Then
strFile.Add(line)
End If
r.Close()
' Because we want to replace the content of the file, we first
' need to delete it.
If IO.File.Exists(PendingRequestsPath) Then
IO.File.Delete(PendingRequestsPath)
End If
' Create a StreamWriter object with the same filename
Dim objWriter As New IO.StreamWriter(PendingRequestsPath, True)
' Iterate through the ArrayList
For Each item As ArrayList In strFile
objWriter.WriteLine(item) ' Write the current item in the ArrayList to the file.
Next
objWriter.Flush()
objWriter.Close()
End While
End If
Next
End Sub
This worked for me:
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim NumberOfControls As Integer = 10
Session("CreateControls") = NumberOfControls
End Sub
Protected Sub btnAllow_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'This will be executed when clicking on the newly created buttons.
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Session("CreateControls") IsNot Nothing Then
For x As Integer = 0 To Convert.ToInt32(Session("CreateControls"))
Dim btnAllow As New Button
btnAllow.Text = "Allow"
btnAllow.ID = "btA" & x
AddHandler btnAllow.Click, AddressOf btnAllow_Click
Panel1.Controls.Add(btnAllow)
Next
End If
End Sub

Passing a NULL value to a GUID

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.

Passing value from codebehind with asyncupload after complete?

I'm trying to pass a value to a feedbacklabel after an asynch upload.
Protected Sub FileUploadComplete(ByVal sender As Object, ByVal e As EventArgs)
Try
Dim filename As String = System.IO.Path.GetFileName(AsyncFileUpload1.FileName)
AsyncFileUpload1.SaveAs(Server.MapPath("tmp/") + filename)
lblFeedback.Text = "File uploaded. Processing information"
'Get a StreamReader class that can be used to read the file
Dim objStreamReader As StreamReader
objStreamReader = File.OpenText(Server.MapPath("tmp/") + filename)
While objStreamReader.Peek <> -1
lblFeedback.Text += objStreamReader.ReadLine()
End While
objStreamReader.Close()
Catch ex As Exception
End Try
End Sub
The thing is I need to display how many rows have been uploaded in the database. How can I do this?
Add at the end of FileUploadComplete procedure following method call (I hope you can translate it from C# to VB):
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "feedback", string.Format("top.$get('{0}').innerText = '{1}'", lblFeedback.ClientID, lblFeedback.Text), true);

upload jpg/png/ gif photos

I was doing a test to upload pictures and i found out that when i upload pictures more than 2000px the webpage turn to be slow. I want users to upload pics with size not more than 600px and height 700px.
Imports System.Data
Imports System.IO
Imports System.Data.SqlClient
Partial Class PhotoAdmin_Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UserIdValue.Text = Membership.GetUser().ProviderUserKey.ToString()
cannotUploadImageMessage.Visible = False
End Sub
Protected Sub dvPictureInsert_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertedEventArgs) Handles dvPictureInsert.ItemInserted
'If the record was successfully inserted, save the picture
If e.AffectedRows > 0 Then
'Determine the maximum pictureID for this user
Dim results As DataView =
CType(maxPictureIDDataSource.Select(DataSourceSelectArguments.Empty),
DataView)
Dim pictureIDJustAdded As Integer = CType(results(0)(0), Integer)
'Reference the FileUpload control
Dim imageUpload As FileUpload =
CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If imageUpload.HasFile Then
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
imageUpload.SaveAs(baseDirectory & pictureIDJustAdded & ".jpg")
End If
End If
If e.Exception Is Nothing Then
' Use the AffectedRows property to determine whether the
' record was inserted. Sometimes an error might occur that
' does not raise an exception, but prevents the insert
' operation from completing.
If e.AffectedRows = 1 Then
MessageLabel.Text = "Record inserted successfully."
Else
MessageLabel.Text = "An error occurred during the insert operation."
' Use the KeepInInsertMode property to remain in insert mode
' when an error occurs during the insert operation.
e.KeepInInsertMode = True
End If
Else
' Insert the code to handle the exception.
MessageLabel.Text = e.Exception.Message
' Use the ExceptionHandled property to indicate that the
' exception has already been handled.
e.ExceptionHandled = True
e.KeepInInsertMode = True
End If
End Sub
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting
Dim cancelInsert As Boolean = False
Dim imageUpload As FileUpload =
CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If Not imageUpload.HasFile Then
cancelInsert = True
Else
If Not imageUpload.FileName.ToUpper().EndsWith(".JPG") Then
cancelInsert = True 'Invalid image file!
End If
End If
If cancelInsert Then
e.Cancel = True
cannotUploadImageMessage.Visible = True
End If
'Set the UserId value to the currently logged on user's ID
e.Values("UserId") = Membership.GetUser().ProviderUserKey
'Set the UploadedOn value to the current date/time
e.Values("UploadedOn") = DateTime.Now
End Sub
Protected Sub gvPictures_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gvPictures.RowDeleted
Dim baseDirectory As String = Server.MapPath("~/UploadedImages/")
Dim fileName As String = baseDirectory &
e.Keys("PictureID") & ".jpg"
File.Delete(fileName)
End Sub
Protected Sub gvPictures_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvPictures.RowUpdating
e.NewValues("UserId") = Membership.GetUser().ProviderUserKey
End Sub
End Class
Setting a max width and height on an uploaded image isn't necessarily going to fix your problem as you could upload an image with a much higher DPI and it still be a "large" image with small dimensions. Also, you would have to check the image dimensions once the image had been uploaded to your server.
You could set a maxiumum file size in the web.config using the maxRequestLength property which could be used to prevent a large file being uploaded...
Sorry if my vb is wrong as im a c# guy!! but I hope this should give you a guidance. I do something similar in c#. Good luck
Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting
Dim cancelInsert As Boolean = False
Dim imageUpload As FileUpload =
CType(dvPictureInsert.FindControl("imageUpload"), FileUpload)
If Not imageUpload.HasFile Then
cancelInsert = True
Else
If Not imageUpload.FileName.ToUpper().EndsWith(".JPG") Then
cancelInsert = True 'Invalid image file!
Else
Dim image As System.Drawing.Image =
System.Drawing.Image.FromStream(imageUpload.PostedFile.InputStream)
If image.Width > 600 Or image.Height > 700 Then
cancelInsert = True
End If
End If
End If
//etc

Resources