NullReferenceException was caught - vb.net

Please I'm using vb.net 2008 and Sql 2008 and I have to save a picture in to the database. When I run the code initially it was saving and later i realized it was giving me NullReferenceException was caught. Object reference not set to an instance of an object. I' just confused!
The code below
Imports System.Data.SqlClient
Imports System.IO
Private Sub btnImage1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImage1.Click
'Code to load picture
Dim OpenFileDialog1 As New OpenFileDialog
OpenFileDialog1.Filter = "JPG|*.jpg|BITMAP|*.bmp|GIF|*.gif"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName <> "" AndAlso IO.File.Exists(OpenFileDialog1.FileName) Then
Dim Extention As String = New IO.FileInfo(OpenFileDialog1.FileName).Extension
Select Case Extention.ToLower
Case Is = ".jpg", Is = ".bmp", Is = ".gif"
Case Else
MsgBox("Only JPG, BMP and GIF files are allowed. Thank you")
Exit Sub
End Select
Me.Pic1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub
'Code to save picture (I stepped into the code and the frmAllottee.Pic1 is there)
Public Sub Save_Picture()
Dim sql_command As SqlCommand
Dim mStream As MemoryStream = New MemoryStream()
'Dim mstream As New MemoryStream()
frmAllottee.Pic1.BackgroundImage.Save(mstream, frmAllottee.Pic1.BackgroundImage.RawFormat) - This line gives the error
Dim arrImage() As Byte = mstream.GetBuffer()
mstream.Close()
Dim Sql As String = "Insert into Alloc(Pic) VALUES(#Pic)"
sql_command = New SqlClient.SqlCommand(Sql, Con)
sql_command.Connection.Open()
sql_command.Parameters.AddWithValue("#Pic1", arrImage)
sql_command.ExecuteNonQuery()
sql_command.Connection.Close()
End Sub

This would happen if frmAllottee.Pic1.BackgroundImage is null.
Image and BackgroundImage are not the same.

Me.Pic1.Image = Image.FromFile(OpenFileDialog1.FileName)
This line of code here doesnt correspond to this code :
frmAllottee.Pic1.BackgroundImage.Save(mstream, frmAllottee.Pic1.BackgroundImage.RawFormat)
You have inserted an Image in your Pic1 in the Image while you are saving it and you chose BackgroundImage instead of Image
Also
Dim Sql As String = "Insert into Alloc(Pic) VALUES(#Pic)"
sql_command = New SqlClient.SqlCommand(Sql, Con)
sql_command.Connection.Open()
sql_command.Parameters.AddWithValue("#Pic1", arrImage)
sql_command.ExecuteNonQuery()
sql_command.Connection.Close()
#Pic from inserting to database should be the same as your #Pic1 when addingwithvalue i.e. (both should be #Pic or whichever you like)
Ive tried it and it works

Related

compress image before insert it to the database

i have table in database(SQL server) contain image column, how to compress the image before insert it to the database?
or if there any solution for what i need to do i will be Glad, this what i need:
i'm making a small program for rent shops, so the user will print contracts and after the contract printed and signed the user want to store it again so he can retrieve it any time. i'm using image column to allow the user to have a copy for the contract as image but the problem is that the contracts is 2 pages so for the one contract i need 2 image and this take a lot of space.
is there any way to do it deferment. i'm using a server to feed all computers connected to the program.
this is the code to insert image:
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim fName As String
fName = imagepath
If File.Exists(fName) Then
Dim content As Byte() = ImageToStream(fName)
'فحص الاتصال بقاعدة البيانات
If SQL.conn.State = ConnectionState.Open Then
SQL.conn.Close()
End If
SQL.conn.Open()
Dim cmd As New SqlCommand()
cmd.CommandText = "insert into test (image) values(#image)"
cmd.Parameters.AddWithValue("#image", (content))
cmd.Connection = SQL.conn
cmd.ExecuteNonQuery()
SQL.conn.Close()
Else
MsgBox(fName & " الصورة المختارة ليست موجودة او غير صالحة ", vbCritical, "حصل خطأ")
End If
End Sub
Dim imagepath As String
Dim myStream As IO.Stream = Nothing
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim openFileDialog1 As New OpenFileDialog()
'Set the Filter.
openFileDialog1.Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png"
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
myStream = openFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
imagepath = openFileDialog1.FileName
End If
Catch Ex As Exception
MessageBox.Show("Cannot read file from disk. Original error: " & Ex.Message)
Finally
' Check this again, since we need to make sure we didn't throw an exception on open.
If (myStream IsNot Nothing) Then
myStream.Close()
End If
End Try
Else
openFileDialog1.FileName = Nothing
Return
End If
End Sub
Private Function ImageToStream(ByVal fileName As String) As Byte()
Dim stream As New MemoryStream()
tryagain:
Try
Dim image As New Bitmap(fileName)
image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg)
Catch ex As Exception
GoTo tryagain
End Try
Return stream.ToArray()
End Function
I would not suggest compressing the images. Unfortunately, this would probably have little affect on many of the more common image formats (such as Jpeg) as they are already compressed.
You could adjust the quality to the minimum (whilst still being a readable image) at the time the images are uploaded. But I would suggest doing this at the time they are scanned in. That way each one could be viewed to see that it is still readable.

