Digitally sign multiple PDF files with an E-ID in a specified folder - vb.net

Note: I have heavily edited most of my post as I have advanced a bit further now
I am currently working on a small project: the general idea is that the user selects a folder, inserts his E-ID and all PDF files in that folder are modified with his digital signature and an image to represent this when printed.
I am currently using the iTextSharp framework to accomplish this. But because I have to convert the source to VB.NET, I have hit a full stop.
The following code accomplishes its task of adding a digital signature to a PDF document, however. It only does so with the test-certificate I have created with Visual Studio. Anything else and the PDF just isn't created, I have checked with breakpoints and myPkcs12Store does not get filled with anything: I cannot retrieve the personal key from the eID.
Private Sub Test()
Dim myKeyStore As New X509Store(StoreName.My, StoreLocation.CurrentUser)
myKeyStore.Open(OpenFlags.[ReadOnly])
Dim myCertificateCollection As X509Certificate2Collection = myKeyStore.Certificates
Dim myCertificate As X509Certificate2 = Nothing
Dim selectedCertificates As X509Certificate2Collection = X509Certificate2UI.SelectFromCollection(myCertificateCollection, "Certificaten", "Select een certificaat om te tekenen", X509SelectionFlag.SingleSelection)
If selectedCertificates.Count > 0 Then
Dim certificatesEnumerator As X509Certificate2Enumerator = selectedCertificates.GetEnumerator()
certificatesEnumerator.MoveNext()
myCertificate = certificatesEnumerator.Current
End If
myKeyStore.Close()
'Settings'
Dim source = "source.pdf"
Dim result = "result.pdf"
Dim reason = "test"
Dim Location = "locatie"
Dim myPkcs12Store As New Pkcs12Store()
Using memorystreamPfx As New System.IO.MemoryStream(myCertificate.Export(X509ContentType.Pkcs12))
myPkcs12Store.Load(memorystreamPfx, "")
End Using
For Each strAlias As String In myPkcs12Store.Aliases
If myPkcs12Store.IsKeyEntry(strAlias) Then
Dim pk = myPkcs12Store.GetKey(strAlias).Key
Using myPdfReader As New PdfReader(source)
Using myFileStream As New FileStream(result, FileMode.Create, FileAccess.Write)
Using myPdfStamper As PdfStamper = PdfStamper.CreateSignature(myPdfReader, myFileStream, "0")
Dim myPdfDocument As New Document(myPdfReader.GetPageSizeWithRotation(1))
'Define the digital signature appearance'
Dim myPdfSignatureAppearance As PdfSignatureAppearance = myPdfStamper.SignatureAppearance
myPdfSignatureAppearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED
myPdfSignatureAppearance.Image = Image.GetInstance("Images/poro1_by_justduet-d63wx6c.png")
myPdfSignatureAppearance.Reason = reason
myPdfSignatureAppearance.Location = Location
myPdfSignatureAppearance.SetVisibleSignature(New iTextSharp.text.Rectangle(myPdfDocument.PageSize.Width - 120, 36, myPdfDocument.PageSize.Width - 36, 96), myPdfReader.NumberOfPages, "Digital Signature")
'Attach digital signature to PDF document'
Dim myExternalSignature As IExternalSignature = New PrivateKeySignature(pk, "SHA-256")
MakeSignature.SignDetached(myPdfSignatureAppearance, myExternalSignature, {(myPkcs12Store.GetCertificate(strAlias).Certificate)}, Nothing, Nothing, Nothing, 0, CryptoStandard.CMS)
End Using
End Using
End Using
End If
Next
Any help would be appreciated! Further questions please ask
bdebaere

