records deleted from database when uploading files - database

When i try to upload multiple pictures to the database my code works fine and all the pictures show in the gallery, but when i try to modify the picture in the database, and modify one picture it deletes the rest of the pictures from the database. The recordset isnt deleted and the rest of the information stays the same, its just the 5+ places i have for the pictures whose data gets deleted. here is my code so far..
message.Text = "please wait"
pics.Visible = False
'wherepics are stored
Dim savepath As String = Server.MapPath("/cgi-bin/properties/")
Dim tfn0 As String = ""
Dim tfn1 As String = ""
'dims the filenames a variables
Dim img0 As String = pic0.FileName
Dim img1 As String = pic1.FileName
'this is the set of paths to check
'this will check for redundencies in the database so no dublicate file names will occur
Dim ptc0 As String = savepath + img0
Dim ptc1 As String = savepath + img1
Dim url0 As String = ""
Dim url1 As String = ""
Dim counter As Integer = 2
If (System.IO.File.Exists(ptc0)) Then
While (System.IO.File.Exists(ptc0))
tfn0 = counter.ToString = img0
ptc0 = savepath + tfn0
counter = counter + 1
End While
ElseIf (System.IO.File.Exists(ptc1)) Then
While (System.IO.File.Exists(ptc1))
tfn1 = counter.ToString = img1
ptc1 = savepath + tfn1
counter = counter + 1
End While
End If
Dim sp0 As String = savepath + img0
Dim sp1 As String = savepath + img1
If Not pic0.FileName = Nothing Then
pic0.SaveAs(sp0)
img0 = pic0.FileName
url0 += "pic_main"
url1 += img0
End If
If Not pic1.FileName = Nothing Then
If pic0.FileName = Nothing Then
pic1.SaveAs(sp1)
img1 = pic0.FileName
url0 += "pic_one"
url1 += img1
Else
pic1.SaveAs(sp1)
img1 = pic0.FileName
url0 += ", pic_one"
url1 += ", " & img1
End If
End If
Dim datanames() As String = {url0}
', "pic_six", "pic_seven", "pic_eight", "pic_nine"
Dim datavalues() As String = {url1}
', file6, file7, file8, file9
DB.UpdateCommand(datanames, datavalues, "property", "property_id = " & Request.QueryString("id")) ', true)
Response.Redirect("finished.aspx")

I have found the solution it was looking at all of the file upload controls, since nothing was in them it would reference those fields I had this figured out a while ago, got busy and never found time to post my answer. in the database and delete anything that was in it and replace it with a blank space. I changed the code a bit to where the users chooses the slot in which they want to update, then carry over a qstring instead of having it update all of them at once

Related

removing Buttons when exporting to PDF