Import CSV file to database using VB

I need to import the information from a CSV txt file to a database using the DataGridView in my form. The application should allow the user to open a .txt file and then update the DataGridView table in my form. I am able to get the file, but am unable to update the grid using the file. I can update textboxes, but cannot figure out how to update the grid. Can anyone help me out with this?
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private fileToOpen As String 'the file to be opened and read
Private responseFileDialog As DialogResult 'response from OpenFileDialog
Private myStreamReader As StreamReader 'the reader object to get contents of file
Private myStreamWriter As StreamWriter 'the writer object to save contents of textbox
Private myTextFieldParser As TextFieldParser ' To parse text to searched.
Dim myDataAdapter As OleDb.OleDbDataAdapter
Dim myString() As String
Dim myRow As DataRow
Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim fileContentString As String 'contents of the file
Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter)
'Dim myRow As DataRow
'set the properties of the OpenFileDialog object
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
OpenFileDialog1.Title = "Select File to View..."
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
'responseFileDialog contains holds the response of the user (which button they selected)
responseFileDialog = OpenFileDialog1.ShowDialog()
'check to see if the user select OKAY, if not they selected CANCEL so don't open anything
If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then
'make sure there isn't a file already open, if there is then close it
If (myStreamReader IsNot Nothing) Then
myStreamReader.Close()
'TextBoxFileOutput.Clear()
End If
'open the file and read its text and display in the textbox
fileToOpen = OpenFileDialog1.FileName
myStreamReader = New StreamReader(OpenFileDialog1.FileName)
initTextFieldParser()
'loop through the file reading its text and adding it to the textbox on the form
Do Until myStreamReader.Peek = -1
fileContentString = myStreamReader.ReadLine()
'Try
' myTextFieldParser = New TextFieldParser(fileToOpen)
' myTextFieldParser.TextFieldType = FieldType.Delimited
' myTextFieldParser.SetDelimiters(",")
'Catch ex As Exception
' MessageBox.Show("Cannot Open File to Be Read!")
'End Try
myTextFieldParser.TextFieldType = FieldType.Delimited
myString = TextFieldParser.NewLine()
myRow.Item("FirstName") = myString(1)
MyContactsDataSet.Tables("People").Rows.Add(myRow)
PeopleTableAdapter.Update(MyContactsDataSet)
'TextBoxFileOutput.AppendText(fileContentString)
'TextBoxFileOutput.AppendText(Environment.NewLine)
Loop
'close the StreamReader now that we are done with it
myStreamReader.Close()
'SaveToolStripMenuItem.Enabled = True
End If
End Sub
Private Sub initTextFieldParser()
'Close myTextFieldParser in case the user is surfing through the records and then
'decides to search for a particular last name --> Basically start searching from beginning of the file
If (myTextFieldParser IsNot Nothing) Then
myTextFieldParser.Close()
End If
Try
myTextFieldParser = New TextFieldParser(fileToOpen)
myTextFieldParser.TextFieldType = FieldType.Delimited
myTextFieldParser.SetDelimiters(",")
Catch ex As Exception
MessageBox.Show("Cannot Open File to Be Read!")
End Try
End Sub
End Class
updating gridview with your file content
Import System.IO as we gonna need StreamReader
Using reader As New StreamReader("filepath")
DataGridView1.Columns.Add("col1",reader.ReadToEnd())
End Using
check this out!

Writing multiple SQL server tables as separate nodes to XML Document

