vb.net - PrintDialog not appearing - vb.net

I'm almost done with my system. All I need to finish is the print process. Sadly, the print dialog is not appearing.
Here's the code for the printing process
Private Sub PrintReceipt()
Dim printdialog As New PrintDialog
Dim printdocument As New Printing.PrintDocument
printdialog.Document = printdocument
AddHandler printdocument.PrintPage, AddressOf printdocument_printPage
Dim result As DialogResult
If (result = DialogResult.OK) Then
printdocument.Print()
End If
End Sub
There is nothing wrong with the printdocument_printpage, which is basically just what it will be printing, yet, since printing hasn't even begun, I won't bother putting it here unless requested.
I want the said dialog to appear after the transaction has been saved. which its not doing for some reason. And here's the code for the save transaction.
Dim payment As New Payment
mydbcon = New MySqlConnection
mydbcon.ConnectionString = "server=localhost;userid=root;password=;database=sdudb"
Dim reader As MySqlDataReader
If e.PaymentSuccess = True Then
Try
mydbcon.Open()
Dim Query As String
Query = "select * from itemstored"
COMMAND = New MySqlCommand(Query, mydbcon)
reader = COMMAND.ExecuteReader()
While reader.Read
insertTranscation(reader.GetString("itemname"), reader.GetString("price"))
End While
DeleteItemStored()
PrintReceipt()
reader.Close()
reader.Dispose()
mydbcon.Close()
Catch ex As Exception
MessageBox.Show(ex.StackTrace)
End Try
End If
Ignore the mysql here. It's not the main problem.

The dialog will not show if you don't tell it to. You've forgotten to call printdialog.ShowDialog() in your code, and you also never set result to anything before checking it.
It's a simple fix:
Dim result As DialogResult = printdialog.ShowDialog()

Related

Show image in vb.net

I'm trying to show a saved image in SQL Server but it gives me an error that says "parameter is not valid".
While oDataReader.Read()
TextBox1.Text = oDataReader("nombre")
Dim imagenbyte As Byte()
imagenbyte = oDataReader("imagen")
Dim mStream As New IO.MemoryStream()
mStream.Write(imagenbyte, 0, Convert.ToInt32(imagenbyte.Length))
Dim bm As Bitmap = New Bitmap(mStream, True)
PictureBox1.Image = bm
End While
You can consolidate that code down to this:
While oDataReader.Read()
TextBox1.Text = oDataReader("nombre")
Dim mStream As New IO.MemoryStream(oDataReader("imagen"))
PictureBox1.Image = Image.FromStream(mStream)
End While
The main fix here is using Image instead of Bitmap. And if you know you'll only have one record, you should change While to If. If you might have more than one record, you need to completely re-think some things in your user interface.

Skipping a line of code if an image isn't selected

If a user selects an image it will save the image as per the below code:
PictureBox1.Image.Save(PicFile, System.Drawing.Imaging.ImageFormat.Jpeg)
Now if the user decides not to select an image, is there a way to skip this code? I currently get the following error:
Additional information: Object reference not set to an instance of an object.
This is what I've tried:
Dim opf As New OpenFileDialog
opf.Filter = "Choose Image(.jpg;.png;*.gif)|*.jpg;*.png;*.gif"
If opf.ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(opf.FileName)
End If
Try
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim img As Byte()
img = ms.ToArray()
DataGridView1.Rows.Add(img)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
Now if the user decides not to select an image, is there a way to skip this code?
If by this you mean the user selects Cancel, then yes. Simply place the Try[...]Catch block into your If statement and it will only attempt the code if the user selects Open.
Something like this:
Dim opf As New OpenFileDialog
opf.Filter = "Choose Image(.jpg;.png;*.gif)|*.jpg;*.png;*.gif"
If opf.ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(opf.FileName)
Try
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim img As Byte()
img = ms.ToArray()
DataGridView1.Rows.Add(img)
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
End If
If you only wanted to skip certain bits of code you could do a check on opf.FileName. As an example:
If opf.FileName <> "" Then
PictureBox1.Image = Image.FromFile(opf.FileName)
End If

VB How do i recall a line of text from a text file, based on user selection?

