Put content of fileStream in dataset - vb.net

I want to read Stream that i get from XtrapivotGrid of DevExpress. I can save it in the computer but what i want is to save it in one of my table in my dataset called dataset1.
For now i have that code who permit to save it the directory Temp:.
Using FS As New IO.FileStream("D:\Temp\qqc.layout", IO.FileMode.Create)
PivotGridControl1.SaveLayoutToStream(FS)
End Using
Dim read As New System.IO.FileStream("D:\Temp\qqc.layout", IO.FileMode.Open, IO.FileAccess.Read)
DataSet1.LayoutMainRapport.ReadXml(read)
DataSet1.AcceptChanges()
read.Close()
The table LayoutMainRapport have 3 columns:
ID(Int)
Name(nvarchar(50))
Content(xml).
The output from the stream is xml.
thanks in advance!

I believe you should convert your saved layout into string and then save this string to database (and of course you can load this layout back from the database string value):
Private Function SaveLayoutToString(ByVal dxControl As DevExpressControl) As String
Using ms As MemoryStream = New MemoryStream()
dxControl.SaveLayoutToStream(ms)
Return Convert.ToBase64String(ms.ToArray())
End Using
End Function
Private Sub RestoreLayoutFromString(ByVal dxControl As DevExpressControl, ByVal layout As String)
If String.IsNullOrEmpty(layout) Then
Return
End If
Using ms As MemoryStream = New MemoryStream(Convert.FromBase64String(layout))
dxControl.RestoreLayoutFromStream(ms)
End Using
End Sub
Here DevExpressControl dxControl is the DevExpress control which supports saving and loading layout (XtraPivotGrid, XtraGrid, XtraLayoutControl etc.)

I simply had to save a name for the xml and after save it into my dataset.
Dim saveDialog As SaveLayout = New SaveLayout
If saveDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim read As New IO.MemoryStream
PivotGridControl1.SaveLayoutToStream(read)
read.Position = 0
Dim lecteur As New IO.StreamReader(read)
Dim ligne As DataRow = DataSet1.LayoutMainRapport.NewRow()
ligne("Nom") = saveDialog.txtNom.Text
ligne("Contenu") = lecteur.ReadToEnd()
DataSet1.LayoutMainRapport.Rows.Add(ligne)
LayoutMainRapportTableAdapter.Update(DataSet1)
End If

Related

VB.NET writing comments to jpeg file programmatically

I searched stackoverflow and I realized that GetPropertyItem and SetPropertyItem can edit comments in JPEG file
Dim images As Image = System.Drawing.Image.FromFile("C:\\Sample.jpeg")
Dim MSGF As New ArrayList
Dim ID() As String = {"hello ","i am here"}
Dim propItem As PropertyItem = images.GetPropertyItem(40092)
Dim encoderParameters As New EncoderParameters(1)
encoderParameters.Param(0) = New EncoderParameter(Encoder.Quality, 100L)
For i = 0 To ID.Length - 1
Dim TEMP As String = ID(i)
For II = 0 To TEMP.Length - 1
MSGF.Add(Convert.ToInt32(TEMP(II)))
Next
Next
For i = 0 To MSGF.Count - 1
propItem.Value.SetValue(Convert.ToByte(MSGF(i)), i)
Next
images.SetPropertyItem(propItem)
images.Save(TextBox1.Text & "\" & "1" & TextBox2.Text)
What I realized was I can get comments from jpeg file by GetPropertyItem. However, comments is based on the ascii code. Therefore, I was trying to convert comment that I wanted to insert to ascii code.
propItem.Value.SetValue(Convert.ToByte(MSGF(i)), i)
This part was actually changed comments which already existed in the jpeg file.
However, if there is no comments in jpeg file, propItem.value.setValue doesn't work because there is nothing to edit.
Is there anyway to just add comments to jpeg file?
Based on this answer in C#, it could be as simple as this:
Dim jpeg = New JpegMetadataAdapter(pathToJpeg)
jpeg.Metadata.Comment = "Some comments"
jpeg.Metadata.Title = "A title"
jpeg.Save()
' Saves the jpeg in-place
jpeg.SaveAs(someNewPath)
' Saves with a new path
Here is the class:
Public Class JpegMetadataAdapter
Private ReadOnly path As String
Private frame As BitmapFrame
Public ReadOnly Metadata As BitmapMetadata
Public Sub New(path As String)
Me.path = path
frame = getBitmapFrame(path)
Metadata = DirectCast(frame.Metadata.Clone(), BitmapMetadata)
End Sub
Public Sub Save()
SaveAs(path)
End Sub
Public Sub SaveAs(path As String)
Dim encoder As New JpegBitmapEncoder()
encoder.Frames.Add(BitmapFrame.Create(frame, frame.Thumbnail, Metadata, frame.ColorContexts))
Using stream As Stream = File.Open(path, FileMode.Create, FileAccess.ReadWrite)
encoder.Save(stream)
End Using
End Sub
Private Function getBitmapFrame(path As String) As BitmapFrame
Dim decoder As BitmapDecoder = Nothing
Using stream As Stream = File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
decoder = New JpegBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad)
End Using
Return decoder.Frames(0)
End Function
End Class

