if else for run file and stream file generate vb.net - vb.net

How to First Run File seconds stream file in text box via if and else
If Process.Start("test.bat") Then
Dim address As String = "id.txt"
Dim client As WebClient = New WebClient()
Dim reader As StreamReader = New StreamReader(client.OpenRead(address))
TextBox1.Text = reader.ReadToEnd
End If
Note: text file generated via batch file.

Try
Dim proc = Process.Start("test.bat")
proc.WaitForExit()
Using client As New WebClient()
TextBox1.Text = client.DownloadString(File.ReadAllText("id.txt"))
End Using
Catch
End Try

Related

VB.Net: Cannot download stream file generated with ZipOutputStream

I'm trying to zip a set of pdf files and send to client as download.
No matter what combinations of Response settings I try, the code doesn't throw any exception and apparently the zip file stream is created fine, but the file is not sent to the client as a download and when you hit the download button nothing happens.
Private Sub lkbDownloadPdfs_Click(sender As Object, e As System.EventArgs) Handles aDownloadPdfs.ServerClick
Try
Dim WSStockToolAuthTokenUrl As String = ConfigurationManager.AppSettings("WSStockToolAuthTokenUrl")
Dim auth As AuthenticationHeader = Utility.GetAuthenticationForStockToolToken()
Dim token As String = Utility.GetInitializationToken(WSStockToolAuthTokenUrl, auth.UserName, auth.password)
Response.Clear()
Response.ContentType = "application/zip"
Response.AppendHeader("Content-Disposition", "attachment; filename=files.zip")
If (token IsNot Nothing) Then
Dim result As String = PDFApiCallResult(token)
Dim pdfPathList As List(Of String) = Utility.GeneratePDFList(result)
If (pdfPathList.Count = 1) Then
Dim pdfPath As String = pdfPathList.ElementAt(0)
Dim strFile As String
Dim strmZipOutputStream = New ZipOutputStream(Response.OutputStream)
strmZipOutputStream.SetLevel(9)
Dim objCrc32 As New Crc32()
For Each strFile In pdfPathList
Dim Client As WebClient = New WebClient()
Dim strmFile As Stream = Client.OpenRead(strFile)
Dim reader As StreamReader = New StreamReader(strmFile)
Dim Content As String = reader.ReadToEnd()
Dim abyBuffer(Convert.ToInt32(Content.Length - 1)) As Byte
Dim sFile As String = Path.GetFileName(strFile)
Dim theEntry As ZipEntry = New ZipEntry(sFile)
theEntry.DateTime = DateTime.Now
theEntry.Size = Content.Length
strmFile.Close()
objCrc32.Reset()
objCrc32.Update(abyBuffer)
theEntry.Crc = objCrc32.Value
strmZipOutputStream.PutNextEntry(theEntry)
strmZipOutputStream.Write(abyBuffer, 0, abyBuffer.Length)
Next
strmZipOutputStream.Flush()
strmZipOutputStream.Finish()
strmZipOutputStream.Close()
Response.Flush()
Response.Close()
Response.SuppressContent = True
HttpContext.Current.ApplicationInstance.CompleteRequest()
Else
End If
End If
Catch ex As Exception
ExceptionManager.Publish(ex)
End Try
End Sub
Any help? (If you have working C# code I could try to convert it to vb.net too)
Update 1: This is the aspx where the link which does the callback resides:
<asp:UpdatePanel runat="server" ID="updImages" UpdateMode="Conditional">
...
DOWNLOAD PDFS
...
<asp:AsyncPostBackTrigger ControlID="lkbAddToWishlist" />
<asp:AsyncPostBackTrigger ControlID="ddlCustomizations" />
</asp:UpdatePanel>
I've read that maybe the response is not working at all because of the ajax way the update panel does the postback, but not sure about that and how to deal with that.

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

VB.NET Show message after FTP upload complete

I'm trying to create a uploader to FTP, although the file uploads perfectly, I am just wondering how I would be able to show a message after the ftp process has complete.
Close()
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
Using ms As New System.IO.MemoryStream
sc.CaptureDeskTopRectangle(Me.boundsRect).Save(ms, System.Drawing.Imaging.ImageFormat.Png)
Using wc As New System.Net.WebClient
wc.UploadData("ftp://MYUSERNAME:MYPASSWORD#MYSITE.COM/" + sb.ToString() + ".png", ms.ToArray())
End Using
End Using
How would I manage this?
Edit: Also as you can see I use a random string.. although If I use sb.ToString() twice will it give me the exact same result for both? If not how can I manage this??
You need to declare the Random as Static. The UploadData has a UploadDataCompleted event you can listen for.
Dim s As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Static r As New Random
Dim sb As New StringBuilder
For i As Integer = 1 To 8
Dim idx As Integer = r.Next(0, 35)
sb.Append(s.Substring(idx, 1))
Next
Using ms As New System.IO.MemoryStream
sc.CaptureDeskTopRectangle(Me.boundsRect).Save(ms, System.Drawing.Imaging.ImageFormat.Png)
Using wc As New System.Net.WebClient
AddHandler wc.UploadDataCompleted, AddressOf UploadCompleted
wc.UploadData("ftp://MYUSERNAME:MYPASSWORD#MYSITE.COM/" + sb.ToString() + ".png", ms.ToArray())
End Using
End Using
Private Sub UploadCompleted(sender As Object, e As Net.UploadDataCompletedEventArgs)
'do completed work here
End Sub
I don't think you can use the UploadData like that. Here is a Link for an example of ftp uploading.
Public Shared Sub Main()
' Get the object used to communicate with the server.
Dim request As FtpWebRequest = DirectCast(WebRequest.Create("ftp://www.contoso.com/test.htm"), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
' This example assumes the FTP site uses anonymous logon.
request.Credentials = New NetworkCredential("anonymous", "janeDoe#contoso.com")
' Copy the contents of the file to the request stream.
Dim sourceStream As New StreamReader("testfile.txt")
Dim fileContents As Byte() = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd())
sourceStream.Close()
request.ContentLength = fileContents.Length
Dim requestStream As Stream = request.GetRequestStream()
requestStream.Write(fileContents, 0, fileContents.Length)
requestStream.Close()
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription)
response.Close()
End Sub