This is what i have so far...
Dim Test As String = "C:\test.txt"
Dim User As String
Console.WriteLine("What user password would you like?")
User = Console.ReadLine().ToLower
Dim objReader As New System.IO.StreamReader(Test)
While Not objReader.EndOfStream
If User.Contains("Admin1") Then
Console.WriteLine(objReader.ReadLine())
End If
End While
objReader.Close()
I'm not sure whether or not there is something needed to go in the brackets of the " (objReader.ReadLine() " If anyone could help that would be fantastic, thanks.
Here's what you want...
Using sr As New StreamReader("C:\test.txt")
Dim Line As String = sr.ReadLine()
While Line IsNot Nothing
If Line.Contains("Admin1") Then
Console.WriteLine(Line)
End If
Line = sr.ReadLine()
End While
End Using
The "Using" block ensures that the StreamReader object is automatically closed and disposed without you needing to worry about it.

SqlFileStream writing in separate thread not working

Learning and testing using Sql FILESTREAM for a web app. A client uploads a large file form the web page which takes 'X' time and when fully uploaded shows 100% complete. However, very large files also take time for SqlFileStream to write to the file system so I want to spin off a thread to complete that part. The code I've got seems to work fine but no data ends up in the filestream file.
I'm wrapping the initial record creation in it's own transaction scope and using a separate transaction scope in the thread. In the threaded routine I have the appropriate PathName() and TransactionContext but I assume I'm missing something while using a thread.
I've commented out the normal SqlFileStream call which works fine. Can you see anything wrong with what I'm doing here?
Public Function StoreFileStream()
Dim json As New Dictionary(Of String, Object)
Dim parms As New FileStreamThreadParameters
If HttpContext.Current.Request.Files.Count > 0 Then
Dim file As HttpPostedFile = HttpContext.Current.Request.Files(0)
If "contentType" <> String.Empty Then
Dim fs As Stream = file.InputStream
Dim br As New BinaryReader(fs)
Dim noBytes As New Byte()
Try
Dim filePath As String = ""
Dim trxContext As Byte() = {}
Dim baseFileId As Integer
Using trxScope As New TransactionScope
Using dbConn As New SqlConnection(DigsConnStr)
Using dbCmd As New SqlCommand("ADD_FileStreamFile", dbConn)
dbConn.Open()
Using dbRdr As SqlDataReader = dbCmd.ExecuteReader(CommandBehavior.SingleRow)
dbRdr.Read()
If dbRdr.HasRows Then
filePath = dbRdr("Path")
trxContext = dbRdr("TrxContext")
baseFileId = dbRdr("BaseFileID")
End If
dbRdr.Close()
End Using
' Code below writes to file, but trying to offload this to a separate thread so user is not waiting
'Using dest As New SqlFileStream(filePath, trxContext, FileAccess.Write)
' fs.CopyTo(dest, 4096)
' dest.Close()
'End Using
End Using
dbConn.Close()
End Using
trxScope.Complete()
End Using ' transaction commits here, not in line above
parms.baseFileId = baseFileId
parms.fs = New MemoryStream
fs.CopyTo(parms.fs)
Dim fileUpdateThread As New Threading.Thread(Sub()
UpdateFileStreamThreaded(parms)
End Sub)
fileUpdateThread.Start()
json.Add("status", "success")
Catch ex As Exception
Elmah.ErrorSignal.FromCurrentContext().Raise(ex)
json.Add("status", "failure")
json.Add("msg", ex.Message)
json.Add("procedure", System.Reflection.MethodBase.GetCurrentMethod.Name)
End Try
Else
json.Add("status", "failure")
json.Add("msg", "Invalid file type")
json.Add("procedure", System.Reflection.MethodBase.GetCurrentMethod.Name)
End If
End If
Return json
End Function
Public Class FileStreamThreadParameters
Public Property baseFileId As Integer
Public fs As Stream
End Class
Private Sub UpdateFileStreamThreaded(parms As FileStreamThreadParameters)
Dim filePath As String = ""
Dim trxContext As Byte() = {}
Try
Using trxScope As New TransactionScope
Using dbConn As New SqlConnection(DigsConnStr)
Using dbCmd As New SqlCommand("SELECT FileBytes.PathName() 'Path', GET_FILESTREAM_TRANSACTION_CONTEXT() 'TrxContext' FROM FileStreamFile WHERE Id = " & parms.baseFileId, dbConn)
dbConn.Open()
Using dbRdr As SqlDataReader = dbCmd.ExecuteReader(CommandBehavior.SingleRow)
dbRdr.Read()
If dbRdr.HasRows Then
filePath = dbRdr("Path")
trxContext = dbRdr("TrxContext")
End If
dbRdr.Close()
Using dest As New SqlFileStream(filePath, trxContext, FileAccess.Write)
parms.fs.CopyTo(dest, 4096)
dest.Close()
End Using
End Using
End Using
dbConn.Close()
End Using
trxScope.Complete()
End Using
Catch ex As Exception
'Elmah.ErrorSignal.FromCurrentContext().Raise(ex)
End Try
End Sub
Obviously this is a complex issue. I actually got it to work with the code below. However I eventually abandoned using SQL FILESTREAM altogether due to too much complexity in getting it all set up.
This is an existing web application with the sql server on a different box. After I got the filestreaming to work the next hurdle was authentication setup. Filestream requires Integrated Security on your connection string. Even with windows authentication on our Intranet app, I could not get the web app to use the windows credentials when connecting to the database. It always seemed to use the computer name or the app pool service. I tried many many examples I found on the net and here to no avail. Even if I got that to work then I would want to use and Active Directory group over individual logins which looked to be another hurdle.
This app stores documents in a varbinary column so that full text search can be enabled at some point. The issue was with large files which are generally pictures or videos. Since you can't search text on those anyway the strategy now is to store those on the file system and all other searchable docs (.docx, .pptx, etc) will still be stored in the varbinary. I'm actually sad that I could not get filestream to work as it seems like the ideal solution. I'll come back to it some day but it really should not be so frickin complicated. :-(
The code I got working is:
Dim filePath As String = ""
Dim trxContext As Byte() = {}
Dim baseFileId As Integer
Using trxScope As New TransactionScope
Using dbConn As New SqlConnection(DigsFSConnStr)
Using dbCmd As New SqlCommand("NEW_FileStreamBaseFile", dbConn)
dbCmd.CommandType = CommandType.StoredProcedure
dbCmd.Parameters.AddWithValue("#Title", fileDesc)
dbCmd.Parameters.AddWithValue("#Summary", summary)
dbCmd.Parameters.AddWithValue("#Comments", comments)
dbCmd.Parameters.AddWithValue("#FileName", uploadedFileName)
dbCmd.Parameters.AddWithValue("#ContentType", contentType)
dbCmd.Parameters.AddWithValue("#FileExt", ext)
'dbCmd.Parameters.AddWithValue("#FileBytes", noBytes) ' now that were offloading the file byte storage to a thread
dbCmd.Parameters.AddWithValue("#UploadedByResourceID", uploadedByResourceID)
dbCmd.Parameters.AddWithValue("#UploadedByShortName", uploadedByShortName)
dbCmd.Parameters.AddWithValue("#FileAuthor", fileAuthor)
dbCmd.Parameters.AddWithValue("#TagRecID", tagRecID)
dbCmd.Parameters.AddWithValue("#UserID", samAccountName)
dbCmd.Parameters.AddWithValue("#FileDate", fileDate)
dbCmd.Parameters.AddWithValue("#FileType", fileType)
dbCmd.Parameters.AddWithValue("#FileTypeRecID", fileTypeRecId)
' Save to file system too for xod conversion
file.SaveAs(HttpContext.Current.Server.MapPath("~/files/uploaded/") & uploadedFileName)
dbConn.Open()
Using dbRdr As SqlDataReader = dbCmd.ExecuteReader(CommandBehavior.SingleRow)
dbRdr.Read()
If dbRdr.HasRows Then
filePath = dbRdr("Path")
trxContext = dbRdr("TrxContext")
json.Add("baseFileId", dbRdr("BaseFileID"))
virtualFileRecId = dbRdr("VirtualFileRecID")
dbStatus = dbRdr("status")
If dbStatus = "failure" Then
json.Add("msg", dbRdr("msg"))
End If
End If
dbRdr.Close()
End Using
' Prepare and start Task thread to write the file
If dbStatus = "success" Then
bytes = br.ReadBytes(fs.Length)
Dim task As New System.Threading.Tasks.Task(
Sub()
UpdateNewFileStreamBytes(virtualFileRecId, bytes)
End Sub)
task.Start()
json.Add("status", "success")
Else
json.Add("status", "failure")
End If
End Using
dbConn.Close()
End Using
trxScope.Complete()
End Using ' transaction commits here, not in line above
With the task procedure of:
Private Sub UpdateNewFileStreamBytes(virtualFileRecId As Integer, fileBytes As Byte())
Dim filePath As String = ""
Dim trxContext As Byte() = {}
Try
Using trxScope As New TransactionScope
Using dbConn As New SqlConnection(DigsFSConnStr)
Using dbCmd As New SqlCommand("UPD_FileStreamBaseFile", dbConn)
dbCmd.CommandType = CommandType.StoredProcedure
dbCmd.Parameters.AddWithValue("#VirtualFileRecID", virtualFileRecId)
dbConn.Open()
Using dbRdr As SqlDataReader = dbCmd.ExecuteReader(CommandBehavior.SingleRow)
dbRdr.Read()
If dbRdr.HasRows Then
filePath = dbRdr("Path")
trxContext = dbRdr("TrxContext")
End If
dbRdr.Close()
Using dest As New SqlFileStream(filePath, trxContext, FileAccess.Write)
dest.Write(fileBytes, 0, fileBytes.Length)
dest.Close()
End Using
End Using
End Using
dbConn.Close()
End Using
trxScope.Complete()
End Using
Catch ex As Exception
Elmah.ErrorSignal.FromCurrentContext().Raise(ex)
End Try

