cosign - api :error when call to SignatureFieldCreateSign - cosign-api

I want to sign PDF document, I use CoSign API, The code was written in vb6.
When I use SAPI.SignetureFieldCreateSign (create signature and sign in the document), this method need to return 0 if everything ok, but it returns -1878850896.
My code:
Private Sub SignPDF()
'Custom Values
Dim rc As Integer
Dim SAPI As New SAPICrypt
Dim SESHandle As New SESHandle
Dim SFS As New SAPILib.SigFieldSettings
Dim TF As New SAPILib.timeFormat
Dim fileType As SAPI_ENUM_FILE_TYPE
Dim objFSO As FileSystemObject
Dim objFile As File
Dim objFolder As Folder
Dim strFolderPath As String
Dim flags As Integer
Dim filePath As String 'PDF file to sign
Dim username As String 'CoSign account username
Dim password As String 'CoSign account password
Dim domain As String 'CoSign account domain
Dim sigPageNum As Integer 'Create signature on the first page
Dim sigX As Integer 'Signature field X location
Dim sigY As Integer 'Signature field Y location
Dim sigWidth As Integer 'Signature field width
Dim sigHeight As Integer 'Signature field height
Dim timeFormat As String 'The display format of the time
Dim dateFormat As String 'The display format of the date
Dim appearanceMask As Integer 'Elements to display on the signature field
'Initialize variables
fileType = SAPI_ENUM_FILE_TYPE.SAPI_ENUM_FILE_ADOBE 'Type of the file to sign - PDF
flags = 0
strFolderPath = "C:\Users\jennya\Desktop\pdfFiles\"
username = "MyUsername"
password = "MyPassword"
domain = ""
sigPageNum = 1
sigX = 145
sigY = 125
sigWidth = 160
sigHeight = 45
timeFormat = "hh:mm:ss"
dateFormat = "dd/MM/yyyy"
appearanceMask = SAPI_ENUM_DRAWING_ELEMENT.SAPI_ENUM_DRAWING_ELEMENT_GRAPHICAL_IMAGE Or _
SAPI_ENUM_DRAWING_ELEMENT.SAPI_ENUM_DRAWING_ELEMENT_SIGNED_BY Or _
SAPI_ENUM_DRAWING_ELEMENT.SAPI_ENUM_DRAWING_ELEMENT_TIME
'Instantiate and Init SAPI
'Initialize SAPI library
rc = SAPI.Init
If rc <> SAPI_OK Then
MsgBox "error initializing SAPI", vbOKOnly, "Error"
'Exit Sub
End If
'HandleAcquire
'Acquire SAPI session handle
rc = SAPI.HandleAcquire(SESHandle)
If rc <> SAPI_OK Then
MsgBox "Failed in SAPIHandleAcquire"
End If
'Logon
'Personalize SAPI Session
rc = SAPI.Logon(SESHandle, username, domain, password)
If rc <> SAPI_OK Then
MsgBox "Failed to authenticate user"
End If
'Defining signature field settings
'Define signature field settings
SFS.Page = sigPageNum
SFS.x = sigX
SFS.y = sigY
SFS.Width = sigWidth
SFS.Height = sigHeight
SFS.appearanceMask = appearanceMask
SFS.SignatureType = SAPI_ENUM_SIGNATURE_TYPE.SAPI_ENUM_SIGNATURE_DIGITAL
SFS.DependencyMode = SAPI_ENUM_DEPENDENCY_MODE.SAPI_ENUM_DEPENDENCY_MODE_INDEPENDENT
TF.dateFormat = dateFormat
TF.timeFormat = timeFormat
TF.ExtTimeFormat = SAPI_ENUM_EXTENDED_TIME_FORMAT.SAPI_ENUM_EXTENDED_TIME_FORMAT_GMT 'Display GMT offset
SFS.timeFormat = TF
'Signing
Set objFSO = New FileSystemObject 'creates a new File System Object reference
If objFSO.FolderExists(strFolderPath) Then 'check if Source folder exists
Set objFolder = objFSO.GetFolder(strFolderPath) 'get Source folder
For Each objFile In objFolder.Files 'for every file in the folder.
filePath = objFile.Path
'Create and sign a new signature field in the document
rc = SAPI.SignatureFieldCreateSign(SESHandle, fileType, filePath, SFS, flags, "")
If rc <> SAPI_OK Then
MsgBox "Failed in SAPISignatureFieldCreateSign"
End If
Next
Else
MsgBox "Folder not exists"
End If
'Cleaning Up
'Release user context
rc = SAPI.Logoff(SESHandle)
If rc <> SAPI_OK Then
MsgBox "Failed to Logoff"
End If
SAPI.Finalize
End Sub

