Request Signature Docusign Rest API vb.net - 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.

Related

Google Sheets API V4 VB Net BatchUpdate - Upload

I am attempting to load the contents of a CSV file directly to an existing Google Sheet using the batch update method.
The problem is that my code is only uploading the last record, but from what I can tell the request object has all the data.
So far I am able to loop through the CSV file and cast each row to a Google Sheets ValueRange and add each ValueRange to a data object in order to apply it to the RequestBody required by the Google Sheets API.
This is all based on the API documentation available from Google.
Google Sheets API V4 Batch Update
I tossed in a few Message Boxes just to see what is happening in the background.
Below is the code I am using currently, and a sample set of data you can put into a csv file to run.
It appears that I am missing something with the upload request itself, if anyone has any input or experience with this I can't seem to get past this.
*Note: this code is simply a VB .Net winform app with a single button added to the form.
Imports System.Threading
Imports Google.Apis.Sheets.v4
Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Services
Imports Microsoft.VisualBasic.FileIO
Imports Google.Apis.Sheets.v4.Data
Imports Data = Google.Apis.Sheets.v4.Data
Public Class Form1
Dim ClientID As String = "<GOOGLE CLIENT>.apps.googleusercontent.com"
Dim ClientSecret As String = "<CLIENT SECRET>"
Dim Scopes As String() = {SheetsService.Scope.Spreadsheets}
Dim credential As UserCredential = GoogleWebAuthorizationBroker.AuthorizeAsync(New ClientSecrets() With {.ClientId = ClientID,
.ClientSecret = ClientSecret},
Scopes, "user",
CancellationToken.None).Result
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim r As Integer = 1
Dim oblist = New List(Of Object)
Dim sheetsService As SheetsService = New SheetsService(New BaseClientService.Initializer With {
.HttpClientInitializer = credential,
.ApplicationName = "Google-SheetsSample/0.1"
})
Dim spreadsheetId As String = "<SPREADSHEET ID>"
Dim valueInputOption As String = "RAW"
Dim valueRanges As ValueRange = New ValueRange()
Dim data As List(Of Data.ValueRange) = New List(Of Data.ValueRange)
Dim tfp As New TextFieldParser("<PATH TO CSV FILE I WANT TO UPLOAD>")
tfp.SetDelimiters(",")
tfp.TextFieldType = FieldType.Delimited
'tfp.ReadLine() ' skip header
While tfp.EndOfData = False
Dim fields = tfp.ReadFields()
Dim range2 As String = "A" & r ' range to update
valueRanges.MajorDimension = "ROWS" '"ROWS";//COLUMNS
valueRanges.Range = range2 ' apply range to ValueRnage
' My csv has 12 fields
oblist = New List(Of Object)() From {
fields(0), fields(1), fields(2), fields(3), fields(4), fields(5), fields(6), fields(7), fields(8), fields(9), fields(10), fields(11)
}
valueRanges.Values = New List(Of IList(Of Object)) From { ' add list of objects pulled from TextFieldParser to ValueRange
oblist
}
data.Add(valueRanges) ' Add valueRange to data for RequestBody
r += 1 ' Increment Range
End While
MsgBox("Count of value ranges in data object : " & data.Count)
Dim requestBody As Data.BatchUpdateValuesRequest = New Data.BatchUpdateValuesRequest()
requestBody.ValueInputOption = valueInputOption
requestBody.Data = data
MsgBox("Request body data : " & requestBody.Data.Count)
Dim request As SpreadsheetsResource.ValuesResource.BatchUpdateRequest = sheetsService.Spreadsheets.Values.BatchUpdate(requestBody, spreadsheetId)
Dim response As Data.BatchUpdateValuesResponse = request.Execute()
MsgBox("Count of Rows uploaded to google sheet : " & response.TotalUpdatedRows)
End Sub
End Class
CSV - EXAMPLE -
Column 1,Column 2,Column 3,Column 4,Column 5,Column 6,Column 7,Column 8,Column 9,Column 10,Column 11,Column 12
ex12,ex34,ex56,ex78,ex100,ex122,ex144,ex166,ex188,ex210,ex232,ex254
ex13,ex35,ex57,ex79,ex101,ex123,ex145,ex167,ex189,ex211,ex233,ex255
ex14,ex36,ex58,ex80,ex102,ex124,ex146,ex168,ex190,ex212,ex234,ex256
ex15,ex37,ex59,ex81,ex103,ex125,ex147,ex169,ex191,ex213,ex235,ex257
ex16,ex38,ex60,ex82,ex104,ex126,ex148,ex170,ex192,ex214,ex236,ex258
ex17,ex39,ex61,ex83,ex105,ex127,ex149,ex171,ex193,ex215,ex237,ex259
ex18,ex40,ex62,ex84,ex106,ex128,ex150,ex172,ex194,ex216,ex238,ex260
ex19,ex41,ex63,ex85,ex107,ex129,ex151,ex173,ex195,ex217,ex239,ex261
ex20,ex42,ex64,ex86,ex108,ex130,ex152,ex174,ex196,ex218,ex240,ex262
ex21,ex43,ex65,ex87,ex109,ex131,ex153,ex175,ex197,ex219,ex241,ex263
Here I create one code .. The difference is only you pass List to ValueRange whereas there should be IList ..
But for conversion from list to Ilist I used objList.ToList () and I don't know it's drawback you need to check
And also you have to create new object of valueRange within while loop
Dim sheetId = FileId
Dim service = GetGoogleAPPSheetService()
Dim val_range As ValueRange
Dim DataList As List(Of ValueRange) = New List(Of ValueRange)
Dim I As Integer = 0
Dim objList As List(Of Object)
Dim objMainList As List(Of IList(Of Object))
Dim objIlIst As IList(Of Object)
Dim objImainList As IList(Of IList(Of Object))
For Each dr As DataRow In dt.Rows
I += 1
val_range = New ValueRange
val_range.Range = "A" & I.ToString
objList = New List(Of Object) From {dr(0).ToString, dr(1).ToString}
objMainList = New List(Of IList(Of Object)) From {objList.ToList()}
val_range.Values = objMainList.ToList
DataList.Add(val_range)
Next
Dim req_body As BatchUpdateValuesRequest = New BatchUpdateValuesRequest
req_body.ValueInputOption = "RAW"
req_body.Data = DataList.ToList
Dim request As SpreadsheetsResource.ValuesResource.BatchUpdateRequest = service.Spreadsheets.Values.BatchUpdate(req_body, sheetId)
Dim response As BatchUpdateValuesResponse = request.Execute
MsgBox("Count of Rows uploaded to google sheet : " & response.TotalUpdatedRows)
Catch ex As Exception
Throw ex
End Try