I have multiple SQL server tables from which I want to pull data and write to XML. I want my XML to be formed like this:
<Data>
<Query1Table>
<Table>
<Column1>Data</Column1>
<Column2>Data</Column2>
...
</Table>
</Query1Table>
<Query2Table>
<Table>
<Column1>Data</Column1>
<Column2>Data</Column2>
...
</Table>
</Query2Table>
</Data>
I'm using datasets to write the xml, but the code I'm working with doesn't append the data, it overwrites:
Dim connetionString As String
Dim connection As SqlConnection
Dim adapter As SqlDataAdapter
Dim directory As String
Dim ds As New DataSet
Dim sql As String
connection = New SqlConnection(connetionString)
sql = "select * from scheduledata"
connection.Open()
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
ds.DataSetName = "Schedule"
ds.WriteXml(directory)
ds.Clear()
sql = "select * from costdata"
adapter = New SqlDataAdapter(sql, connection)
adapter.Fill(ds)
ds.WriteXml(directory)
I have tried adding it all to the same data set by calling the SQL queries at once, but that doesn't help to separate them in the XML -- it groups them in the same node.
I'm open to a different method if anyone has a good suggestion.
You've defined directory as a string, so ds.WriteXml will (create and) write to a file by that name.
Use a FileStream or XmlTextWriter instead.
The way that I write to .xml files (which works) is as follows
Private Sub AuthenticationContinuebtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AuthenticationContinuebtn.Click
On Error GoTo PasswordHandler
GlobalVariables.Username = Usernametxtbx.Text
GlobalVariables.Password = Passwordtxtbx.Text
GetUsernamePassword()
Close()
Exit Sub
PasswordHandler:
MsgBox("Incorrect password or username.")
End Sub
Private Sub UserAuthenticationWindow_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim FileName4 As String = "C:\Forte\UsernamePassword.xml"
Dim FileRead4 As XmlTextReader = New XmlTextReader("C:\Forte\UsernamePassword.xml")
'If statement to see if file exists.
If System.IO.File.Exists(FileName4) = True Then
Do While (FileRead4.Read)
Select Case FileRead4.NodeType
Case XmlNodeType.Text, XmlNodeType.Element
If FileRead4.Name = "Username" Then
FileRead4.Read()
Usernametxtbx.Text = FileRead4.Value
GlobalVariables.Username = Usernametxtbx.Text
End If
If FileRead4.Name = "Password" Then
FileRead4.Read()
Passwordtxtbx.Text = FileRead4.Value
GlobalVariables.Password = Passwordtxtbx.Text
End If
End Select
Loop
Else
MainBox.MainTextBox.AppendText(FileName4 & " could not be found. Settings are restored to defaults.")
MainBox.Logging(Date.Now & FileName4 & " could not be found. Settings are restored to defaults.")
End If
FileRead4.Close()
End Sub
Public Sub createNode3(ByVal Username As String, ByVal Password As String, ByVal writer As XmlTextWriter)
'On Error Resume Next
writer.WriteStartElement("Username_Password")
writer.WriteStartElement("Username")
writer.WriteString(Username)
writer.WriteEndElement()
writer.WriteStartElement("Password")
writer.WriteString(Password)
writer.WriteEndElement()
writer.WriteEndElement()
End Sub

Argument Exception - The path is not of a legal form (vb.net)

