Upload Progressbar with FtpWebRequest - wpf

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

Related

SSIS Script Task (Not working when Scheduled)

I have as SSIS Package with a script task. The task works great in Visual Studio 2015. However when I deploy the package and run it via SSMS the task script shows sucessful, but it runs extremely quickly and the file is not created. My code is farily simple (Grabs a file from a url, and saves it to a network location)
Public Sub Main()
Dim url, destination As String
destination = Dts.Variables("StagingPath").Value.ToString + Dts.Variables("DeliveryFile").Value.ToString
url = Dts.Variables("ReportURL").Value.ToString
'Delete staging file if it exists
Try
If IO.File.Exists(destination) Then IO.File.Delete(destination)
Dim result As Boolean = SaveFile(url, destination)
If result = True Then
Dts.TaskResult = ScriptResults.Success
Else
Dts.TaskResult = ScriptResults.Failure
End If
Catch ex As Exception
Dts.TaskResult = ScriptResults.Failure
End Try
End Sub
Protected Function SaveFile(ByVal url As String, ByVal localpath As String) As Boolean
Dim loRequest As System.Net.HttpWebRequest
Dim loResponse As System.Net.HttpWebResponse
Dim loResponseStream As System.IO.Stream
Dim loFileStream As New System.IO.FileStream(localpath, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Dim laBytes(256) As Byte
Dim liCount As Integer = 1
Try
loRequest = CType(System.Net.WebRequest.Create(url), System.Net.HttpWebRequest)
loRequest.Credentials = System.Net.CredentialCache.DefaultCredentials
loRequest.Timeout = 600000
loRequest.Method = "GET"
loResponse = CType(loRequest.GetResponse, System.Net.HttpWebResponse)
loResponseStream = loResponse.GetResponseStream
Do While liCount > 0
liCount = loResponseStream.Read(laBytes, 0, 256)
loFileStream.Write(laBytes, 0, liCount)
Loop
loFileStream.Flush()
loFileStream.Close()
'Success
SaveFile = True
Catch ex As Exception
SaveFile = False
End Try
End Function
Like I said, everything is fine when run locally but not when deployed to SSISDB Catalog. The url passed is to a local resource on our SSRS Server, that is a pdf file.
The solution was to deploy the whole project whenever I had a change to the script task, or the script task will not even attempt to run but reports as running sucessfully.

Reading Data from Access database and adding to a combox is very slow

So Ive been trying to read from a large access database and the table iam trying to read from contains nearly 20000 entries, all of which are needed in the combox. With some testing I have figured out that the program slows down the longer it runs. The first 5000 are added almost instantaneously, but the next 5000 increment increase exponentially. Over all it would take about 5 minutes to load the entire thing. Am i missing something that will make it more efficient? Ive attached the function iam using below. It is in Vb.net
Private Sub chkBoxPurchasedPart_CheckedChanged(sender As Object, e As EventArgs) Handles chkBoxPurchasedPart.CheckedChanged
If (chkBoxPurchasedPart.Checked) Then
chkBoxRawMaterial.Checked = False
chkBoxSkipMaterialSelection.Checked = False
MaterialButton.Enabled = True
comboxMaterial.Sorted = True
comboxMaterialHdn.Text = "AS SUPPLIED"
comboxMaterialHdn.Enabled = False
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim oConnect, oQuery As String
oConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Y:\eng\ENG_ACCESS_DATABASES\VisibPartAttributes.mdb"
oQuery = "SELECT * FROM VISIB_PARTMASTER_LOCAL WHERE PRODUCT_LINE LIKE '%PUR%' OR PRODUCT_LINE LIKE '%NOSTD%' AND PARTDESCR NOT LIKE '%OBSOLETE%'"
Try
cn.Open()
Catch ex As Exception
Finally
cn = New OleDbConnection(oConnect)
cn.Open()
End Try
cmd = New OleDbCommand(oQuery, cn)
dr = cmd.ExecuteReader
comboxMaterial.Items.Add("- - OTHER - -")
While dr.Read()
comboxMaterial.Items.Add(dr(0))
End While
dr.Close()
cn.Close()
Try
Dim s As Session = Session.GetSession()
Dim dispPart As Part = s.Parts.Display()
Dim c As NXOpen.Assemblies.Component = dispPart.ComponentAssembly.RootComponent
Dim children As NXOpen.Assemblies.Component() = c.GetChildren()
Dim childMaterial As String = Nothing
For Each child As NXOpen.Assemblies.Component In children
childMaterial = child.GetStringAttribute("STACKTECK_PARTN")
If (childMaterial.Length > 5 Or child.Name.StartsWith("PUR")) Then
comboxMaterial.Text = childMaterial
End If
Next
Catch ex As Exception
End Try
ElseIf (chkBoxPurchasedPart.Checked = False) Then
comboxMaterialHdn.Text = ""
comboxMaterialHdn.Enabled = True
txtBoxDiameter.Enabled = True
txtBoxRoundLength.Enabled = True
txtBoxInnerDiameter.Enabled = True
txtBoxLength.Enabled = True
txtBoxWidth.Enabled = True
txtBoxThickness.Enabled = True
MaterialButton.Enabled = False
txtBoxVisMaterial.Text = ""
txtBoxVisMaterialDescription.Text = ""
txtBoxEachQuantity.Text = ""
txtBoxTotalQuantity.Text = ""
txtBoxUnitOfMeasure.Text = ""
comboxMaterial.Sorted = False
comboxMaterial.Items.Clear()
comboxMaterial.Text = ""
End If
End Sub
For anyone in the future having a similar issue, the combobox wasnt the problem, the previous designer had the AutoCompleteMode set to suggest and append which slowed the entire process down. Disable it and your program should speed up.
I would only load the combo-box records after the first 3 or 4 characters have been entered. This should drastically reduce the number of records being returned, and a still allow the autocomplete to work.
This thread has code to assist you : get 65K records only listed in combo box from a table of 155K records

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

Unzip a zip file in silverlight

I am trying to develop code to unzip file from the zip file in Silverlight 5. The files are in a directory within the zip file.
I translated this code I found elsewhere from c# to VB since we are a VB shop. It is failing on the fourth line "Object reference not set to an instance of an object.".
I realize now that the problem is that the third line is expecting a relative uri and I am passing it a file, but I don't know how to fix this.
Can you tell me what is wrong with this code. I will also welcome other ideas.
Thanks.
Public Shared Function GetZipContents(ByVal filename As String) As String()
Try
Dim zipStream As System.IO.Stream = New System.IO.MemoryStream()
Dim zipInfo As New StreamResourceInfo(zipStream, Nothing)
Dim streamInfo As StreamResourceInfo = Application.GetResourceStream(zipInfo, New Uri(filename, UriKind.Relative))
Dim fileStream As Stream = streamInfo.Stream
Dim names As New List(Of String)()
Dim reader As New BinaryReader(fileStream)
Do While reader.ReadUInt32() = &H4034B50
' Skip the portions of the header we don't care about
reader.BaseStream.Seek(14, SeekOrigin.Current)
Dim compressedSize As UInteger = reader.ReadUInt32()
Dim uncompressedSize As UInteger = reader.ReadUInt32()
Dim nameLength As Integer = reader.ReadUInt16()
Dim extraLength As Integer = reader.ReadUInt16()
Dim nameBytes() As Byte = reader.ReadBytes(nameLength)
names.Add(Encoding.UTF8.GetString(nameBytes, 0, nameLength))
reader.BaseStream.Seek(extraLength + compressedSize, SeekOrigin.Current)
Loop
' Move the stream back to the begining
fileStream.Seek(0, SeekOrigin.Begin)
Return names.ToArray()
Catch ex As Exception
MessageBox.Show(ex.Message)
Return Nothing
End Try
End Function
There is quick and dirty way to unzip in Silverlight.
Use Application.GetResourceStream Method.
http://msdn.microsoft.com/en-us/library/cc190632(v=vs.95).aspx
Check out my blogpost on this: http://www.sharpgis.net/post/2010/08/25/REALLY-small-unzip-utility-for-Silverlight-e28093-Part-2.aspx
Sorry I would have time to explore the suggestions. I did find a way to accomplish my goal on my own. See the code below. I would be using this code either because the Technical Leader here prefers I do it a different way using a WCF service. Warning I was not able to test this code 100% since I am not planning to use it, but it is close to being right.
Imports ICSharpCode.SharpZipLib.Zip
Public Shared Sub UnZip(ByVal SrcFile As String, ByVal DstFile As String, ByVal BufferSize As Integer)
Try
Dim _FileName As String
Dim _ZipEntry As ZipEntry
Dim _FileStreamOut As FileStream = Nothing
Dim _Done As Boolean = False
Dim _FileStreamIn As New FileStream(SrcFile, FileMode.Open, FileAccess.Read)
Dim _ZipInStream As New ZipInputStream(_FileStreamIn)
Do Until _Done = True
_ZipEntry = _ZipInStream.GetNextEntry()
If IsNothing(_ZipEntry) Then
_Done = True
Exit Do
End If
_FileName = DstFile & "\" & _ZipEntry.Name
_FileName = _FileName.Replace("/", "\")
If Right(_FileName, 1) = "\" Then
If Directory.Exists(_FileName) = False Then
Directory.CreateDirectory(_FileName)
End If
Else
_FileStreamOut = New FileStream(_FileName, FileMode.Create, FileAccess.Write)
Dim size As Integer
Dim buffer(BufferSize - 1) As Byte
Do
size = _ZipInStream.Read(buffer, 0, buffer.Length)
_FileStreamOut.Write(buffer, 0, size)
Loop While size > 0
End If
Loop
_ZipInStream.Close()
_FileStreamOut.Close()
_FileStreamIn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub

How to printing a document in 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.

Resources