How to printing a document in silverlight - silverlight

I've written an application web in silverlight for view Tiff files.
I send an absolut uri of Tiff files to silverlight app and it view /zooming or download a file.
I print the tiff with PrintDocument library, but the file sent to printer is very large (500Mb for 100kb of tiff file).
Now this is my code for printing:
Protected Sub pd_PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Try
If (PrintPageCount = 0) Then
PrintPageCount = ImageTiff.NumberOfDirectories
PrintCurrPage = 0
End If
If (PrintCurrPage < PrintPageCount) Then
ImageTiff.SetDirectory(PrintCurrPage)
Dim cnv As New Canvas With
{
.Width = 840,
.Height = 1180,
.Background = New ImageBrush With {
.ImageSource = GetWritableBmp(ImageTiff, larghezza, altezza),
.Stretch = Stretch.Fill
}
}
ev.PageVisual = cnv
PrintCurrPage += 1
ev.HasMorePages = True
Else
ev.HasMorePages = False
End If
Catch ex As Exception
MessageBox.Show("Errore handler:" & ex.Message & vbCrLf & ex.StackTrace)
End Try
End Sub
And my event handler for print button
Private Sub ButtonPrint_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonPrint.Click
Try
Dim pdoc As New PrintDocument()
AddHandler pdoc.PrintPage, AddressOf Me.pd_PrintPage
pdoc.Print(Uri.AbsoluteUri)
Catch ex As Exception
MessageBox.Show("Errore:" & ex.Message)
End Try
End Sub
I want to send print of "http://www.mysite.it/tifffiles/mytif.tif" directly to printer, this is possible?

In Silverlight 4 and above, Microsoft extended support for printing documents. See http://msdn.microsoft.com/en-us/library/ee671023(v=VS.95).aspx. If you can covert the TIFF to a XAML document or Bitmap it may make your process easier.

Related

saved image file showing twice when I refresh combobox list