I'm currently having the most irritating error in a program i'm making and i would seriously appreciate any help or advice that could help me fix it. The part of the program that i'm having a problem with is a form that loads up a selected image into a picturebox and then saves it into an MS Access database upon the click of the 'save' button. When executing the "Browse_Click" event, it prompts you to search for an image location and loads it into a picturebox (pbImage). This bit works fine and successfully loads it into it picturebox. The problem i'm having is when i try to save the image to my access database, i get the following argument exception error "The path is not of a legal form".
As far as i know all my code is fully functional because it previously worked, however an hour or two ago this error suddenly started appearing.
The first section of code below is what is executed when i want to load the picture into the picture box. The section below that is the 'save' code.
Public Class Manage_Cottages
Dim imgName As String
Dim daImage As OleDbDataAdapter
Dim dsImage As DataSet
Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
Dim dlgImage As FileDialog = New OpenFileDialog()
dlgImage.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif"
If dlgImage.ShowDialog() = DialogResult.OK Then
imgName = dlgImage.FileName
Dim selectedFileName As String = dlgImage.FileName
txtPath.Text = selectedFileName
Dim newimg As New Bitmap(imgName)
pbImage.SizeMode = PictureBoxSizeMode.StretchImage
pbImage.Image = DirectCast(newimg, Image)
End If
dlgImage = Nothing
imgName = " "
End Sub'
Save code
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=..\Debug\CourseworkDatabase.mdb"
Dim CN As New OleDbConnection(cnString)
CN.Open()
If imgName <> "" Then
Dim fs As FileStream
fs = New FileStream(imgName, FileMode.Open, FileAccess.Read) <----- where the error occurs.
Dim picByte As Byte() = New Byte(fs.Length - 1) {}
fs.Read(picByte, 0, System.Convert.ToInt32(fs.Length))
fs.Close()
Dim strSQL As String
strSQL = "INSERT INTO Cottage_Details([Image]) values (" & " #Img)"
Dim imgParam As New OleDbParameter()
imgParam.OleDbType = OleDbType.Binary
imgParam.ParameterName = "Img"
imgParam.Value = picByte
Dim cmd As New OleDbCommand(strSQL, CN)
cmd.Parameters.Add(imgParam)
cmd.ExecuteNonQuery()
MessageBox.Show("Image successfully saved.")
cmd.Dispose()
CN.Close()
End If
End Sub
Also below is the first couple of lines of what's displayed in the immediate window (not sure whether it will be of any help to diagnose the problem)
A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll
System.Transactions Critical: 0 : http://msdn.microsoft.com/TraceCodes/System/ActivityTracing/2004/07/Reliability/Exception/UnhandledUnhandled exceptionAlphaHolidayCottages.vshost.exeSystem.ArgumentException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089The path is not of a legal form. at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength)
Thanks for your time and help, would be over the moon if someone could help me resolve the issue.
Chris
You set imgName to " " at the end of btnBrowse_Click, so when you save the file under btnSave_Click you are trying to save it to the file name " ".
Try removing imgName = " " at the end of btnBrowse_Click, or assign imgName a proper file name before you save it.

iTextSharp Form Field Not Displaying ampersands, &, with SetField