VB.NET Return Form Object using Form Name

I'm basically writing a custom Error Logging Form for one of my applications because users cannot be trusted to report the errors to me.
I am obtaining the Form Name using the 'MethodBase' Object and then getting the DeclaringType Name.
Dim st As StackTrace = New StackTrace()
Dim sf As StackFrame = st.GetFrame(1)
Dim mb As MethodBase = sf.GetMethod()
Dim dt As String = mb.DeclaringType.Name
How can I then use this to obtain the Form Object so I can pass this to my 'screenshot method' that screenshots the particular form referenced.
Public Sub SaveAsImage(frm As Form)
'Dim fileName As String = "sth.png"
'define fileName
Dim format As ImageFormat = ImageFormat.Png
Dim image = New Bitmap(frm.Width, frm.Height)
Using g As Graphics = Graphics.FromImage(image)
g.CopyFromScreen(frm.Location, New Point(0, 0), frm.Size)
End Using
image.Save(_LogPath & Date.Now.ToString("ddMMyyyy") & ".png", format)
End Sub
I posted the same solution to a similar question. Try this:
Dim frm = Application.OpenForms.Item(dt)

Extract Images with text from PDF and Edit it using iTextSharp

I am trying to do following things in Windows Forms
1) Read a PDF in Windows Forms
2) Get the Images with Text in it
3) Color / fill the Image
4) save everything to a new file
I have tried Problem with PdfTextExtractor in itext!
But It didn't help.
Here is the code I've tried:
Public Shared Sub ExtractImagesFromPDF(sourcePdf As String, outputPath As String)
'NOTE: This will only get the first image it finds per page.'
Dim pdf As New PdfReader(sourcePdf)
Dim raf As RandomAccessFileOrArray = New iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf)
Try
For pageNumber As Integer = 1 To pdf.NumberOfPages
Dim pg As PdfDictionary = pdf.GetPageN(pageNumber)
' recursively search pages, forms and groups for images.'
Dim obj As PdfObject = FindImageInPDFDictionary(pg)
If obj IsNot Nothing Then
Dim XrefIndex As Integer = Convert.ToInt32(DirectCast(obj, PRIndirectReference).Number.ToString(System.Globalization.CultureInfo.InvariantCulture))
Dim pdfObj As PdfObject = pdf.GetPdfObject(XrefIndex)
Dim pdfStrem As PdfStream = DirectCast(pdfObj, PdfStream)
Dim bytes As Byte() = PdfReader.GetStreamBytesRaw(DirectCast(pdfStrem, PRStream))
If (bytes IsNot Nothing) Then
Using memStream As New System.IO.MemoryStream(bytes)
memStream.Position = 0
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(memStream)
' must save the file while stream is open.'
If Not Directory.Exists(outputPath) Then
Directory.CreateDirectory(outputPath)
End If
Dim path__1 As String = Path.Combine(outputPath, [String].Format("{0}.jpg", pageNumber))
Dim parms As New System.Drawing.Imaging.EncoderParameters(1)
parms.Param(0) = New System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0)
'Dim jpegEncoder As System.Drawing.Imaging.ImageCodecInfo = iTextSharp.text.Utilities.GetImageEncoder("JPEG")'
img.Save(path__1) 'jpegEncoder, parms'
End Using
End If
End If
Next
Catch
Throw
Finally
pdf.Close()
raf.Close()
End Try
End Sub
Now, the actual purpose of this is to get something like this
If this is the actual PDF, I will have to check if there any any items in that bin(by Text in that box)
If there are items then I have to color it like below
Can someone help me with this
The PDF can be retrieved here.

Load data from serialization to listbox

