Filestream and receive the data from the read - asp.net

Reading an JSON document "source.json" thru filestream but how do you get the data from the json file? After that I am trying to append the newly edited json data back on the same file.
Dim pathSource As String = "Server.MapPath('~/source.json')"
Try
Using fs As FileStream = New FileStream(pathSource, _
FileMode.Open, FileAccess.Read)
Dim bytes() As Byte = New Byte((fsSource.Length) - 1) {}
Dim numBytesToRead As Integer = CType(fsSource.Length,Integer)
Dim numBytesRead As Integer = 0
While (numBytesToRead > 0)
Dim n As Integer = fsSource.Read(bytes, numBytesRead, _
numBytesToRead)
If (n = 0) Then
Exit While
End If
numBytesRead = (numBytesRead + n)
numBytesToRead = (numBytesToRead - n)
End While
numBytesToRead = bytes.Length
Dim xmlBuilder = New StringBuilder()
fs.Seek(0, SeekOrigin.Begin)
Dim ms As New MemoryStream()
fs.CopyTo(ms)
xmlBuilder.Append(Encoding.UTF8.GetString(ms.ToArray()))
ms.Flush()
ms.Close()
'???How to access the data from the file "source.json" you just read in???
'Edit the file "source.json" data
?? How to put it into "bytesout" the edited data???
Using fsAppend As FileStream = New FileStream(pathSource, _
FileMode.Append, FileAccess.Write)
fsAppend.Write(bytesout, 0, numBytesToRead)
End Using
End Using
Catch ioEx As FileNotFoundException
Console.WriteLine(ioEx.Message)
End Try

I've been down that path. Try to figure out what you did wrong with newtonsoft. The serializer and deserializer methods are fairly easy to use. You only have to create an object per the Json format and deserializer will populate the object automatically. You just have to have the variables in the class be declared as public property nameofjsonobject as

Related

How to get the contents a particular cell using excel data reader in Visual Basic? Using ExcelData Reader

I'm using the following code and I'm trying to understand how to access the content of each cell in the excel document in order to Validate it... but everything that I've found on the internet is in C# I tried to translate it but I'm getting some errors.. this is my code:
Using stream = File.Open(FullUpldPath, FileMode.Open, FileAccess.Read)
Using reader As IExcelDataReader = ExcelReaderFactory.CreateReader(stream)
Dim result As DataSet = reader.AsDataSet(New ExcelDataSetConfiguration() With {
.ConfigureDataTable = Function(__) New
ExcelDataTableConfiguration() With {
.UseHeaderRow = True}})
Dim tables As DataTableCollection = result.Tables
End Using
End Using
Dim file__1 as String = "excelpath"
If file__1.EndsWith(".xlsx") Then
' Reading from a binary Excel file (format; *.xlsx)
Dim stream As FileStream = File.Open(file__1, FileMode.Open, FileAccess.Read)
excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream)
excelReader.IsFirstRowAsColumnNames = True
dtExcelData = excelReader.AsDataSet()
excelReader.Close()
Return dtExcelData
End If
If file__1.EndsWith(".xls") Then
' Reading from a binary Excel file ('97-2003 format; *.xls)
Dim stream As FileStream = File.Open(file__1, FileMode.Open, FileAccess.Read)
excelReader = ExcelReaderFactory.CreateBinaryReader(stream)
dtExcelData = excelReader.AsDataSet()
excelReader.Close()
Return dtExcelData
End If

ASP.NET: Unable to cast IO.StreamWriter to IO.MemoryStream

I have a complex class module that make a lot of processing and return a object of type IO.StreamWriter, but I need cast this object to IO.MemoryStream, furthemore to Byte(). Finally it converts Byte() to Base64String that ajax consumes and generate a CSV file.
I made this with DynamicPDF.Document, but this library has a method that returns binary.
Dim objSW As IO.StreamWriter = EXP.ExportarBinario(objCommand, HttpContext.Current.Response.OutputStream, 1)
Dim objMS As New MemoryStream()
objSW.BaseStream.CopyTo(objMS)
Dim objArrayByte As Byte() = objMS.ToArray()
Dim strArrayByte64 As String = String.Format("data:{0};base64,{1}", "application/vnd.excel", Convert.ToBase64String(objArrayByte))
Return strArrayByte64

Downloading html as string