I'm having an issue with iTextSharp and a PDF form (form fields specifically) that I've spend nearly two days on that I am direly hoping someone has the answer to.
I have a PDF form that when I open it as a user I can enter ampersands, &, into form fields just fine. However, when I use iTextSharp to fill in a form field value using .SetField the ampersands disappear. I have tried using & (which actually causes all the text in the field to appear as blank), the unicode representation of &, not flattening the form, flattening the form, etc. all to no avail. I am not sure what the issue could be as I mentioned the form field can certainly accept commas and ampersands with it's default encoding.
Is there something i'm missing?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Using iText 4.1.2.0
GeneratePDF2()
End Sub
Private Sub GeneratePDF2()
''//The directory to output files to
Dim WorkingFolder = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim FormFileName = Path.Combine(WorkingFolder, "testfile.pdf")
Dim FinalFileName = Path.Combine(WorkingFolder, "Final.pdf")
''//The name of the form field that we are going to create
Dim TextFieldName = "form1[0].#subform[0].Table3[0].Row2[0].Line2_FullName_and_AddressofEmployer[0]"
Dim FieldValue As String = "Jonathan & Chris & Mark" ' Does Not Work
'Dim FieldValue As String = "Jonathan and Chris and Mark" ' Works
Dim Letter As RandomAccessFileOrArray
'Create a PDF reader object based on the PDF template
Dim PDFReader As PdfReader
'Dim BAOS1 As MemoryStream
Dim Stamper As PdfStamper
Dim BAOS As MemoryStream = New MemoryStream()
Dim Copy As PdfCopyFields = New PdfCopyFields(BAOS)
Dim FormFilePath As String = FormFileName
Letter = New RandomAccessFileOrArray(FormFilePath)
'Create a PDF reader object based on the PDF template
PDFReader = New PdfReader(Letter, Nothing)
Dim BAOS1 As MemoryStream = New MemoryStream()
Stamper = New PdfStamper(PDFReader, BAOS1)
Dim FormFields As AcroFields = Stamper.AcroFields
'Set field value
FormFields.SetField(TextFieldName, FieldValue)
'Rename field after setting value
Dim RenamedFormFieldName As String
RenamedFormFieldName = String.Concat(Guid.NewGuid().ToString, "_", Guid.NewGuid().ToString)
FormFields.RenameField(TextFieldName, RenamedFormFieldName)
' flatten the form to remove editting options, set it to false
' to leave the form open to subsequent manual edits
Stamper.FormFlattening = True
' close the pdf
Stamper.Close()
'This could be the correct location
Copy.AddDocument(New PdfReader(BAOS1.ToArray))
Copy.Writer.CloseStream = False
Copy.Close()
PDFReader = New PdfReader(BAOS.ToArray())
Stamper = New PdfStamper(PDFReader, New FileStream(FinalFileName, FileMode.Create))
Stamper.FormFlattening = True
Stamper.Close()
End Sub
I'm unable to reproduce your problem, I'm using version 5.1.1.0. Below is sample code that creates a PDF, adds a field to it and then sets the field's value to This & that. (Its in three steps because I don't know how to add a field during the initial PDF creation.) I also tried manually creating a PDF in Acrobat and I was able to set the field to an ampersand just fine, too. Are you creating the form field in iTextSharp or another program? Can you post that PDF somewhere so we can look at it?
Option Explicit On
Option Strict On
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
''//The directory to output files to
Dim WorkingFolder = My.Computer.FileSystem.SpecialDirectories.Desktop
''//This sample code creates a base PDF, then adds a text field to it and finally sets the field value.
''//These filenames represent those three actions
Dim BaseFileName = Path.Combine(WorkingFolder, "Base.pdf")
Dim FormFileName = Path.Combine(WorkingFolder, "Form.pdf")
Dim FinalFileName = Path.Combine(WorkingFolder, "Final.pdf")
''//The name of the form field that we are going to create
Dim TextFieldName = "Text1"
''//Create our base PDF
Using FS As New FileStream(BaseFileName, FileMode.Create, FileAccess.Write, FileShare.Read)
Using Doc As New Document(PageSize.LETTER)
Using W = PdfWriter.GetInstance(Doc, FS)
Doc.Open()
Doc.NewPage()
Doc.Add(New Paragraph("This is my form"))
Doc.Close()
End Using
End Using
End Using
''//Add our form field
Using FS As New FileStream(FormFileName, FileMode.Create, FileAccess.Write, FileShare.Read)
Dim R1 = New PdfReader(BaseFileName)
Using S As New PdfStamper(R1, FS)
Dim F As New TextField(S.Writer, New Rectangle(50, 50, 500, 100), TextFieldName)
S.AddAnnotation(F.GetTextField(), 1)
S.Close()
End Using
End Using
''//Set the field value to text with an ampersand
Using FS As New FileStream(FinalFileName, FileMode.Create, FileAccess.Write, FileShare.Read)
Dim R2 = New PdfReader(FormFileName)
Using S As New PdfStamper(R2, FS)
S.AcroFields.SetField(TextFieldName, "This & that")
S.Close()
End Using
End Using
Me.Close()
End Sub
End Class
EDIT
I just tried it with the PDF you sent and its working just fine for me. Below is the full code that I ran. Here's the PDF it made. Are you sure you're not doing something else to the PDF (I don't know what.) If you create a brand new Windows Applications and use the below code against 5.1.1.0 does it work for you?
Option Explicit On
Option Strict On
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
''//The directory to output files to
Dim WorkingFolder = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim FormFileName = Path.Combine(WorkingFolder, "testfile.pdf")
Dim FinalFileName = Path.Combine(WorkingFolder, "Final.pdf")
''//The name of the form field that we are going to create
Dim TextFieldName = "form1[0].#subform[0].Table3[0].Row2[0].Line2_FullName_and_AddressofEmployer[0]"
''//Set the field value to text with an ampersand
Using FS As New FileStream(FinalFileName, FileMode.Create, FileAccess.Write, FileShare.Read)
Dim R2 = New PdfReader(FormFileName)
Using S As New PdfStamper(R2, FS)
S.AcroFields.SetField(TextFieldName, "Chris & Mark")
S.FormFlattening = True
S.Close()
End Using
End Using
Me.Close()
End Sub
End Class
Had a similar case where German umlauts entered by the user in the application were not showing in the PDF. Turned out to be a font issue.
Had to ship our own fonts with the application (Liberation package to get cross-platform Arial-style) and doing this (it's Java):
BaseFont baseFont = BaseFont.createFont(FONT_FILE, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
acroFields.setFieldProperty(fieldName, "textfont", baseFont, null);