Save file if error reading with Stream Reader

I am trying to parse a uploaded txt file. I need to save the file if there is an error parsing it. The problem is that the parser is using a Stream Reader and if an error occurs it just saves the empty file and not the file contents.
Dim file As HttpPostedFile = context.Request.Files(0)
If Not IsNothing(file) AndAlso file.ContentLength > 0 AndAlso Path.GetExtension(file.FileName) = ".txt" Then
Dim id As Integer = (Int32.Parse(context.Request("id")))
Try
ParseFile(file, id)
context.Response.Write("success")
Catch ex As Exception
Dim filename As String = file.FileName
Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
file.SaveAs(uploadPath + id.ToString() + filename)
End Try
Else
context.Response.Write("error")
End If
My ParseFile method is something like this
Protected Sub ParseFile(ByVal studentLoanfile As HttpPostedFile, ByVal id As Integer)
Using r As New StreamReader(studentLoanfile.InputStream)
line = GetLine(r)
End Using
End Sub
Is there a way to Clone the file before it gets passed into the parseFile sub or a way to read the file without loosing the contents?
Thanks in advance
For anyone who runs into this problem in the future, I ended up reading the file to the end and saving it into a variable. Then converted it back into a memory stream to use for the parser. If an error occurs, I just create a new file with the string. This is the code I used.
Dim id As Integer = (Int32.Parse(context.Request("id")))
'Read full file for error logging
Dim content As String = [String].Empty
Using sr = New StreamReader(uploadedFile.InputStream)
content = sr.ReadToEnd()
End Using
'Convert it back into a stream
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(content)
Dim stream As New MemoryStream(byteArray)
Try
ParseFile(stream, id, content)
context.Response.Write("success")
Catch ex As Exception
Dim filename As String = uploadedFile.FileName
Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
'Save full file on error
Using sw As StreamWriter = File.CreateText(uploadPath + id.ToString() + filename)
sw.WriteLine(content)
End Using
context.Response.Write("error")
Throw ex
End Try
Else
context.Response.Write("error")
End If

Cannot write a text message in Text File using WP7

I cannot write a file in a textfile in my wp7 application, what should I do?
here is my code
Dim isolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication
Dim isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("TextFile1.txt", FileMode.Append, isolatedStorage)
Dim streamwriter As StreamWriter = New StreamWriter(isoStream)
streamwriter.WriteLine("sample")
streamwriter.Close()
I also try to put it inside the Using statement, but it is still now writing in the text file
Dim isolatedStorage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication
Using isoStream As IsolatedStorageFileStream = New IsolatedStorageFileStream("/TextFile1.txt", FileMode.Append, isolatedStorage)
Using streamwriter As StreamWriter = New StreamWriter(isoStream)
streamwriter.WriteLine("PreMenu.xaml")
streamwriter.Close()
End Using
End Using
there is no error, but it is not writing a text in textfile, what should I do?