SaveFileDialog.OpenFile() IndexOutofRangeException

I recently wrote some code related to a menu strip bar, there is an option contains OpenFile, SaveFile and Exit etc. Following is the code.
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "ebd files (*.txt)|*.txt"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
Try
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
Dim sw As New StreamWriter(myStream)
sw.Flush()
sw.Close()
myStream.Close()
End If
Catch Ex As Exception
MessageBox.Show("Can't save file on disk: " & Ex.Message)
End Try
End If
another chunk of code exactly same but withou If statement, as following,
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "ebd files (*.txt)|*.txt"
saveFileDialog1.FilterIndex = 2
saveFileDialog1.RestoreDirectory = True
Try
myStream = saveFileDialog1.OpenFile()
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
Dim sw As New StreamWriter(myStream)
'some sw.WriteLine code here...
sw.Flush()
sw.Close()
myStream.Close()
End If
Catch Ex As Exception
MessageBox.Show("Can't save file on disk: " & Ex.Message)
End Try
The problem I have is the second piece of code, when it runs the system will throw out index out of range exception, How can I fix it without using a If statement? Is there any method to show the dialog window anyway? Anyone can give me clue on this index error message? Thanks!
Looking at the source code of OpenFile reveals the possible point of error
public Stream OpenFile()
{
IntSecurity.FileDialogSaveFile.Demand();
string str = base.FileNamesInternal[0];
if (string.IsNullOrEmpty(str))
{
throw new ArgumentNullException("FileName");
}
Stream stream = null;
new FileIOPermission(FileIOPermissionAccess.AllAccess, IntSecurity.UnsafeGetFullPath(str)).Assert();
try
{
stream = new FileStream(str, FileMode.Create, FileAccess.ReadWrite);
}
finally
{
CodeAccessPermission.RevertAssert();
}
return stream;
}
It seems that the code try to get the base.FileNamesInternal[0]; but if you don't show the dialog or choose a file name to save this internal array is probably empty.
I have tried to read the item at index zero in the property FileNames and I get the same error
string file = saveFileDialog1.FileNames(0) ' Index out of range....
I would like to hear from our WinForms more experienced posters if this is really what it seems
I guess I'm a bit confused about what you are trying to accomplish.
In the second example it seems you never 'show the dialog' ie saveFileDialog1.ShowDialog()
Thus the user cannot select a file/path
Then you attempt to use the file/path that has not been set
http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.openfile.aspx
If you just need to open an arbitrary file for write without showing the user the dialog why not just use File.Open() or something?
http://msdn.microsoft.com/en-us/library/b9skfh7s.aspx