VB.net Crystal report export to html and send as html mail body using outlook

I am trying to send contents of a crystal report as email body using outlook application.
Here is my code in VB.net
Imports outlook = Microsoft.Office.Interop.Outlook
Dim a As String = something.ConnectionString
Dim cryRpt As ReportDocument
Dim username As String = a.Split("=")(3).Split(";")(0) 'get username
Dim password As String = a.Split("=")(4).Split(";")(0) 'get password
cryRpt = New ReportDocument()
Dim Path As String = Application.StartupPath
Dim svPath As String = Application.StartupPath & "\PDF"
If Not Directory.Exists(svPath) Then
Directory.CreateDirectory(svPath)
End If
cryRpt.Load(Path & "\Reports\dr.rpt")
CrystalReportViewer1.ReportSource = cryRpt
cryRpt.SetDatabaseLogon(username, password)
CrystalReportViewer1.Refresh()
Dim myExportOptions As ExportOptions
myExportOptions = cryRpt.ExportOptions
myExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
myExportOptions.ExportFormatType = ExportFormatType.HTML40 'i tried HTML32 also
Dim html40FormatOptions As HTMLFormatOptions = New HTMLFormatOptions()
html40FormatOptions.HTMLBaseFolderName = svPath
html40FormatOptions.HTMLFileName = "dr.htm"
html40FormatOptions.HTMLEnableSeparatedPages = False
html40FormatOptions.HTMLHasPageNavigator = False
html40FormatOptions.UsePageRange = False
myExportOptions.FormatOptions = html40FormatOptions
cryRpt.Export()
Try
Dim oApp As outlook.Application
oApp = New outlook.Application
Dim oMsg As outlook.MailItem
oMsg = oApp.CreateItem(outlook.OlItemType.olMailItem)
oMsg.Subject = txtSubject.Text
oMsg.BodyFormat = outlook.OlBodyFormat.olFormatHTML
oMsg.HTMLBody = ""
oMsg.HTMLBody = getFileAsString(svPath & "\PoPrt\QuotPrt.html")
oMsg.To = txtEmailId.Text
Dim ccArray As New List(Of String)({txtCC1.Text, txtCC2.Text, txtCC3.Text})
Dim cclis As String = String.Join(",", ccArray.Where(Function(ss) Not String.IsNullOrEmpty(ss)))
oMsg.CC = cclis
oMsg.Display(True)
Catch ex As Exception
MsgBox("Something went wrong", vbExclamation)
End Try
SvFormPanel3.Visible = False
the function
Private Function getFileAsString(ByVal file As String) As String
Dim reader As System.IO.FileStream
Try
reader = New System.IO.FileStream(file, IO.FileMode.Open)
Catch e As Exception
MsgBox("Something went wrong. " + e.Message, vbInformation)
End Try
Dim resultString As String = ""
Dim b(1024) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While reader.Read(b, 0, b.Length) > 0
resultString = resultString & temp.GetString(b)
Array.Clear(b, 0, b.Length)
Loop
reader.Close()
Return resultString
End Function
The report will get exported to the specified location as html. And when we manually open that html file it displays perfectly with border lines and all.
But when its getting added as html body of outlook application, the formatting will be gone, and looks scattered.
can anyone help
Did you try this?
Open outlook, go to, File>Options>Mail
go to section MessageFormat and untick "Reduce message size by removing format..."
I have solved the issue by exporting it into PDF and then convert to Image and embed in email body.