I am trying to download a webpage as string. Can someone please explain why the following code doesn't work?
Dim URL As String = "http://stackoverflow.com/"
Dim client As WebClient = New WebClient()
Dim data As Stream = client.OpenRead(URL)
Dim reader As StreamReader = New StreamReader(data)
Dim str As String = ""
str = reader.ReadLine()
Do While str.Length > 0
Console.WriteLine(str)
str = reader.ReadLine()
Loop
When I run it it never goes inside the loop.
Give this a shot...
Dim URL As String = "http://stackoverflow.com/"
Dim html As String = New WebClient().DownloadString(URL)
Better Solution (Releases resources that the network stack is using. Also ensure's (hope) the CLR cleans these up when needed.)
Using client As New WebClient()
html = client.DownloadString(URL)
End Using

Convert WebControl Image to iText.text.image

This is my code
Dim doc As iTextSharp.text.Document = New iTextSharp.text.Document()
Dim path As String = Request.MapPath("Sample PDFs") & "\Sample.tif"
PdfWriter.GetInstance(doc, New FileStream(Request.PhysicalApplicationPath + _
"render\1.pdf", FileMode.Create))
Dim data As clsData = New clsData(GetConnection, enumEgswFetchType.DataTable)
Dim int As Integer = data.GetPageCount(path)
doc.Open()
For ctr As Integer = 0 To int - 1
Dim img As iTextSharp.text.Image
Dim image As New System.Web.UI.WebControls.Image
image.ImageUrl = "ctrls/ViewTif.aspx?path=" + path.ToString + "&page=" + ctr.ToString
img = iTextSharp.text.Image.GetInstance(image, System.Web.UI.WebControls.Image)
doc.Add(image)
Next
doc.Close()
Response.Redirect("~/1.pdf")
Is there any way that I can get the webcontrol image to the itext? the image variable is a dynamic image with a source page returning a jpeg image from a tif file. Or is there any way I can directly put the tif to itext as pdf?
Is there a reason that you need to use System.Web.UI.WebControls.Image? One of the overloads for iTextSharp.text.Image.GetInstance() accepts a URL:
Dim TestFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf")
Using FS As New FileStream(TestFile, FileMode.Create, FileAccess.Write, FileShare.None)
Using Doc As New Document()
Using Writer = PdfWriter.GetInstance(Doc, FS)
Doc.Open()
Doc.Add(New Paragraph("Hello World"))
''//Get the image from a URL
Dim Img = iTextSharp.text.Image.GetInstance("http://www.google.com/images/srpr/logo4w.png")
''//Optionally adjust it
Img.ScaleAbsolute(100, 200)
''//Add it to the document
Doc.Add(Img)
Doc.Close()
End Using
End Using
End Using

CryptoStream.FlushFinalBlock throwing input data is not a complete block exception

I use the following two methods to encrypt and decrypt strings:
'Encrypts string. Returns encrypted byte array.
Public Function Encrypt(ByVal str As String) As Byte()
Dim inputInBytes() As Byte = Encoding.Unicode.GetBytes(str)
Dim laesProvider As New AesCryptoServiceProvider()
laesProvider.Key = _key
laesProvider.Mode = CipherMode.CBC
laesProvider.IV = _IV
laesProvider.Padding = PaddingMode.PKCS7
Dim lencryptor As ICryptoTransform = laesProvider.CreateEncryptor
Dim encryptedStream As New MemoryStream
Dim cryptStream As CryptoStream = New CryptoStream(encryptedStream, lencryptor, CryptoStreamMode.Write)
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock()
encryptedStream.Position = 0
Dim result(encryptedStream.Length - 1) As Byte
encryptedStream.Read(result, 0, encryptedStream.Length)
cryptStream.Close()
Return result
End Function
'Decrypts bytearray. Returns string.
Public Function DecryptToStr(ByVal inputInBytes() As Byte) As String
Dim laesProvider As New AesCryptoServiceProvider()
laesProvider.Key = _key
laesProvider.Mode = CipherMode.CBC
laesProvider.IV = _IV
laesProvider.Padding = PaddingMode.PKCS7
Dim ldecryptor As ICryptoTransform = laesProvider.CreateDecryptor
' Provide a memory stream to decrypt information into
Dim decryptedStream As MemoryStream = New MemoryStream()
Dim cryptStream As CryptoStream = New CryptoStream(decryptedStream, ldecryptor, CryptoStreamMode.Write)
cryptStream.Write(inputInBytes, 0, inputInBytes.Length)
cryptStream.FlushFinalBlock() '#### This is where the exception is thrown ####
decryptedStream.Position = 0
' Read the memory stream and convert it back into a string
Dim result(decryptedStream.Length - 1) As Byte
decryptedStream.Read(result, 0, decryptedStream.Length)
cryptStream.Close()
Return Encoding.Unicode.GetString(result)
End Function
The error occurs when attempting to decrypt certain length strings. When the string is a social security # (11 chars including dashes) then is throws "The input data is not a complete block" CryptographicException. If I pass in for example a string that is exactly 8 characters long, then everything works as expected. I thought that the PKCS7 padding would take care of the various lengths. I'm sure that I'm missing something simple, but after hours of googling, the answer eludes me.
The issue wasn't in the encryption method, it was in the length of the varbinary set in the database where it was being stored. So the encrypted data was being truncated.

Resources