I am trying to remove or hide the 4 commandbuttons when exporting to PDF. The way I do it works for the first time exporting but if I export the same file again, I'll get an error referring to this line: Me.CommandButton3.Select even though all buttons are back. Is there a better way of hiding without having to delete them? I dont have printobject under properties as suggested on the internet. I should add, I still have other macros like a publish_date I do not wanna remove.
Also, I realized those commandbuttons arent saved as shapes, so trying to hide shapes didnt work either. But what about linking them to shapes and making the other shapes go into the fore and background when saving to PDF? would that work?!
Another idea was perhaps something like this:
Dim s As Shape
For Each s In ActiveDocument.Shapes
If s.Type = msoFormControl Then
If s.Type = wdButtonControl Then
s.Delete
End If
End If
Next s
It isnt working and I need the buttons back after exporting. Below my code with deleting the buttons, getting them back, but also getting an error with commandbutton 3 not working anymore, which is saving the file as .docm:
Private Sub CommandButton1_Click()
Const FilePath As String = "//SRVDC\Arbeitsordner\Intern\Meetings\Finale Versionen\"
Const OrigFileName As String = "20210910_Besprechungsnotizen_00_"
Dim Title As String: Title = "Besprechungsnotizen"
Dim newTitle As String
Dim MyDate As String: MyDate = Format(Date, "YYYYMMDD")
Dim User As String
Dim Version As String
If Split(ActiveDocument.Name, ".")(0) = OrigFileName Then
'file has not been resaved
Else
'file has been saved before so extract data from filename
Dim nameElements As Variant
nameElements = Split(Split(ActiveDocument.Name, ".")(0), "_")
User = nameElements(UBound(nameElements))
Version = nameElements(UBound(nameElements) - 1)
Title = nameElements(UBound(nameElements) - 3)
End If
If User = "" Then
User = InputBox("Wer erstellt? (Name in Firmenkurzform)")
newTitle = MsgBox("Anderer Titel?", vbQuestion + vbYesNo + vbDefaultButton2, "Titel")
If newTitle = vbYes Then
Title = InputBox("Wie soll der Titel sein?")
Else
End If
Version = "0"
Else
newVersion = MsgBox("Neue Version?", vbQuestion + vbYesNo + vbDefaultButton2, "Neue Version")
If newVersion = vbYes Then
Dim currentUser As String
currentUser = InputBox("Wer bearbeitet? (Name in Firmenkurzform)")
If currentUser = User Then
Else
User = User & currentUser
End If
Version = Format$(Version + 1)
Else
Version = Format$(Version)
End If
End If
Me.CommandButton1.Select
Selection.Delete
Me.CommandButton2.Select
Selection.Delete
Me.CommandButton3.Select
Selection.Delete
Me.Refresh.Select
Selection.Delete
ActiveDocument.ExportAsFixedFormat OutputFileName:=FilePath & _
MyDate & "_" & Title & "_i_0" & Version & "_" & User & ".pdf", _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
IncludeDocProps:=True, _
CreateBookmarks:=wdExportCreateWordBookmarks, _
BitmapMissingFonts:=True
ActiveDocument.Undo
ActiveDocument.Undo
ActiveDocument.Undo
ActiveDocument.Undo
ActiveDocument.Undo
End Sub
Ok I found a solution that works with a few tricks. So I added 4 rectangle shapes and I only wanna make 3 disappear while saving as PDF. It works when I wrap 3 of those shapes behind the text (or buttons) and add
With ActiveDocument
.Shapes(1).WrapFormat.Type = wdWrapFront
ActiveDocument.ExportAsFixedFormat OutputFileName:=FilePath & ...
...
.Shapes(1).WrapFormat.Type = wdWrapBehind
End With
Somehow it does put those 3 in front of the text and only puts those three behind the text again and leaving the 4th rectangle permanent in front of another text. Just as I want it. Below my entire code:
Private Sub CommandButton1_Click()
Const FilePath As String = "//SRVDC\Arbeitsordner\Intern\Meetings\Finale
Versionen\"
Const OrigFileName As String = "20210910_Besprechungsnotizen_00_"
Dim Title As String: Title = "Besprechungsnotizen"
Dim newTitle As String
Dim MyDate As String: MyDate = Format(Date, "YYYYMMDD")
Dim User As String
Dim Version As String
If Split(ActiveDocument.Name, ".")(0) = OrigFileName Then
'file has not been resaved
Else
'file has been saved before so extract data from filename
Dim nameElements As Variant
nameElements = Split(Split(ActiveDocument.Name, ".")(0), "_")
User = nameElements(UBound(nameElements))
Version = nameElements(UBound(nameElements) - 1)
Title = nameElements(UBound(nameElements) - 3)
End If
If User = "" Then
User = InputBox("Wer erstellt? (Name in Firmenkurzform)")
newTitle = MsgBox("Anderer Titel?", vbQuestion + vbYesNo + vbDefaultButton2, "Titel")
If newTitle = vbYes Then
Title = InputBox("Wie soll der Titel sein?")
Else
End If
Version = "0"
Else
newVersion = MsgBox("Neue Version?", vbQuestion + vbYesNo + vbDefaultButton2, "Neue Version")
If newVersion = vbYes Then
Dim currentUser As String
currentUser = InputBox("Wer bearbeitet? (Name in Firmenkurzform)")
If currentUser = User Then
Else
User = User & currentUser
End If
Version = Format$(Version + 1)
Else
Version = Format$(Version)
End If
End If
With ActiveDocument
.Shapes(1).WrapFormat.Type = wdWrapFront
ActiveDocument.ExportAsFixedFormat OutputFileName:=FilePath & _
MyDate & "_" & Title & "_i_0" & Version & "_" & User & ".pdf", _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
IncludeDocProps:=True, _
CreateBookmarks:=wdExportCreateWordBookmarks, _
BitmapMissingFonts:=True
.Shapes(1).WrapFormat.Type = wdWrapBehind
End With
End Sub

Why image cannot be saved in database