The error you got "-1878850896" when converted to Hex is 900302B0.
If you look this error up in the SAPI Reference Guide (you can find an online version under: http://www.arx.com/api - see exact location here) you will find the following:
SAPI_ERR_TOO_MANY_CERTS_TO_SELECT_FROM
Failed to get the default certificate. The user has more than one certificate and SAPI cannot determine which one should be used as the default.
0x900302b0
This indicates that the CoSign account with which you were trying to sign contains more than a single signing certificate, and in the your SAPI code you did not indicate the default certificate to use for signing.
Ari

Related

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.

Retrieve list of files using SVN revision number

TortoiseSVN provides a COM interface for retrieving information about a file.
Using VBA, I can get information about a file in the SVN repository by doing this:
Public Function getSvnURL(ByVal fullFilename As String)
Dim oSvn As Object
Set oSvn = CreateObject("SubWCRev.Object")
oSvn.GetWCInfo fullFilename, 1, 1
getSvnURL = oSvn.url
End Function
If I have an SVN revision number however, is there an API I can use to get the files that were part of that commit? Something like:
Public Function getFilesInRevision(revisionNumber As Integer) as Collection
Dim oSvn As Object
Set oSvn = CreateObject("SubWCRev.Object")
oSvn.GetWCInfo revisionNumber
getFilesInRevision= oSvn.fileList
End Function
I ended up using the following method:
Public Function getFilesForRevision(revisionNumber As Long, folder As String) As Collection
Dim command As String
command = "svn log -v -q -r " & revisionNumber & " " & folder
Dim rawText As String
rawText = ShellRun(command)
Dim lines() As String
lines = Split(rawText, vbLf)
Set getFilesForRevision = New Collection
Dim filenameRegex As Object
Set filenameRegex = CreateObject("VBScript.RegExp")
filenameRegex.Pattern = "\s{3}.\s(.*)"
Dim line As Variant
For Each line In lines
If filenameRegex.test(line) Then
getFilesForRevision.Add (filenameRegex.Execute(line).Item(0).submatches(0))
End If
Next line
End Function
Which relies on this method to run the command and store the console output:
'http://stackoverflow.com/questions/2784367/capture-output-value-from-a-shell-command-in-vba
Public Function ShellRun(sCmd As String) As String
'Run a shell command, returning the output as a string'
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec(sCmd)
Set oOutput = oExec.StdOut
'handle the results as they are written to and read from the StdOut object'
Dim s As String
Dim sLine As String
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend
ShellRun = s
End Function
Which can be called like this:
Sub getFilesForRevisionTest()
Dim files As Collection
Set files = getFilesForRevision(111041, "C:\SVN\")
Dim fullFilename As Variant
For Each fullFilename In files
Debug.Print fullFilename
Next fullFilename
End Sub

How insert password when i try to read my Excel? vb.net

I try to read a Excel, but have password (i know password) how insert password to read excel. My Code is like that:
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
'Dim FolderPath As String = ConfigurationManager.AppSettings("Upload")
Dim FilePath As String = Server.MapPath("~") & "\Upload\" & FileName
FileUpload1.SaveAs(FilePath)
Dim existingFile = New FileInfo(FilePath)
Dim pack As ExcelPackage = New ExcelPackage(existingFile)
Dim workBook As ExcelWorkbook = pack.Workbook
If workBook.Worksheets.Count > 0 Then ...
Error display on row:
Dim pack As ExcelPackage = New ExcelPackage(existingFile)
Error:
Can not open the package. Package is an OLE compound document. If this
is an encrypted package, please supply the password

streamwriter in windows store app - write text to file in VB

Does anybody have VB code to emulate Streamwriter for Windows Store?
I know it's been replaced by StorageFolder class but there is no VB sample in MSDN and I can't seem to translate properly from c# examples. Any help would be appreciated. I am just trying to write text (CSV) to a file and save it to the documents folder. In the code below windows store want a stream instead of strPath when I try dim-ing a streamwriter. (been playing with pickerdialog too, but that might be the next hurdle).
Dim strpath As String = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary & "\" & strFileName
'Build String for file*******************
Dim swExport As StreamWriter = New StreamWriter(strpath)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Possibly the simplest approach would be to use a MemoryStream if you like StreamWriter, so something like:
Dim sessionData As New MemoryStream()
' TODO: stage data in sessionData
Dim swExport As StreamWriter = New StreamWriter(sessionData)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Dim file As StorageFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync("towns.json", CreationCollisionOption.ReplaceExisting)
Using (fileStream As Stream = await file.OpenStreamForWriteAsync())
sessionData.Seek(0, SeekOrigin.Begin)
await sessionData.CopyToAsync(fileStream)
await fileStream.FlushAsync()
End Using
I was making it too difficult. To write to a file I just needed to use storagefolder and storagefile. I have also included the FileSavePicker in the code (note that filetypechoices is mandatory)
Private Async Function btnExport_Click(sender As Object, e As RoutedEventArgs) As Task
'Calls Filepicker to determine location
'Calls Sqlite to select ALL
'Creates CSV file to be saved at location chosen
'save to file
Dim intCount As Integer = "5"
Dim x As Integer
Dim strLine As String 'hold each line for export file
'Create FileName based on date
Dim strDate As String = Date.Today.ToString("MMddyyyy")
Dim strFileName As String = "Export" & strDate & ".csv"
' Configure save file dialog box
Dim dlgPicker As New Windows.Storage.Pickers.FileSavePicker
'add types for picker (manditory field)
Dim types = New List(Of String)
types.Add(".csv")
types.Add(".txt")
'set picker parameters
dlgPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads
dlgPicker.SuggestedFileName = strFileName '"Document" '
dlgPicker.FileTypeChoices.Add("CSV/TXT", types) 'manditory
dlgPicker.DefaultFileExtension = ".csv" 'Filter files by extension
dlgPicker.CommitButtonText = "Save"
' Show save file dialog box
Dim SaveCSV = Await dlgPicker.PickSaveFileAsync()
'************************get data************
Dim sbExport As Text.StringBuilder = New Text.StringBuilder
sbExport.AppendLine(strHeader)
For x = 0 To intCount - 1
strLine = "Get the text you want to write here"
sbExport.AppendLine(strLine)
Next x
'************************************
'write data to file
Await FileIO.WriteTextAsync(SaveCSV, sbExport.ToString)
Dim mb As MessageDialog = New MessageDialog("Done")
Await mb.ShowAsync()
End Function

Pdf to Tiff file covert in vb.net using PdfSharp.dll

i am using Pdfsharp.dll to convert tiff image to pdf file in vb.net, and it is successfull when i run in my machine, when i use it from other machine, which shows the Error like "Raw string contains invalid character with a value > 255.", please any one help me to fix error,
i using the PdfSharp.dll library and the following code
Dim objDoc As PdfDocument
Dim objPdfPage As PdfPage
Dim objTiffImg As Image
Dim objXImg As XImage
Dim iPageCount As Integer
Dim objXgr As XGraphics
Dim sPdfFile As String = Nothing
Dim objDir As DirectoryInfo
Dim objFile As FileInfo()
Dim objFileInfo As FileInfo
Try
objTiffImageSpliter = New TiffImageSplitter()
objDoc = New PdfDocument
iPageCount = objTiffImageSpliter.GetPageCount(sFileName)
For iCount As Integer = 0 To iPageCount - 1
objPdfPage = New PdfPage
objTiffImg = objTiffImageSpliter.getTiffImage(sFileName, iCount)
objXImg = XImage.FromGdiPlusImage(objTiffImg)
'objPdfPage.Height = objXImg.PointWidth
'objPdfPage.Width = objXImg.PointHeight
objDoc.Pages.Add(objPdfPage)
objXgr = XGraphics.FromPdfPage(objDoc.Pages(iCount))
objXgr.DrawImage(objXImg, 10, 10)
Next
sPdfFile = System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) & "\MY_FaxFile\"
If System.IO.Directory.Exists(sPdfFile) Then
objDir = New DirectoryInfo(sPdfFile)
objFile = objDir.GetFiles()
For Each objFileInfo In objFile
objFileInfo.Delete()
Next
sPdfFile &= "MyFax.pdf"
Else
System.IO.Directory.CreateDirectory(sPdfFile)
sPdfFile &= "MyFax.pdf"
End If
objDoc.Save(sPdfFile) ' This Line shows the Error.
objDoc.Close()
Catch ex As Exception
MsgBox(ex.ToString)
sPdfFile = Nothing
End Try
Return sPdfFile
I'm not familiar with this library, but based on your code and error message, I would guess that your App Data folder contains non-ASCII characters and that the PdfSharp library does not support non-ASCII characters in the filename.