For anyone looking for an answer to this:
Dim myX509Store As New X509Store(StoreName.My, StoreLocation.CurrentUser)
myX509Store.Open(OpenFlags.[ReadOnly])
'Dim myCertificateCollection As X509Certificate2Collection = myX509Store.Certificates
Dim myCertificateChain As IList(Of X509Certificate) = New List(Of X509Certificate)()
Dim myCertificate As X509Certificate2 = Nothing
Dim myCertificateCollection As X509Certificate2Collection = X509Certificate2UI.SelectFromCollection(myX509Store.Certificates, "Certificaten", "Select een certificaat om te tekenen", X509SelectionFlag.SingleSelection)
If myCertificateCollection.Count > 0 Then
Dim certificatesEnumerator As X509Certificate2Enumerator = myCertificateCollection.GetEnumerator()
certificatesEnumerator.MoveNext()
myCertificate = certificatesEnumerator.Current
'myCertificate = selectedCertificates(0)
Dim myX509Chain As New X509Chain()
myX509Chain.Build(myCertificate)
For Each myChainElement As X509ChainElement In myX509Chain.ChainElements
myCertificateChain.Add(DotNetUtilities.FromX509Certificate(myChainElement.Certificate))
Next
End If
myX509Store.Close()
Dim ocspClient As IOcspClient = New OcspClientBouncyCastle()
Dim tsaClient As ITSAClient = Nothing
For intI As Integer = 0 To myCertificateChain.Count - 1
Dim cert As X509Certificate = myCertificateChain(intI)
Dim tsaUrl As String = CertificateUtil.GetTSAURL(cert)
If tsaUrl IsNot Nothing Then
tsaClient = New TSAClientBouncyCastle(tsaUrl)
Exit For
End If
Next
Dim crlList As IList(Of ICrlClient) = New List(Of ICrlClient)()
crlList.Add(New CrlClientOnline(myCertificateChain))
'Settings
Dim source = "source.pdf"
Dim result = "result.pdf"
Dim reason = "test"
Dim Location = "locatie"
Using myPdfReader As New PdfReader(source)
Using myFileStream As New FileStream(result, FileMode.Create, FileAccess.Write)
Using myPdfStamper As PdfStamper = PdfStamper.CreateSignature(myPdfReader, myFileStream, "0"c)
Dim myPdfDocument As New Document(myPdfReader.GetPageSizeWithRotation(1))
'Define the digital signature appearance
Dim myPdfSignatureAppearance As PdfSignatureAppearance = myPdfStamper.SignatureAppearance
myPdfSignatureAppearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED
'myPdfSignatureAppearance.Image = Image.GetInstance("Images/poro1_by_justduet-d63wx6c.png")
myPdfSignatureAppearance.Reason = reason
myPdfSignatureAppearance.Location = Location
myPdfSignatureAppearance.SetVisibleSignature(New iTextSharp.text.Rectangle(myPdfDocument.PageSize.Width - 120, 36, myPdfDocument.PageSize.Width - 36, 96), myPdfReader.NumberOfPages, "Digital Signature")
Dim pks As IExternalSignature = New X509Certificate2Signature(myCertificate, DigestAlgorithms.SHA1)
'Attach digital signature to PDF document
'Dim myExternalSignature As IExternalSignature = New PrivateKeySignature(pk, "SHA-256")
MakeSignature.SignDetached(myPdfSignatureAppearance, pks, myCertificateChain, crlList, ocspClient, tsaClient, 0, CryptoStandard.CMS)
End Using
End Using
End Using
The only problem is if you are using eID for every PDF you have to enter your PIN.
bdebaere

Related

Add Image And Text To Existing .pdf Using iText in VB.net