I'm using VB.NET and SQL Server for my system. I have a problem saving an image into the database. I need to save and retrieve image on the same page but I get an error:
unable to cast System.DBNull to system bytes.
I have tried several coding to fix my coding but it does not worked.
Code for retrieve image.
Dim id As String = txtImages.Text.Trim() 'txtImages is textbox name
Image1.Visible = id <> ""
If id <> "" Then
Dim dt As DataTable = GetData((Convert.ToString("SELECT ImagePic FROM masterlist WHERE id
='") & Request.QueryString("id")) + "'") 'image data will be select depend on what user search in the
serch textbox
If dt.Rows.Count > 0 Then
Dim bytes As Byte() = TryCast(dt.Rows(0)("ImagePic"), Byte())
Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Image1.ImageUrl = Convert.ToString("data:images/png;base64,") & base64String
Else
Image1.ImageUrl = ""
Image1.AlternateText = "No image present in database with the name" 'if there is no image
in db the message will displayed
End If
End If
End Sub
Code for save image
Dim fileName As String = String.Empty
Dim filePath As String = String.Empty
Dim getPath As String = String.Empty
Dim pathToStore As String = String.Empty
Dim bytes As [Byte]()
Dim fs As FileStreamenter code here
Dim br As BinaryReader
Dim cmd As New SqlCommand("Updateonlyimage_Sp3", cs) ' SQL command for this page is inside SQL Server I declare it as Insertapprovalcustom_Sp2"
cmd.CommandType = CommandType.StoredProcedure
Try
If FileUpload1.HasFile Then
fileName = FileUpload1.FileName
filePath = Server.MapPath("HSCODE/" & Convert.ToString(System.Guid.NewGuid()) & fileName)
'path to doucument inside approval_pdf file
FileUpload1.SaveAs(filePath)
cmd.Parameters.AddWithValue("#id", Request.QueryString("id"))
cmd.Parameters.AddWithValue("#ImagePicName", fileName)
Dim getPos As Integer = filePath.LastIndexOf("\")
Dim len As Integer = filePath.Length()
getPath = filePath.Substring(getPos, len - getPos)
pathToStore = getPath.Remove(0, 1)
cmd.Parameters.AddWithValue("#ImagePicPath", pathToStore)
fs = New FileStream(filePath, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
bytes = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
cmd.Parameters.AddWithValue("#ImagePic", bytes)
cmd.Parameters.AddWithValue("#ContentType", FileUpload1.PostedFile.ContentType)

Update Textbox after each iteration VB.Net WPF

I have a For loop which runs through xlsx files in a directory, I need to append the filenames in a TextBlock after each loop and refresh the TextBlock to show the updated text.
The code I have below only displays the filenames after the loop has executed.
Dim lcFileName As String = ""
Dim fileArray() As String = Directory.GetFiles(txtDirectory.Text, "*.xlsx", SearchOption.AllDirectories)
For Each file As String In fileArray
Dim ExcelApp As Excel.Application = New Excel.Application
Dim Workbook As Excel.Workbook = ExcelApp.Workbooks.Open(file)
Dim Worksheet As Excel.Worksheet = Workbook.Sheets(1)
Dim Range As Excel.Range = Worksheet.UsedRange
Dim rowCount As Integer = Range.Rows.Count
Dim colCount As Integer = Range.Columns.Count
Dim tmpOrder(rowCount, colCount) As String
tbResults.Text = tbResults.Text + Environment.NewLine + Path.GetFileName(file) + " imported."
For i = 1 To rowCount
For j = 1 To colCount
'New line
If (i = 1 And j = 1) Then
tmpOrder(i - 1, j - 1) = Range.Cells(i, j).Value
lcFileName = tmpOrder(i - 1, j - 1).ToString()
Else
If (Not String.IsNullOrEmpty(Range.Cells(i, j).Value)) Then
tmpOrder(i - 1, j - 1) = Range.Cells(i, j).Value.ToString()
End If
End If
Next
Next
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Worksheet)
Worksheet = Nothing
ExcelApp.ActiveWorkbook.Close(True)
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(Workbook)
Workbook = Nothing
ExcelApp.Quit()
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(ExcelApp)
ExcelApp = Nothing
'
Next
Any help would be appreciated, VB.Net required.
Finally got it working.
Ok first I created my Method to update the TextBlock with the parameter passed for the filename.
Public Sub UpdateResults(ByVal lcFile As String)
tbResults.Text = tbResults.Text + Environment.NewLine + Path.GetFileName(lcFile) + " imported."
End Sub
In my For Loop i called the method with the following code
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, New ThreadStart(Sub() Me.UpdateResults(lcFile)))
Where UpdateResults(lcFile) is the method and parameter passed.
If you are not passing any parameters then call your method using this, where 'MyMethod' is the name of the method you want to run.
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, New ThreadStart(AddressOf MyMethod))
Something isn't playing nicely and is preventing the form from updating.
You can allow the app to process pending display operations by adding Application.DoEvents() inside one of the loops.
There is some overhead involved, so you probably want it in the outer loop, not the inner loop.

Create buttons from text file

I am using Visual Basic in Visual Studio 2017. I am trying to create buttons from a text file. If a text file contains words like
Test1
Test2
Test3
etc it should create 3 buttons using those names.
Dim path As String = "c:\words.txt"
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
Dim button As New System.Windows.Forms.Button()
Dim buttonTop As Integer = 100
For Each s In readText
Dim Location As New Point(100, (buttonTop + 20))
button.Location = Location
button.Text = s
button.Width = 100
Me.Controls.Add(button)
buttonTop += 20
button.Visible = True
Next
This code creates the buttons but are not saved. As the loop goes it creates them and they disappear from the form leaving just the last one at the end of the loop.
Any guidelines will be appreciated. Thanks.
Correct Answer. Thanks
Dim path As String = "c:\words.txt"
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
Dim buttonTop As Integer = 20
For Each s In readText
Dim button As New System.Windows.Forms.Button()
Dim Location As New Point(100, (buttonTop + 30))
button.Location = Location
Button.Text = s
button.Width = 100
button.Height = 30
Me.Controls.Add(Button)
buttonTop += 30
button.Visible = True
Next

Compare String Arrays of Different Sizes

I have two string arrays that I want to compare to each other. The one array (sProdList) will always be a set size (16 values), the other (sProd) might be 16, but it might be more or less values. I want to see if sProd contains any of the values in sProdList.
I'm using the below LINQ to try this out:
If Array.Exists(sProd, Function(x As String) sProdList.Contains(x)) Then
The idea being that if the current value of sProd is in sProdList it goes into the If statement, otherwise it skips over it.
When debugging my code I see that the value of x is 24, I'm not sure where it's getting this value from as neither of my arrays have 24 items.
Code is below, any help would be appreciated:
'Separate out Product Names
Dim sProd() As String = {}
Dim sInst() As String = {}
Dim sProdList() As String = {"Auto", "Chequing", "GIC", "Mutual Funds", "Real Estate", "RIF", "RSP", "Savings", "Shares", "Stock", "TFSA", "CCard", "Guar", "Loan", "Loc", "Mortgage"}
sProd = objNode.InnerText.Split(",")
objNode = Nothing
objNode = objXMl.SelectSingleNode("//Inst")
sInst = objNode.InnerText.Split(",")
Dim instPos As Integer = 0
For Each st As String In sProdList
If Array.Exists(sProd, Function(x As String) sProdList.Contains(x)) Then
If sInst(instPos) = "PCCU" Then
img = My.Resources.check
ElseIf sInst(instPos) <> "PCCU" OrElse sInst(instPos) = "" Then
img = My.Resources.exclamation
Else
img = My.Resources.redX
End If
dt.Rows.Add(New Object() {st, imageToByteArray(img)})
instPos += 1
End If
Next
dgProduct.DataSource = dt
You are iterating over sProdList but checking the whole list each time.
You can just use the Linq Contains method to see if sProd contains the string:
For Each st As String In sProdList
If sProd.Contains(st) Then
....
You are iterating sProdList, so you don't want to compare all of them within the loop, but you can use .Intersect to change to loop to just loop over the ones that are in both like this:
For Each st As String In sProdList.Intersect(sProd)
If sInst(instPos) = "PCCU" Then
img = My.Resources.check
ElseIf sInst(instPos) <> "PCCU" OrElse sInst(instPos) = "" Then
img = My.Resources.exclamation
Else
img = My.Resources.redX
End If
dt.Rows.Add(New Object() {st, imageToByteArray(img)})
instPos += 1
Next If
Also, you can further use LINQ to do create your query and feed that directly to dgProduct.DataSource rather than using DataTable as a wrapper like this:
Dim imgs = sInst.Select(Function(i) imageToByteArray(If(i = "PCCU", My.Resources.check, If((i <> "PCCU" OrElse i = ""), My.Resources.exclamation, My.Resources.redX))))
dgProduct.DataSource = sProdList.Intersect(sProd).Zip(imgs, Function(product, image) New From { product, image })

Resources