So I am working with blobs in visual basic, and I'm saving image files to a database. When I save them I have their name.jpg showing up in a combobox, but when I save another image and it refreshes the list, the name of the previous image shows twice. I'm not sure how I managed that. I am new to this so don't look down on me too much!
When the button on my form is clicked:
Private Sub btnSaveBlob_Click(sender As Object, e As EventArgs) Handles btnSaveBlob.Click
SaveBlobToDatabase()
refreshBlobList()
End Sub
My methods:
Private Sub SaveBlobToDatabase()
GetCompleteFilePath()
Dim BLOB() As Byte
Dim FileStream As New IO.FileStream _
(CompleteFilePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim reader As New IO.BinaryReader(FileStream)
BLOB = reader.ReadBytes(CInt(My.Computer.FileSystem.GetFileInfo(CompleteFilePath).Length))
FileStream.Close()
reader.Close()
Dim SaveDocCommand As New SqlCommand
SaveDocCommand.Connection = conn
SaveDocCommand.CommandText = "INSERT INTO DocumentStorage" &
"(FileName, DocumentFile)" &
"VALUES (#FileName, #DocumentFile)"
Dim FileNameParameter As New SqlParameter("#FileName", SqlDbType.NChar)
Dim DocumentFileParameter As New SqlParameter("#DocumentFile", SqlDbType.Binary)
SaveDocCommand.Parameters.Add(FileNameParameter)
SaveDocCommand.Parameters.Add(DocumentFileParameter)
FileNameParameter.Value =
CompleteFilePath.Substring(CompleteFilePath.LastIndexOf("\") + 1)
DocumentFileParameter.Value = BLOB
Try
SaveDocCommand.Connection.Open()
SaveDocCommand.ExecuteNonQuery()
MessageBox.Show(FileNameParameter.Value.ToString &
"saved to database.", "BLOB Saved!", MessageBoxButtons.OK,
MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message, "Save Failed",
MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
SaveDocCommand.Connection.Close()
End Try
End Sub
Private Sub refreshBlobList()
Dim GetBlobListCommand As New SqlCommand("SELECT FileName FROM DocumentStorage", conn)
Dim reader As SqlDataReader
GetBlobListCommand.Connection.Open()
reader = GetBlobListCommand.ExecuteReader
While reader.Read
lstBlob.Items.Add(reader(0))
End While
reader.Close()
GetBlobListCommand.Connection.Close()
If lstBlob.Items.Count > 0 Then
lstBlob.SelectedIndex = 0
End If
End Sub
Objects in .net that show you a .Dispose method should be disposed. They have unmanaged code and need to properly release things. Connections, Commands, Streams, and Readers fall into this group. Luckily .net has provided Using...End Using blocks that handle this for us even if there is an error. For this reason, these objects should be kept local to the methods where they are used.
As much as possible, methods should perform a single task. I pulled out the code to create the byte array to a separate Function. I also split the data access code from the user interace code. You may want to put the data access code in a separate class. This would come in handy if you want to change to a web app, for example.
In the data access code:
You can pass the connection string directly to the constructor of the connection. Likewise, pass the CommandText and Connection directly to the constructor of the command. The .Add method of the .Parameters collection will create a new parameter from the name and datatype passed to it. You can also set the value on the same line.
Private ConStr As String = "Your connection string"
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim RowsAdded As Integer
Try
RowsAdded = SaveBlobToDatabase()
Catch ex As Exception
MessageBox.Show(ex.Message, "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
If RowsAdded = 1 Then
MessageBox.Show("Saved to database.", "BLOB Saved!", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Private Function SaveBlobToDatabase() As Integer
Dim RowsAdded As Integer
Dim CompleteFilePath As String = GetCompleteFilePath()
Using conn As New SqlConnection(ConStr),
SaveCommand As New SqlCommand("INSERT INTO DocumentStorage(FileName, DocumentFile) VALUES(#FileName, #DocumentFile);", conn)
SaveCommand.Parameters.Add("#FileName", SqlDbType.NChar).Value = Path.GetFileName(CompleteFilePath) 'Requires Imports System.IO
SaveCommand.Parameters.Add("#DocumentFile", SqlDbType.Binary).Value = GetByteArrayFromFile(CompleteFilePath)
conn.Open()
RowsAdded = SaveCommand.ExecuteNonQuery()
End Using
Return RowsAdded
End Function
Private Function GetByteArrayFromFile(FullPath As String) As Byte()
Dim Blob() As Byte
Using FileStream As New IO.FileStream(FullPath, IO.FileMode.Open, IO.FileAccess.Read),
reader As New IO.BinaryReader(FileStream)
Blob = reader.ReadBytes(CInt(My.Computer.FileSystem.GetFileInfo(FullPath).Length))
End Using
Return Blob
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
lstBlob.Items.Clear()
lstBlob.DataSource = refreshBlobList()
lstBlob.DisplayMember = "FileName"
If lstBlob.Items.Count > 0 Then
lstBlob.SelectedIndex = 0
End If
End Sub
Private Function refreshBlobList() As DataTable
Dim dt As New DataTable
Using conn As New SqlConnection(ConStr),
GetBlobListCommand As New SqlCommand("SELECT FileName FROM DocumentStorage", conn)
conn.Open()
dt.Load(GetBlobListCommand.ExecuteReader)
End Using
Return dt
End Function

LocalReport in WinForms Font Squashed (compressed)

I have a Winforms application that has suddenly begun to incorrectly render RDLCs to both physical printers and Print To PDF. It is targeting .NET 4.5.2 and began to show this after an update to 4.7.2 last week. I am able to reproduce the issue on my testbed system as well.
Examples:
Correctly printed:
Incorrectly printed:
I am rendering the RDLC into a MemoryStream and passing that to a PrintDocument.
I've changed the DPI of the PrintDocument and tried different Fonts in the RDLC
Any help or a point in the right direction would be great.
EDIT:
Private Sub Export()
Dim RL As PageLayout = CType(_RenderLayout, PageLayout)
Dim deviceInfo As String = RL.GetDeviceInfo
Dim warnings() As Warning = Nothing
_streams = New List(Of Stream)()
_report.Render("Image", deviceInfo, AddressOf CreateStream, warnings)
Dim exportStream As Stream
For Each exportStream In _streams
exportStream.Position = 0
Next
End Sub
Private Function CreateStream(ByVal name As String, ByVal fileNameExtension As String, ByVal encoding As Encoding,
ByVal mimeType As String, ByVal willSeek As Boolean) As Stream
Dim stream As Stream = New MemoryStream
_streams.Add(stream)
_streamCount += 1
Return stream
End Function
Private Sub PrintPage(ByVal sender As Object, ByVal ev As PrintPageEventArgs)
Dim pageImage As New Metafile(_streams(_currentPageIndex))
ev.Graphics.TextRenderingHint = Drawing.Text.TextRenderingHint.ClearTypeGridFit
ev.Graphics.DrawImage(pageImage, ev.PageBounds)
_currentPageIndex += 1
ev.HasMorePages = (_currentPageIndex < _streams.Count)
End Sub

WPF - destroy page after unloaded has run

In a WPF app we have the need to sometimes create a new tab that contains a Page inside a Frame..
Once the page has been opened (initialised once) it still seems to stay in navigation history and attempts to load data that may not be relevant at the time.
I have tried a myriad of methods including NavigationService.RemoveBackEntry, but it still persists :-(
This is an example of how the tab/page are opened
Private Sub CashFlow_Edit(sender As Object, e As RoutedEventArgs)
Try
Dim DGV As DGVx = ReportsCashFlow_Grid.FindName("CashFlow_DGV")
e.Handled = True
IsNewRecord = False
If DGV.SelectedItems.Count = 1 Then
Dim row As System.Data.DataRowView = DGV.SelectedItems(0)
Form_ID = row("ID")
Dim vName As String = row("Name")
Dim vTab As STC_Tabx = Application.Current.MainWindow.FindName(TabName)
Dim TabControl As STCx = Application.Current.MainWindow.FindName("AccountingReports_TabControl")
If Not vTab Is Nothing Then
vTab.Close()
End If
Dim MCFrame As New Frame
Dim MCTab As New STC_Tabx
With MCTab
.Name = TabName
.Header = " " & vName & " "
.ImageSource = ReturnImageAsString("Edit.png", 16)
.CloseButtonVisibility = DevComponents.WpfEditors.eTabCloseButtonVisibility.Visible
.TabToolTip = "View or edit the " & vName & " template"
.Content = MCFrame
End With
RemoveHandler MCTab.Closing, AddressOf TabControl_TabClosing
AddHandler MCTab.Closing, AddressOf TabControl_TabClosing
Dim vGrid As Grid = Application.Current.MainWindow.FindName("MainGrid_Accounting")
RegisterControl(vGrid, MCTab)
TabControl.Items.Add(MCTab)
Dim MCPage As New ReportCashFlow_Page
MCFrame.NavigationService.Navigate(MCPage)
LoadedTabs(TabName)
MCTab.IsSelected = True
End If
Catch ex As Exception
EmailError(ex)
End Try
End Sub
To remove all the back entries do something like:
while(NavigationService.CanGoBack)
{
NavigationService.RemoveBackEntry();
}
It's not the clean bit of code I would like, but it works - create a global Boolean - when the sub that opens the tab/page is called it's set to true and the loading event will only run the loading code if this is true - it's set to false at the end.
Private Sub ReportCashFlow_Page_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
Try
If IsNewTab = False Then
Exit Sub
End If
'Run all the loading code here
Catch ex As Exception
EmailError(ex)
Finally
IsNewTab = False
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, CType(Sub() CashFlow_LoadBudget(), SendOrPostCallback), Nothing)
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, CType(Sub() ToggleReserve(), SendOrPostCallback), Nothing)
End Try
End Sub

VB.NET Winforms render report as pdf giving "Error occurred during local report processing"

Hello I am just trying to get my head round reporting in VB.NET.
The report view preview is working fine so it doesn't appear to be a problem with the report itself but the render as pdf is giving "Error occurred during local report processing", inner exception is giving "Error occurred during report processing"
I'm obviously missing something but can't see what.
Be grateful if anybody could help shed any light on this please.
Private Sub ExportToPDFToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportToPDFToolStripMenuItem1.Click
Try
Dim viewer As New Microsoft.Reporting.WinForms.ReportViewer
Dim report = New Microsoft.Reporting.WinForms.LocalReport
viewer.LocalReport.ReportEmbeddedResource = "ECUWMS.10day.rdlc"
viewer.ProcessingMode = ProcessingMode.Local
Dim rpJob As New ReportParameter
rpJob.Name = "JobNo"
rpJob.Values.Add("0000030")
viewer.LocalReport.SetParameters(New ReportParameter() {rpJob})
viewer.RefreshReport()
Dim reportinfo As Byte() = viewer.LocalReport.Render("PDF") ' --> Errors here.
Dim SFD As New SaveFileDialog
SFD.Filter = "PDF Files(*.PDF) | *.pdf"
If SFD.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim newfile As New FileStream(SFD.FileName, FileMode.Create, FileAccess.Write)
newfile.Write(reportinfo, 0, reportinfo.Length)
newfile.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK)
End Try
End Sub
As 'suggested' in the ex.InnerException.InnerException.Message you need to provide a ReportDataSource named dsJobs to your LocalReport.
Thanks for help. I think this is fairly close to finished, I also like the idea of being able to move the filtering to the dataset rather than the report.
The sandbox thing appears to be a gotcha. Without clearing this VS throws an exception.
This logic also works for Excel and Word by just changing the sfd and outputs.
Here is some code if it helps somebody
Private Sub ExportToPDFToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportToPDFToolStripMenuItem1.Click
Dim viewer As New Microsoft.Reporting.WinForms.ReportViewer
Dim report = New Microsoft.Reporting.WinForms.LocalReport
Try
Me.Tblsop_hTableAdapter.Fill(Me.SqlecuDataSet.tblsop_h)
viewer.LocalReport.ReportEmbeddedResource = "ECUWMS.10day.rdlc"
viewer.ProcessingMode = ProcessingMode.Local
viewer.LocalReport.Refresh()
Dim dsJobs As New sqlecuDataSet
Dim ta As sqlecuDataSetTableAdapters.tblsop_hTableAdapter = Tblsop_hTableAdapter
ta.Fill(dsJobs.tblsop_h)
Dim repData As New ReportDataSource
repData.Name = "dsjobs"
repData.Value = dsJobs.tblsop_h
viewer.LocalReport.DataSources.Clear()
viewer.LocalReport.DataSources.Add(repData)
Dim rpJob As New ReportParameter
rpJob.Name = "JobNo"
rpJob.Values.Add("0000030")
viewer.LocalReport.SetParameters(New ReportParameter() {rpJob})
viewer.RefreshReport()
Dim reportinfo As Byte() = viewer.LocalReport.Render("PDF")
Dim SFD As New SaveFileDialog
SFD.Filter = "PDF Files(*.PDF) | *.pdf"
If SFD.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim newfile As New FileStream(SFD.FileName, FileMode.Create, FileAccess.Write)
newfile.Write(reportinfo, 0, reportinfo.Length)
newfile.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK)
MessageBox.Show(ex.InnerException.Message, "Error", MessageBoxButtons.OK)
MessageBox.Show(ex.InnerException.InnerException.Message, "Error", MessageBoxButtons.OK)
End Try
Viewer.LocalReport.ReleaseSandboxAppDomain()
End Sub

Upload Progressbar with FtpWebRequest

I have a program that uploads files to our server when they are dropped over the form, to make it easy for our customers to get large files to us.
I have it mostly working, but I want to have a progress bar so that the user knows it's working, instead of having it just sit there for 5 minutes while the files upload quietly in the background.
I would be happy to just have the progress bar pulse so it looks the program is working, and not frozen. If I can show actual status then that would be better.
My code:
Private Sub Grid1_Drop(sender As System.Object, e As System.Windows.DragEventArgs) Handles Grid1.Drop
Dim sFileInfo As System.IO.FileInfo
Dim sStatus As String = ""
If e.Data.GetDataPresent("FileDrop") Then
Try
Dim theFiles() As String = CType(e.Data.GetData("FileDrop", True), String())
For Each file As String In theFiles
sFileInfo = New System.IO.FileInfo(file)
If UploadFile(txtUsername.Text, sFileInfo) Then
lstFileList.Items.Add(file & " - Uploaded")
Else
lstFileList.Items.Add(file & " - Upload Failed")
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
Public Function UploadFile(ByVal User As String, ByVal oFile As FileInfo) As Boolean
Dim ftpRequest As FtpWebRequest
Dim ftpResponse As FtpWebResponse
Try
ftpRequest = CType(FtpWebRequest.Create(Base + User + "/" + oFile.Name), FtpWebRequest)
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile
ftpRequest.Proxy = Nothing
ftpRequest.UseBinary = True
ftpRequest.Credentials = Cred
ftpRequest.KeepAlive = KeepAlive
ftpRequest.EnableSsl = UseSSL
If UseSSL Then ServicePointManager.ServerCertificateValidationCallback = New RemoteCertificateValidationCallback(AddressOf ValidateServerCertificate)
Dim fileContents(oFile.Length) As Byte
Using fr As FileStream = oFile.OpenRead
fr.Read(fileContents, 0, Convert.ToInt32(oFile.Length))
End Using
Using writer As Stream = ftpRequest.GetRequestStream
writer.Write(fileContents, 0, fileContents.Length)
End Using
ftpResponse = CType(ftpRequest.GetResponse, FtpWebResponse)
ftpResponse.Close()
ftpRequest = Nothing
Return True
Catch ex As WebException
Return False
End Try
End Function
Have a look at the background worker class. http://msdn.microsoft.com/en-us/library/cc221403(v=vs.95).aspx which will free up your ui so you can add in a progress bar control and have it animate while your files are being uploaded

Resources