I am able to write to the file perfectly... however I am having trouble reading from file and inserting read data into a listbox.
Public myData As New MySettings
Public saveFile As String = ("mysettings.ini")
'SAVE INFO TO SETTINGS FILE
Dim fs As Stream = New FileStream(saveFile, FileMode.Create)
Dim bf As BinaryFormatter = New BinaryFormatter()
For l_index As Integer = 0 To ListBox1.Items.Count - 1
Dim l_text As String = CStr(ListBox1.Items(l_index))
bf.Serialize(fs, l_text)
Next
fs.Close()
Return
This is the part where I am having trouble...
'LOAD INFO FROM SETTINGS FILE
Dim fs As Stream = New FileStream(saveFile, FileMode.Open)
Dim bf As BinaryFormatter = New BinaryFormatter()
For l_index As Integer = 0 To saveFile.Count - 1
Dim l_text As String = CStr(saveFile(l_index))
'myData = CType(bf.Deserialize(fs), CType(myData))
ListBox1.Items.Add(myData)
Next
fs.Close()
Return
Any help at all would be appreciated, even a point in the right direction.
Thanks in advance!!
The ListBox ObjectCollection (Items) is not marked as serializable, so you cant serialize the entire thing at once. You may have encountered this and used the loop to serialize each item. The loop does appear to serialize each item, but I don't know how you can deserialize in a loop - you wont know how many items there are, nor will the Serializer.
Rather than one item at a time, you could copy the ListBox items to an array and serialize the entire thing:
Dim ary(lb.Items.Count - 1) As Object
lb.Items.CopyTo(ary, 0)
' OpenOrCreate!
Using fs As New FileStream("C:\Temp\lbitems.bin", FileMode.OpenOrCreate)
Dim bf As New BinaryFormatter
bf.Serialize(fs, ary)
End Using ' close and dispose of stream
Deserialization is just the reverse:
Using fs As New FileStream("C:\Temp\lbitems.bin", FileMode.Open)
Dim bf As New BinaryFormatter
Dim myAry = bf.Deserialize(fs)
lb.Items.Clear()
lb.Items.Add(myAry)
End Using
You can make it a bit simpler using a List(of String) and assign it as the DataSource.
Private myLBItems As New List(Of String)
...
' fake items to add
myLBItems.Add("Foo")
myLBItems.Add("Bar")
myLBItems.Add("Option")
myLBItems.Add("Strict")
lb.DataSource = myLBItems
Using the List as the DataSource, you dont have to copy items from here to there - whatever is in the List will appear in the ListBox. Serialization is simple too:
bf.Serialize(fs, myLBItems)
Since Deserializing returns an Object, you need to cast it (Option Strict):
myLBItems = CType(bf.Deserialize(fs), List(Of String))
Note: This may not be doing what you want at all. Your code is serializing what is in the ListBox after converting it to String. Later, it looks like you want to Deserialize to a MySettings Type.
If MySettings is something like a Name and Value pair (or collection of them), probably half the data and all the Type information will have been lost.

MongoDB C# How to Update GridFS File and metadata?

Need a solution to to see if the grid file exist and then update the file with metadata.
I am using the solution below. but want a better one.
Don't mind having separate Update and Delete methods.
Thanks
Public Class storedXYZ
Property Data As Stream
Property MetaData As storedXYZMetaData
End Class
Public Sub SaveStoredXYZ(storedXYZ As StoredXYZ)
Dim MongoGridFSCreateOptions As New MongoDB.Driver.GridFS.MongoGridFSCreateOptions
Dim qry As IMongoQuery
qry = Query.EQ("metadata.StoredXYZId", BsonValue.Create(storedXYZ.MetaData.StoredXYZ.ToString()))
Dim gridFile As MongoGridFSFileInfo = mdbGridFS.FindOne(qry)
If gridFile IsNot Nothing Then
Dim mongoStream As MongoGridFSStream
MongoGridFSCreateOptions.Metadata = storedXYZ.MetaData.ToBsonDocument
mongoStream = gridFile.OpenWrite()
''Convert MongoStream to MemoryStream
Dim fs As Stream = New MemoryStream()
Dim buffer As Byte() = New Byte(9999) {}
Dim bytesRead As Integer = 0
Do
bytesRead = storedXYZ.Data.Read(buffer, 0, buffer.Length)
mongoStream.Write(buffer, 0, bytesRead)
Loop While bytesRead > 0
mongoStream.Seek(0, SeekOrigin.Begin)
mongoStream.Position = 0
mdbGridFS.SetMetadata(gridFile, storedAXYZ.MetaData.ToBsonDocument)
Else
MongoGridFSCreateOptions.Metadata = storedXYZ.MetaData.ToBsonDocument
Dim fileinfo As MongoGridFSFileInfo
fileinfo = mdbGridFS.Upload(storedXYZ.Data, storedXYZ.MetaData.Name, MongoGridFSCreateOptions)
End If
End Sub
Rather than trying to overwrite the current file why not just fire off a delete command and then re-upload the file and update the document to the old ones Id?
MongoGridFS Upload method gets a new version of the file when you upload a file using an existing file name.
Using OpenWrite with an existing file name updates the file in place. The C# driver is the only driver that allows to update a GridFS file in place.
More information here
You can use fs.files and fs.chnuks collections as any other collection but you have to be careful to keep important for GridFS data untouched.