Big Query Pagination in vb.net

I am trying to page through BigQuery data with vb.net. I keep getting the same first page of data with my code. The way I understand, I need to set the pagetoken of the response to look at the next page.
With the following code, I only get the first page of data while never exiting my loop.
For the login I was setting the Oauthtoken of my queryrequest and that was getting the first page fine, but no attempt is made to page through the results that way.
I appreciate any lead in the right direction.
Dim DT As New DataTable
Dim ErrMessage As String = ""
Try
Dim INIT As New BigqueryService.Initializer
Dim scopes As IList(Of String) = New List(Of String)()
scopes.Add(BigqueryService.Scope.Bigquery)
Dim credential As UserCredential
Using stream As New FileStream("client_secrets.json", FileMode.Open, FileAccess.Read)
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, scopes, "user", CancellationToken.None, New FileDataStore("BQ.App")).Result
End Using
INIT.HttpClientInitializer = credential
Dim service As New BigqueryService(INIT)
Dim j As JobsResource = service.Jobs
Dim req As New QueryRequest
req.Query = tQuery.Text
Dim QRequest As JobsResource.QueryRequest = j.Query(req, projectId)
QRequest.OauthToken = MyAccessToken
Dim JOBID As String = QRequest.Execute.JobReference.JobId
Dim DATA = QRequest.Execute
Dim schema = DATA.Schema
For Each col In schema.Fields
DT.Columns.Add(col.Name)
Next
Dim page_Tok = ""
Dim rr As GetQueryResultsResponse
While True
Try
rr.PageToken = page_Tok
Catch ex As Exception
'No Token Yet
End Try
rr = j.GetQueryResults(projectId, JOBID).Execute
page_Tok = rr.PageToken
If rr.JobComplete = True Then
If page_Tok = "" Then
Exit While
End If
End If
Dim resp2 = rr.Rows
For Each row In resp2
Dim DR As DataRow = DT.NewRow
For f = 0 To row.F.Count - 1
Dim field = row.F
DR(f) = row.F(f).V
Next
DT.Rows.Add(DR)
Next
End While
Catch ex As Exception
ErrMessage = ex.Message
End Try
I'm not a VB expert, but you're not setting the page token in the GetQueryResultsRequest, you're setting it in the response. See https://developers.google.com/resources/api-libraries/documentation/bigquery/v2/csharp/latest/classGoogle_1_1Apis_1_1Bigquery_1_1v2_1_1JobsResource_1_1GetQueryResultsRequest.html
I think that this will work:
req = j.GetQueryResults(projectId, JOBID)
req.PageToken = page_tok
rr = req.Execute

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

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

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.