I've got the below code on a button click which work great. It adds an image to each existing .pdf and then combines several of the new .pdf's together and creates one .pdf. Again, this part of it works great.
The problem I'm having is now I want to keep the existing code but add some text to each page at the same point in the code where the image gets added. I've read a bunch of examples on how to add text to an existing .pdf but due to my inexperience in the area I cant figure out how to make any of the examples work with my existing code. Using VB.net.
I want to add a simple line of text "Example Of text" and position it on the page (300, 300).
Any help would greatly appreciated.
Dim tempFilename = IO.Path.GetTempFileName()
Dim tempFile As New IO.FileStream(tempFilename, IO.FileMode.Create)
' Set up iTextSharp document to hold merged PDF
Dim mergedDocument As New iTextSharp.text.Document(iTextSharp.text.PageSize.LETTER)
Dim copier As New iTextSharp.text.pdf.PdfCopy(mergedDocument, tempFile)
mergedDocument.Open()
Dim pic1 As String = "C:\xxx\xxxx\xxx.png"
Using inputPdfStream As IO.Stream = New IO.FileStream(Server.MapPath(".") + "/xxx.pdf", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Using inputImageStream As IO.Stream = New IO.FileStream(pic1, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Using outputPdfStream As IO.Stream = New IO.FileStream(Server.MapPath(".") + "/xxx2.pdf", IO.FileMode.Create, IO.FileAccess.ReadWrite, IO.FileShare.None)
Dim reader1 = New iTextSharp.text.pdf.PdfReader(inputPdfStream)
Dim stamper = New iTextSharp.text.pdf.PdfStamper(reader1, outputPdfStream)
Dim pdfContentByte = stamper.GetOverContent(1)
Dim image__1 As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(inputImageStream)
image__1.SetAbsolutePosition(527, 710)
image__1.ScaleAbsolute(60, 60)
pdfContentByte.AddImage(image__1)
stamper.Close()
reader1.Close()
outputPdfStream.Close()
inputImageStream.Close()
inputPdfStream.Close()
outputPdfStream.Dispose()
End Using
End Using
End Using
Dim reader As New iTextSharp.text.pdf.PdfReader(New iTextSharp.text.pdf.RandomAccessFileOrArray(Server.MapPath(".") + "/yyy/xxx3".pdf", True), Nothing)
For pageNum = 1 To reader.NumberOfPages
copier.AddPage(copier.GetImportedPage(reader, pageNum))
Next
PTime = PTime + 1
Loop
mergedDocument.Close()
tempFile.Dispose()
After a lot of trial and error I got it to work by adding the following code.
Dim bf As iTextSharp.text.pdf.BaseFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED)
pdfContentByte.SetColorFill(iTextSharp.text.BaseColor.DARK_GRAY)
pdfContentByte.SetFontAndSize(bf, 8)
pdfContentByte.BeginText()
Dim strX As String = "Here"
pdfContentByte.ShowTextAligned(1, strX, 500, 500, 0)
pdfContentByte.EndText()

Request Signature Docusign Rest API vb.net

am trying to use the DocuSign .Net Client to request a signature on a Document I am creating dynamically. So far, I have been able to change the example to vb.net and it works (Exmaple CS). I was converting the "Walkthrough #4 - Request Signature on Document", about 1/2 way down the code. Now I am trying to use the Envelope.Document I've seen in other examples, such as, DocuSign example. But it seems .Document is not part of Envelope, even thought the rest of the code in both examples translates to vb.
My other option is to use the Envelope.AddDocument but I can't seem to figure out what it's expecting. I am supposed to pass fileBytes() as Byte, fileName as String, and index As Integer. I've tried a couple different methods to get the fileBytes but keep getting an error about Invalid_Content_Type Content type is not supported.
Here is the code I've been trying. Any help on how to add a Document to an Envelope would be appreciated. Ultimately I want to be able to add multiple documents to the one envelope. I can get the env.Create(docPath) to work, but that is not helpful.
Thank you in advance for any help you can offer.
Public Function RequestEsignature(email As String, rName As String, docPath As String, strSubject As String) As String
main()
Dim AccountEmail = My.Settings.docusignUserName
Dim AccountPassword = My.Settings.docusignPassword
Dim RecipientEmail = email
Dim RecipientName = rName
Dim documentPath = docPath
Dim msgString As String
Dim acct As Account = New Account()
acct.Email = AccountEmail
acct.Password = AccountPassword
Dim result As Boolean = acct.Login()
If Not result Then
msgString = String.Format("There was an error logging in to DocuSign fo user {0}.\nError Code: {1}\nMessage: {2}", acct.Email, acct.RestError.errorCode, acct.RestError.message)
MsgBox(msgString)
Return Nothing
End If
Dim env As Envelope = New Envelope
env.Login = acct
env.Recipients = New Recipients()
Dim signer(0) As Signer
signer(0) = New Signer()
signer(0).email = email
signer(0).name = RecipientName
signer(0).routingOrder = "1"
signer(0).recipientId = "1"
env.Recipients.signers = signer
Dim envDocs = New Document()
envDocs.documentId = "1"
envDocs.name = "Test Document"
envDocs.uri = docPath
'Dim fileBytes As Byte()
'Dim fileBytes = getByteArrayII(documentPath)
'Dim oFile As FileInfo
'oFile = New FileInfo(documentPath)
'Dim oFileStream As FileStream = oFile.OpenRead()
'Dim lBytes As Long = oFileStream.Length
'If lBytes > 0 Then
' Dim fileData(lBytes - 1) As Byte
' oFileStream.Read(fileData, 0, lBytes)
'If Not env.AddDocument(fileBytes, documentPath, 0) Then
' msgString = String.Format("The was an Error adding the Document." & vbCrLf & "Error Code: {0} " & vbCrLf & "Message: {1}", env.RestError.errorCode, env.RestError.message)
' MsgBox(msgString)
' Return Nothing
'Else
' MsgBox("Doc Successfully Added")
'End If
'oFileStream.Close()
'End If
env.Status = "sent"
env.EmailSubject = strSubject
result = env.Create()
If Not result Then
If Not IsNothing(env.RestError) Then
msgString = String.Format("Error Code: {0}\nMessage: {1}", env.RestError.errorCode, env.RestError.message)
MsgBox(msgString)
Return Nothing
Else
MsgBox("There was a nondescript error while processing this request. \nPLease verify all information is correct before trying again.")
Return Nothing
End If
Else
Return env.EnvelopeId
End If
End Function
Private Function getByteArray(fileName As String) As Byte()
Dim fInfo As New FileInfo(fileName)
Dim numBytes As Long = fInfo.Length
Dim fStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim br As New BinaryReader(fStream)
Dim data As Byte() = br.ReadBytes(CInt(numBytes))
br.Close()
fStream.Close()
Return data
End Function
Private Function getByteArrayII(ByVal fileName As String) As Byte()
Dim tempByte() As Byte = Nothing
If String.IsNullOrEmpty(fileName) Then
Throw New ArgumentNullException("FileName Not Provided")
Return Nothing
End If
Try
Dim fileInfo As New FileInfo(fileName)
Dim numBytes As Long = fileInfo.Length
Dim fStream As New FileStream(fileName, FileMode.Open, FileAccess.Read)
Dim binaryReader As New BinaryReader(fStream)
tempByte = binaryReader.ReadBytes(Convert.ToInt32(numBytes))
fileInfo = Nothing
numBytes = 0
fStream.Close()
fStream.Dispose()
Return tempByte
Catch ex As Exception
Return Nothing
End Try
End Function
HISTORY
I am new to vb.net and programming. Thus far I have been able to make a program that allows users to enter client information with the forms being changed based on certain selections. We have a system that uses our SQL data to do mail merges in Word and then send a PDF for esignature to the client through DocuSign. We are using a SQL backend and a vb.net front end.
Lastly, I have been looking for an answer over the weekend and am now reaching out for help. I have searched google for every possible term(s) I can think to include/exclude. If I am asking publicly that truly means I have exhausted every resource I have. Please do not post links to any DocuSign Documentation as I have already visited all those sites. Thank you.
It doesn't appear that the Envelope class has a Document property, but rather a Documents property which seems to be an array.
The C# example you posted at this link seems to show how to attach a document:
// Attach the document(s) C#
envelope.Documents = new DocuSignWeb.Document[1];
DocuSignWeb.Document doc = new DocuSignWeb.Document();
doc.ID = "1";
doc.Name = "Document Name";
doc.PDFBytes = [Location of Document];
envelope.Documents[0] = doc;
Which in VB would be something like this:
'Attach the document(s) VB
envelope.Documents = new DocuSignWeb.Document(0);
Dim doc As New DocuSignWeb.Document()
doc.ID = "1"
doc.Name = "Document Name"
doc.PDFBytes = [Location of Document]
envelope.Documents(0) = doc
If this is not the problem you are facing, please provide additional details.
Clearly my approach to learning vb, api's and all the other stuff needed to get my program working is extremely daunting. I am not sure if it is my lack of knowledge or just a misunderstanding of the code, but I was finally able to get this figured out.
My function takes an object 'client' that has things like Name and Email, I also pass a list of Document Paths and the Subject line for the email. This loops through the list of documents and adds them to the envelope. I also have some examples of adding Tags which was a learning process in itself. I hope I am the only one unfortunate enough to have to be learning so many different new concepts that something this simple takes months to figure out, but if not here's the code:
'Request Signature - Send Envelope
Public Function RequestEsignature(pClient As iqClient, docPaths As List(Of String), strSubject As String) As DocuSign.Integrations.Client.Envelope
'*****************************************************************
' ENTER VALUES FOR FOLLOWING VARIABLES!
'*****************************************************************
Dim AccountEmail As String = My.Settings.docusignUserName
Dim AccountPassword As String = My.Settings.docusignPassword
Dim RecipientEmail As String = pClient.Email
Dim RecipientName As String = pClient.Name.NameFL
'*****************************************************************
' user credentials
Dim account As New Account()
account = LoginToDocusign()
If Not IsNothing(account) Then
End If
Dim result As Boolean ' = account.Login()
' create envelope object and assign login info
Dim envelope As New Envelope()
Dim recip = New Recipients()
Dim signers = New List(Of Signer)
Dim signer As New Signer()
signer.email = RecipientEmail
signer.name = RecipientName
signer.routingOrder = "1"
signer.recipientId = "1"
Dim fileBytes = New List(Of Byte())
Dim docNames = New List(Of String)
Dim iqDoc As iqPublicClasses.iqDocement
Dim docs = New List(Of Document)
Dim doc As Document
Dim tabs = New List(Of Tab)
Dim tab As New Tab()
Dim iTabs = New List(Of Tab)
Dim iTab As New Tab()
Dim dTabs = New List(Of DateSignedTab)
Dim dTab As New DateSignedTab
Dim rTabs = New List(Of RadioGroupTab)
Dim rTab As New RadioGroupTab()
Dim radios = New List(Of Radios)
Dim radio As New Radios()
tab = New Tab()
tab.anchorIgnoreIfNotPresent = True
tab.anchorString = "\s1\"
tabs.Add(tab)
dTab = New DateSignedTab
dTab.anchorIgnoreIfNotPresent = True
dTab.anchorString = "\d1\"
dTabs.Add(dTab)
iTab = New Tab()
iTab.anchorIgnoreIfNotPresent = True
iTab.anchorString = "\i1\"
iTab.anchorYOffset = 15
iTabs.Add(iTab)
iTab = New Tab()
iTab.anchorIgnoreIfNotPresent = True
iTab.anchorString = "\nri1\"
iTabs.Add(iTab)
rTab = New RadioGroupTab()
rTab.groupName = "RG1"
rTab.anchorIgnoreIfNotPresent = True
radio = New Radios()
radio.anchorString = "\rbn\"
radio.anchorIgnoreIfNotPresent = True
radio.anchorYOffset = -10
radios.Add(radio)
radio = New Radios()
radio.anchorString = "\rby\"
radio.anchorIgnoreIfNotPresent = True
radio.anchorYOffset = -10
radios.Add(radio)
rTab.radios = radios.ToArray
rTabs.Add(rTab)
signer.tabs = New Tabs()
signer.tabs.signHereTabs = tabs.ToArray
signer.tabs.dateSignedTabs = dTabs.ToArray
signer.tabs.initialHereTabs = iTabs.ToArray
signer.tabs.radioGroupTabs = rTabs.ToArray
Dim cnt = 0
For Each docName As String In docPaths
cnt += 1
iqDoc = New iqPublicClasses.iqDocement(docName)
doc = New Document()
doc.attachmentDescription = iqDoc.Name
doc.name = String.Format("{0}{1}", iqDoc.Name, iqDoc.Extension)
doc.fileExtension = iqDoc.Extension
doc.uri = iqDoc.FullPath
doc.documentId = cnt
docs.Add(doc)
docNames.Add(iqDoc.FullPath)
fileBytes.Add(File.ReadAllBytes(iqDoc.FullPath))
Next
' create envelope and send the signature request (since status is set to "sent")
envelope.Login = account
signers.Add(signer)
recip.signers = signers.ToArray
envelope.Recipients = recip
envelope.Status = "sent"
envelope.EmailSubject = strSubject
result = envelope.Create(fileBytes, docs)
If Not result Then
If envelope.RestError IsNot Nothing Then
Console.WriteLine("Error code: {0}" & vbLf & "Message: {1}", envelope.RestError.errorCode, envelope.RestError.message)
Return Nothing
Else
Console.WriteLine("Error encountered while requesting signature from template, please review your envelope and recipient data.")
Return Nothing
End If
Else
Console.WriteLine("Signature request has been sent to {0}, envelopeId is {1}.", envelope.Recipients.signers(0).email, envelope.EnvelopeId)
Return envelope
End If
End Function
PS - As I've said I am extremely new to this and am learning as I am going. I understand this may not be the most elegant approach or properly formatted code, but I unfortunately have very little time to go back an update code I've written. Hopefully one day I will be able to go back and fix all the stuff I didn't understand when I first created it.

automatically download a report

This is the code that i have made but now working to save the report to the directory:
As you see i follow pretty much a lot of microsoft tutorials of how use this class of reporting service, but still dont get how get it working
'objetos de reporting
Dim rs As New reportingservice.ReportingService2010
Dim rsExec As New ReportExecution.ReportExecutionService
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
'datos generales
Dim historyID As String = Nothing
Dim deviceInfo As String = Nothing
Dim format As String = "PDF"
Dim results As Byte()
Dim encoding As String = String.Empty
Dim mimeType As String = String.Empty
Dim extension As String = String.Empty
Dim warnings As ReportExecution.Warning() = Nothing
Dim streamIDs As String() = Nothing
Dim filename As String = "C:/Users/gdedieu/Desktop/reporte.pdf" ' Change to where you want to save
Dim _reportName As String = "per_anexo_1"
Dim _historyID As String = Nothing
Dim _forRendering As Boolean = False
Dim _values As ReportExecution.ParameterValue() = Nothing
Dim _credentials As reportingservice.DataSourceCredentials() = Nothing
Dim ei As ReportExecution.ExecutionInfo = rsExec.LoadReport(_reportName, historyID)
'definimos el parĂ¡metro
_values(0).Name = "an1_id"
_values(0).Value = 1
rsExec.SetExecutionParameters(_values, "en-us")
results = rsExec.Render(format, deviceInfo, extension, mimeType, encoding, warnings, streamIDs)
Dim stream As New System.IO.FileStream(filename, IO.FileMode.OpenOrCreate)
stream.Write(results, 0, results.Length)
stream.Close()
Try setting up a subscription via the Report Manager and specifying the Report Delivery Options value for 'Delivered By:' as 'Report Server File Share'.
This lets you specify a path for a report file to be written to - you will need to ensure that the Reporting Services server has write access to the destination.

How do I reload the formatted text into RTB?

I have a RTB in VB.NET, and put an event handler to save the formatted text into a file after encrypting it. However, I can't figure out how to reload the formatting - when I open it, it shows the symbols of formatting instead of formatted text. Here's my code:
Dim FileName As String = TextBox1.Text
File.Delete(FileName)
Dim EncryptElement As New TripleDESCryptoServiceProvider
EncryptElement.Key = {AscW("B"c), AscW("A"c), AscW("1"c), AscW("R"c), AscW("3"c), AscW("9"c), AscW("G"c), AscW("V"c), AscW("5"c), AscW("S"c), AscW("P"c), AscW("0"c), AscW("L"c), AscW("Z"c), AscW("4"c), AscW("M"c)} '128 bit Key
EncryptElement.IV = {AscW("N"c), AscW("B"c), AscW("5"c), AscW("3"c), AscW("G"c), AscW("L"c), AscW("2"c), AscW("Q"c)} ' 64 bit Initialization Vector
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
Dim cStream As New CryptoStream(fStream, New TripleDESCryptoServiceProvider().CreateEncryptor(EncryptElement.Key, EncryptElement.IV), CryptoStreamMode.Write)
Dim sWriter As New StreamWriter(cStream)
sWriter.WriteLine(RichTextBox1.Rtf)
sWriter.Close()
cStream.Close()
fStream.Close()
The above code is for saving, and the below code is for opening.
Dim FileName As String = TextBox1.Text
Dim DecryptElement As New TripleDESCryptoServiceProvider
DecryptElement.Key = {AscW("B"c), AscW("A"c), AscW("1"c), AscW("R"c), AscW("3"c), AscW("9"c), AscW("G"c), AscW("V"c), AscW("5"c), AscW("S"c), AscW("P"c), AscW("0"c), AscW("L"c), AscW("Z"c), AscW("4"c), AscW("M"c)}
DecryptElement.IV = {AscW("N"c), AscW("B"c), AscW("5"c), AscW("3"c), AscW("G"c), AscW("L"c), AscW("2"c), AscW("Q"c)}
Dim fStream As FileStream = File.Open(FileName, FileMode.OpenOrCreate)
Dim cStream As New CryptoStream(fStream, New TripleDESCryptoServiceProvider().CreateDecryptor(DecryptElement.Key, DecryptElement.IV), CryptoStreamMode.Read)
Dim sReader As New StreamReader(cStream)
Dim DecryptedData As String = ""
DecryptedData = sReader.ReadToEnd
RichTextBox1.AppendText(DecryptedData)
RichTextBox1.Enabled = True
Button1.Text = "OK"
sReader.Close()
cStream.Close()
fStream.Close()
Where is the problem?
You need RichTextBox1.SaveFile(SomeStream, RichTextBoxStreamType) I think StreamWriter is stuffing it up.
Oh and seeing as you just gave the world the keys for your encryption you might want to come up with a new one...
Added after comment not proven though.
Replace these two lines in your save routine
Dim sWriter As New StreamWriter(cStream)
sWriter.WriteLine(RichTextBox1.Rtf)
with
RichTextBox1.SaveFile(cStream,RichTextBoxStreamType.RichText);
and get rid of swriter.Close()
I think.

How to send Image as email attachment using Restful service

Below is the vb.net code that i'm using to receive an image from jquery ajax call..
Public Function MailKpiChart(ByVal img As String) As GenericResponse(Of Boolean) Implements IKPI.MailKpiChart
Dim SmtpServer As New Net.Mail.SmtpClient()
SmtpServer.Credentials = New Net.NetworkCredential("xyz#gmail.com", "password")
SmtpServer.Port = 587
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
Dim blStatus As Boolean
Try
Dim mailMessage As New MailMessage()
mailMessage.From = New MailAddress("from#gmail.com", ".Net Devoloper")
mailMessage.To.Add(New MailAddress("to#gmail.com"))
mailMessage.Subject = "test mail"
mailMessage.Body = "hello world"
Dim imgStream As New MemoryStream()
Dim Image As System.Drawing.Bitmap = getImagefromBase64(img)
Dim filename As String = "sample image"
Image.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png)
mailMessage.Attachments.Add(New Attachment(imgStream, filename, System.Net.Mime.MediaTypeNames.Image.Jpeg))
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network
SmtpServer.Send(mailMessage)
blStatus = True
Return ServiceUtility.BuildResponse(Of Boolean)(blStatus, String.Empty, String.Empty, 0)
Catch ex As Exception
Return ServiceUtility.BuildResponse(Of Boolean)(False, "",
ex.Message, AppConstants.ErrorSeverityCodes.HIGH)
End Try
End Function
and this is the function where i'm converting base64 string to an image
Public Function getImagefromBase64(ByVal uploadedImage As String) As Image
'get a temp image from bytes, instead of loading from disk
'data:image/gif;base64,
'this image is a single pixel (black)
Dim bytes As Byte() = Convert.FromBase64String(uploadedImage)
Dim image__1 As Image
Using ms As New MemoryStream(bytes)
ms.Write(bytes, 0, bytes.Length)
image__1 = Image.FromStream(ms)
End Using
Return image__1
End Function
and when i see my gmail inbox i c a mail with an attachment but i dont see the actual image which i've sent..i just c a blank image
Help Needed
Regards
I had the same issue and solved it by just adding the following line just before attaching the stream to the message.
imgStream.Position = 0
Regards,
Jonathan.
add your url - points to another web site
Dim bodys As String = "<html><head><title> example </title></head><body><table width='100%'>"
bodys += "<p><img width=135 height=77 src='http://www.example.com/image.gif'></p>"
bodys += "</table></body></html>"
Dim mails As New System.Net.Mail.MailMessage()
SmtpServer.Host = "127.0.0.1"
SmtpServer.Port = 25
mails = New System.Net.Mail.MailMessage()
mails.From = New System.Net.Mail.MailAddress("example#example.com")
mails.To.Add(txtEmail.Text)
mails.Subject = ""
mails.BodyEncoding = Encoding.UTF8
mails.IsBodyHtml = True
mails.Body = bodys.ToString()
SmtpServer.Send(mails)
A relative URL - points to a file within a web site
src="image.gif"
http://www.w3schools.com/tags/att_img_src.asp