Docusign download file from template which get illegal characters in file base64string format using Chilkat and rest api - vb.net

I can get file from template which passing templateid and documentid, when retrun from api , i will get as base64string format, and when i try to convert as byte,
I get an error "Additional information: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
Here the code which i used to download file from template
Dim rest As New Chilkat.Rest
Dim success As Boolean
Dim bTls As Boolean = True
Dim port As Integer = 443
Dim bAutoReconnect As Boolean = True
success = rest.Connect("demo.docusign.net", port, bTls, bAutoReconnect)
If (success <> True) Then
Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
rest.AddHeader("X-DocuSign-Authentication", "{ ""Username"": ""DocuSign#example.com"", ""Password"":""DocuSign_password"", ""IntegratorKey"":""DocuSign_Integrator_Key"" }")
Dim sbResponseBody As New Chilkat.StringBuilder
success = rest.FullRequestNoBodySb("GET", "/restapi/v2.1/accounts/xxxx/templates/xxxx-xxxx-xxxx-xxxx-xxxx/documents/x", sbResponseBody)
If (success <> True) Then
Debug.WriteLine(rest.LastErrorText)
Exit Sub
End If
Dim respStatusCode As Integer = rest.ResponseStatusCode
If (respStatusCode >= 400) Then
Debug.WriteLine("Response Status Code = " & respStatusCode)
Debug.WriteLine("Response Header:")
Debug.WriteLine(rest.ResponseHeader)
Debug.WriteLine("Response Body:")
Debug.WriteLine(sbResponseBody.GetAsString())
Exit Sub
End If
Dim jsonResponse As New Chilkat.JsonObject
jsonResponse.LoadSb(sbResponseBody)
Dim pdfBytes As Byte() = Convert.FromBase64String(sbResponseBody.ToString)
Regards,
Aravind

i changed my code from chilkat dll to Docusing dll 3.0.0 , using docusing dll i can download file from envelope, here i past my code , it will useful to some other developer.I am used .net framework code download file from file stream.
Private Function DoWnload(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As String
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using outFile As New System.IO.FileStream("C:\File.pdf", IO.FileMode.Create, IO.FileAccess.Write)
Do
bytesRead = results.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
outFile.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
End Using
Return ""
End Function
Dim envelopeDocItems As List(Of EnvelopeDocItem) = New List(Of EnvelopeDocItem) From {
New EnvelopeDocItem With {
.Name = "Combined",
.Type = "content",
.DocumentId = "combined"
},
New EnvelopeDocItem With {
.Name = "Zip archive",
.Type = "zip",
.DocumentId = "archive"
}
Thanks to Inbar Gazit...
Thanks and Regards,
Aravind

Here is an example: https://www.example-code.com/vbnet/docusign_download_envelope_document.asp
Also see the other VB.NET DocuSign examples: https://www.example-code.com/vbnet/docusign.asp

Related

How do I know the encoding of a webpage that I read in with vb.net?

I tried reading a webpage into my program using vb.net's HttpWebRequest. My problem has to do with figuring out the encoding of the web page before I actually read it into a string. When I read it in, some characters appear as diamonds with question-marks inside the diamonds. The web page itself looks fine in a browser, its just when I read it in that some characters aren't encoded right.
The original code I used was:
Dim myWebRequest As HttpWebRequest = WebRequest.Create(ourUri)
Dim myWebResponse As httpWebResponse = myWebRequest.GetResponse()
Then to try to get the encoding. I used:
Dim contentType As String = myWebResponse.ContentType
Dim charset As String = myWebResponse.CharacterSet
But both 'contentType' and 'charset' end up with the value 'text/html'. What I want to know is if the webpage is encoded in 'utf-8' or some other character set, so I can later retrieve it like this:
Dim receiveStream As Stream = myWebResponse.GetResponseStream()
Dim encode As Encoding = System.Text.Encoding.GetEncoding(charset)
Using reader As StreamReader = New StreamReader(receiveStream, encode)
So to sum up, there seems to be no way to inquire what the encoding is, and then use the answer to read the webpage the right way.
Is that true? Any help is appreciated.
The entire code of the routine (asked for by a commenter) follows:
Public Shared Function DownloadFileUsingURL(ByVal URLstring As String, ByVal descFilePathAndName As String, ByRef errorMessage As String, ByRef hadRedirect As Boolean,
ByRef newURL As String, ByRef isSecureConnection As Boolean, ByVal didSupplyfullfilename As Boolean, ByRef downloadedcontent As String,
ByRef httpTohttps As Boolean, ByRef httpsTohttp As Boolean, ByRef BytesRead As Integer) As Boolean
Dim ourUri As New Uri(URLstring)
Dim csh As New ClassSyncHttp
Dim expectSecureConnection As Boolean
Dim domainchanged As Boolean
newURL = ""
errorMessage = ""
hadRedirect = False
httpTohttps = False
httpsTohttp = False
isSecureConnection = False
If URLstring.ToLower.StartsWith("https:") Then
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
expectSecureConnection = True
Else
ServicePointManager.SecurityProtocol = SecurityProtocolType.SystemDefault
expectSecureConnection = False
End If
Try
Dim myWebRequest As HttpWebRequest = WebRequest.Create(ourUri) ' I changed webrequest to httpwebrequest
Dim cookieContainer As CookieContainer = New CookieContainer ' needs httpwebrequest to work
myWebRequest.CookieContainer = cookieContainer
myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials
myWebRequest.UserAgent = "BrowseNet"
myWebRequest.Timeout = ClassGlobalVariables.downloadTimeoutMilliseconds
myWebRequest.Credentials = CredentialCache.DefaultCredentials
Dim myWebResponse As HttpWebResponse = myWebRequest.GetResponse()
Dim contentType As String = myWebResponse.ContentType
Dim charset As String = myWebResponse.CharacterSet
If Not ourUri.Equals(myWebResponse.ResponseUri) Then
newURL = myWebResponse.ResponseUri.ToString
hadRedirect = True
If newURL.ToLower.StartsWith("https") Then
isSecureConnection = True
End If
compareURLs(URLstring, newURL, httpTohttps, domainchanged)
End If
Dim receiveStream As Stream = myWebResponse.GetResponseStream()
If didSupplyfullfilename Then
Using fs As FileStream = File.Create(descFilePathAndName)
receiveStream.CopyTo(fs)
BytesRead = fs.Length
End Using
Else
Dim encode As Encoding = System.Text.Encoding.GetEncoding(charset)
Using reader As StreamReader = New StreamReader(receiveStream, encode)
' receiveStream.Seek(0, SeekOrigin.Begin)
downloadedcontent = reader.ReadToEnd()
BytesRead = downloadedcontent.Length
End Using
End If
myWebResponse.Close()
If expectSecureConnection Then
isSecureConnection = True
Else
isSecureConnection = False
End If
Return True
Catch ex As webException
If expectSecureConnection Then
' guessing here that the problem was that was wrong about secure connection. (Problem could be elsewhere, of course)
isSecureConnection = False
httpsTohttp = True
If ex.HResult = System.Net.WebExceptionStatus.SecureChannelFailure Then
' not sure what to do
End If
'Else
' isSecureConnection = True
End If
errorMessage = ex.Message
Return False
End Try
End Function

How to download files from Docusign api using vb.net

How to download files once signed by all using vb.net. I manged to send envelope with template id.So i want to get back that file using envelope id, pls provide some sampe code to retrieve back files using vb.net.
Here code what i used in vb.net
Private Function DoWnload(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As String
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
''Dim f1 As FileStream = New FileStream("sample.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
' Return File(results, mimetype, docName)
Dim bytesRead As Integer
Dim buffer(4096) As Byte
Using outFile As New System.IO.FileStream("C:\File.pdf", IO.FileMode.Create, IO.FileAccess.Write)
Do
bytesRead = results.Read(buffer, 0, buffer.Length)
If bytesRead > 0 Then
outFile.Write(buffer, 0, bytesRead)
End If
Loop While bytesRead > 0
End Using
Return ""
End Function
Dim envelopeDocItems As List(Of EnvelopeDocItem) = New List(Of EnvelopeDocItem) From {
New EnvelopeDocItem With {
.Name = "Combined",
.Type = "content",
.DocumentId = "combined"
},
New EnvelopeDocItem With {
.Name = "Zip archive",
.Type = "zip",
.DocumentId = "archive"
}
in that docSelect what need to pass ? i passed documetid, getting error.
Regards,
Aravind
Private Function DoWork(ByVal accessToken As String, ByVal basePath As String, ByVal accountId As String, ByVal envelopeId As String, ByVal documents As List(Of EnvelopeDocItem), ByVal docSelect As String) As FileStreamResult
Dim config = New Configuration(New ApiClient(basePath))
config.AddDefaultHeader("Authorization", "Bearer " & accessToken)
Dim envelopesApi As EnvelopesApi = New EnvelopesApi(config)
Dim results As System.IO.Stream = envelopesApi.GetDocument(accountId, envelopeId, docSelect)
Dim docItem As EnvelopeDocItem = documents.FirstOrDefault(Function(d) docSelect.Equals(d.DocumentId))
Dim docName As String = docItem.Name
Dim hasPDFsuffix As Boolean = docName.ToUpper().EndsWith(".PDF")
Dim pdfFile As Boolean = hasPDFsuffix
Dim docType As String = docItem.Type
If ("content".Equals(docType) OrElse "summary".Equals(docType)) AndAlso Not hasPDFsuffix Then
docName += ".pdf"
pdfFile = True
End If
If "zip".Equals(docType) Then
docName += ".zip"
End If
Dim mimetype As String
If pdfFile Then
mimetype = "application/pdf"
ElseIf "zip".Equals(docType) Then
mimetype = "application/zip"
Else
mimetype = "application/octet-stream"
End If
Return File(results, mimetype, docName)
End Function
You will need to get the nuget from here - https://www.nuget.org/packages/DocuSign.eSign.dll/ but version 5.0.0 won't work with the code above, use version 4.3
Update: adding this additional class:
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Threading.Tasks
Namespace Models
Public Class EnvelopeDocItem
Public Property Name As String
Public Property Type As String
Public Property DocumentId As String
End Class
End Namespace

VB.Net signedXml "Invalid character in a Base-64 string"

I'm getting an error everytime I try to upload a XML file to an specific server.
It returns "Invalid character in a Base-64 string". Here the code I'm using to sign:
Public Sub Assinar03(ByVal strArqXMLAssinar As String, ByVal strUri As String, ByVal x509Certificado As X509Certificate2, ByVal strArqXMLAssinado As String)
Dim SR As StreamReader = Nothing
SR = File.OpenText(strArqXMLAssinar)
Dim vXMLString As String = SR.ReadToEnd()
SR.Close()
Dim _xnome As String = String.Empty
Dim _serial As String = String.Empty
If x509Certificado IsNot Nothing Then
_xnome = x509Certificado.Subject.ToString()
_serial = x509Certificado.SerialNumber
End If
Dim _X509Cert As New X509Certificate2()
Dim store As New X509Store("MY", StoreLocation.CurrentUser)
store.Open(OpenFlags.[ReadOnly] Or OpenFlags.OpenExistingOnly)
Dim collection As X509Certificate2Collection = DirectCast(store.Certificates, X509Certificate2Collection)
Dim collection1 As X509Certificate2Collection = DirectCast(collection.Find(X509FindType.FindBySerialNumber, _serial, False), X509Certificate2Collection)
If collection1.Count > 0 Then
_X509Cert = Nothing
For i As Integer = 0 To collection1.Count - 1
If DateTime.Now < collection1(i).NotAfter OrElse Not _X509Cert Is Nothing AndAlso _X509Cert.NotAfter < collection1(i).NotAfter Then
_X509Cert = collection1(i)
End If
Next
If _X509Cert Is Nothing Then _X509Cert = collection1(0)
Dim doc As New XmlDocument()
doc.PreserveWhitespace = False
doc.LoadXml(vXMLString)
Dim qtdeRefUri As Integer = doc.GetElementsByTagName(strUri).Count
Dim reference As New Reference()
Dim keyInfo As New KeyInfo()
Dim signedXml As New SignedXml(doc)
signedXml.SigningKey = _X509Cert.PrivateKey
Dim _Uri As XmlAttributeCollection = doc.GetElementsByTagName(strUri).Item(0).Attributes
For Each _atributo As XmlAttribute In _Uri
If _atributo.Name.ToLower.Trim = "Id".ToLower.Trim Then
reference.Uri = "#" + _atributo.InnerText
End If
Next
If reference.Uri Is Nothing Then reference.Uri = ""
reference.DigestMethod = SignedXml.XmlDsigSHA1Url
'--------------------------------------------------
Dim env As New XmlDsigEnvelopedSignatureTransform()
env.Algorithm = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"
reference.AddTransform(env)
'--------------------------
Dim c14 As New XmlDsigC14NTransform(False)
c14.Algorithm = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"
reference.AddTransform(c14)
'--------------------------
signedXml.AddReference(reference)
keyInfo.AddClause(New KeyInfoX509Data(_X509Cert))
'--------------------------
signedXml.KeyInfo = keyInfo
signedXml.ComputeSignature()
'--
Dim xmlDigitalSignature As XmlElement = signedXml.GetXml()
doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, True))
XMLDoc = New XmlDocument()
XMLDoc.PreserveWhitespace = False
XMLDoc = doc
Me.vXMLStringAssinado = XMLDoc.OuterXml
'-----------
Dim SW_2 As StreamWriter = File.CreateText(strArqXMLAssinado)
SW_2.Write(Me.vXMLStringAssinado)
SW_2.Close()
'-----------
End If
SR.Close()
End Sub
Is there something else I should add to the code?
The manual tells me to follow the instructions from https://www.w3.org/TR/xmldsig-core/
Turns out it was a line break when saving the document. I set the .PreserveWhitespace property to true before saving the .xml file and not it seems to be working.

VB.net synchronisation Folder and file [duplicate]

I am trying to download multiple directories from FTP server to my local machine,
I have tried this,
Const localFile As String = "C:\Documents and Settings\cr\Desktop\T\New Folder\"
Const remoteFile As String = "textbox.Text"
Const host As String = "ftp://ftp.example.com"
Const username As String = "username"
Const password As String = "password"
For i1 = 0 To ListBox1.SelectedItems.Count - 1
Dim li As New ListViewItem
li = ListView1.Items.Add(ListBox1.SelectedItems(i1))
Dim URI1 As String = host + remoteFile & "/" & ListBox1.SelectedItems(i1)
Dim ftp1 As System.Net.FtpWebRequest = CType(FtpWebRequest.Create(URI1), FtpWebRequest)
ftp1.Credentials = New System.Net.NetworkCredential(username, password)
ftp1.KeepAlive = False
ftp1.UseBinary = True
ftp1.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
Using response As System.Net.FtpWebResponse = CType(ftp1.GetResponse, System.Net.FtpWebResponse)
Using responseStream As IO.Stream = response.GetResponseStream
Dim length As Integer = response.ContentLength
Dim bytes(length) As Byte
'loop to read & write to file
Using fs As New IO.FileStream(localFile & ListBox1.SelectedItems(i1), IO.FileMode.Create)
Dim buffer(2047) As Byte
Dim read As Integer = 1
Do
read = responseStream.Read(buffer, 0, buffer.Length)
fs.Write(buffer, 0, read)
Loop Until read = 0 'see Note(1)
responseStream.Close()
fs.Flush()
fs.Close()
End Using
responseStream.Close()
End Using
response.Close()
End Using
li.BackColor = Color.Aquamarine
Next
But here the problem is that I am able to download multiple files from folders, but unable to download the sub directories and their contents from the main directory.
Basically the main directory consist of files and sub directories both. So is there any possible way to download sub directory and its contents from FTP?
Thanks in advance.
Translating my answer to C# Download all files and subdirectories through FTP to VB.NET:
The FtpWebRequest does not have any explicit support for recursive file download (or any other recursive operation). You have to implement the recursion yourself:
List the remote directory
Iterate the entries, downloading files and recursing into subdirectories (listing them again, etc.)
A tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the FtpWebRequest. The FtpWebRequest unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.
Your options are:
Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name". If that succeeds, it's a file, if that fails, it's a directory.
You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)
You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)
Sub DownloadFtpDirectory(
url As String, credentials As NetworkCredential, localPath As String)
Dim listRequest As FtpWebRequest = WebRequest.Create(url)
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails
listRequest.Credentials = credentials
Dim lines As List(Of String) = New List(Of String)
Using listResponse As FtpWebResponse = listRequest.GetResponse(),
listStream As Stream = listResponse.GetResponseStream(),
listReader As StreamReader = New StreamReader(listStream)
While Not listReader.EndOfStream
lines.Add(listReader.ReadLine())
End While
End Using
For Each line As String In lines
Dim tokens As String() =
line.Split(New Char() {" "}, 9, StringSplitOptions.RemoveEmptyEntries)
Dim name As String = tokens(8)
Dim permissions As String = tokens(0)
Dim localFilePath As String = Path.Combine(localPath, name)
Dim fileUrl As String = url + name
If permissions(0) = "d" Then
If Not Directory.Exists(localFilePath) Then
Directory.CreateDirectory(localFilePath)
End If
DownloadFtpDirectory(fileUrl + "/", credentials, localFilePath)
Else
Dim downloadRequest As FtpWebRequest = WebRequest.Create(fileUrl)
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile
downloadRequest.Credentials = credentials
Using downloadResponse As FtpWebResponse = downloadRequest.GetResponse(),
sourceStream As Stream = downloadResponse.GetResponseStream(),
targetStream As Stream = File.Create(localFilePath)
Dim buffer As Byte() = New Byte(10240 - 1) {}
Dim read As Integer
Do
read = sourceStream.Read(buffer, 0, buffer.Length)
If read > 0 Then
targetStream.Write(buffer, 0, read)
End If
Loop While read > 0
End Using
End If
Next
End Sub
Use the function like:
Dim credentials As NetworkCredential = New NetworkCredential("user", "mypassword")
Dim url As String = "ftp://ftp.example.com/directory/to/download/"
DownloadFtpDirectory(url, credentials, "C:\target\directory")
If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats; and recursive downloads.
For example with WinSCP .NET assembly you can download whole directory with a single call to the Session.GetFiles:
' Setup session options
Dim SessionOptions As SessionOptions = New SessionOptions
With SessionOptions
.Protocol = Protocol.Ftp
.HostName = "ftp.example.com"
.UserName = "user"
.Password = "mypassword"
End With
Using session As Session = New Session()
' Connect
session.Open(SessionOptions)
' Download files
session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
End Using
Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.
The Session.GetFiles method is recursive by default.
(I'm the author of WinSCP)
Check out my FTP class: Its pretty straight forward.
Take a look at my FTP class, it might be exactly what you need.
Public Class FTP
'-------------------------[BroCode]--------------------------
'----------------------------FTP-----------------------------
Private _credentials As System.Net.NetworkCredential
Sub New(ByVal _FTPUser As String, ByVal _FTPPass As String)
setCredentials(_FTPUser, _FTPPass)
End Sub
Public Sub UploadFile(ByVal _FileName As String, ByVal _UploadPath As String)
Dim _FileInfo As New System.IO.FileInfo(_FileName)
Dim _FtpWebRequest As System.Net.FtpWebRequest = CType(System.Net.FtpWebRequest.Create(New Uri(_UploadPath)), System.Net.FtpWebRequest)
_FtpWebRequest.Credentials = _credentials
_FtpWebRequest.KeepAlive = False
_FtpWebRequest.Timeout = 20000
_FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
_FtpWebRequest.UseBinary = True
_FtpWebRequest.ContentLength = _FileInfo.Length
Dim buffLength As Integer = 2048
Dim buff(buffLength - 1) As Byte
Dim _FileStream As System.IO.FileStream = _FileInfo.OpenRead()
Try
Dim _Stream As System.IO.Stream = _FtpWebRequest.GetRequestStream()
Dim contentLen As Integer = _FileStream.Read(buff, 0, buffLength)
Do While contentLen <> 0
_Stream.Write(buff, 0, contentLen)
contentLen = _FileStream.Read(buff, 0, buffLength)
Loop
_Stream.Close()
_Stream.Dispose()
_FileStream.Close()
_FileStream.Dispose()
Catch ex As Exception
MessageBox.Show(ex.Message, "Upload Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Sub DownloadFile(ByVal _FileName As String, ByVal _ftpDownloadPath As String)
Try
Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpDownloadPath)
_request.KeepAlive = False
_request.Method = System.Net.WebRequestMethods.Ftp.DownloadFile
_request.Credentials = _credentials
Dim _response As System.Net.FtpWebResponse = _request.GetResponse()
Dim responseStream As System.IO.Stream = _response.GetResponseStream()
Dim fs As New System.IO.FileStream(_FileName, System.IO.FileMode.Create)
responseStream.CopyTo(fs)
responseStream.Close()
_response.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Download Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Public Function GetDirectory(ByVal _ftpPath As String) As List(Of String)
Dim ret As New List(Of String)
Try
Dim _request As System.Net.FtpWebRequest = System.Net.WebRequest.Create(_ftpPath)
_request.KeepAlive = False
_request.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails
_request.Credentials = _credentials
Dim _response As System.Net.FtpWebResponse = _request.GetResponse()
Dim responseStream As System.IO.Stream = _response.GetResponseStream()
Dim _reader As System.IO.StreamReader = New System.IO.StreamReader(responseStream)
Dim FileData As String = _reader.ReadToEnd
Dim Lines() As String = FileData.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
For Each l As String In Lines
ret.Add(l)
Next
_reader.Close()
_response.Close()
Catch ex As Exception
MessageBox.Show(ex.Message, "Directory Fetch Error: ", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Return ret
End Function
Private Sub setCredentials(ByVal _FTPUser As String, ByVal _FTPPass As String)
_credentials = New System.Net.NetworkCredential(_FTPUser, _FTPPass)
End Sub
End Class
To initialize:
Dim ftp As New FORM.FTP("username", "password")
ftp.UploadFile("c:\file.jpeg", "ftp://domain/file.jpeg")
ftp.DownloadFile("c:\file.jpeg", "ftp://ftp://domain/file.jpeg")
Dim directory As List(Of String) = ftp.GetDirectory("ftp://ftp.domain.net/")
ListBox1.Items.Clear()
For Each item As String In directory
ListBox1.Items.Add(item)
Next

Google Drive Rest: convert does not work

I am using the G Drive REST endpoints (not .net client) to upload docx files through vb .net. My problem is that if even i declare the query parameter "convert" as true, the files are getting uploaded but they never auto-convert.
The first thing i do is to create a new file with POST and after that i upload the content with Put in the upload uri in a separate request.
it does not even work when i use the Google Playground to upload the docx files.
Public Shared Function UploadStream(fileStream As IO.Stream, filename As String, mimetype As String, target As String, accesstoken As String, Optional ConvertToGDoc As Boolean = False) As String
Try
Dim subject As String = ""
Dim doc As New Aspose.Words.Document
Dim docformat = Aspose.Words.FileFormatUtil.DetectFileFormat(fileStream) ' detect the format of the file Then 'check if the file is doc or docx
If docformat.LoadFormat = Aspose.Words.LoadFormat.Doc Or docformat.LoadFormat = Aspose.Words.LoadFormat.Docx Then 'check if the file is word document
doc = New Aspose.Words.Document(fileStream)
subject = doc.BuiltInDocumentProperties.Subject 'get the subject from the word file
If doc.BuiltInDocumentProperties.Subject = "" Then subject = "none"
Else
subject = "none" 'set the subject as none if the file is not word file
End If
Dim localmd5 = Files.MD5stream(fileStream)
Dim baseaddress = "https://www.googleapis.com/drive/v2/files?convert=" + ConvertToGDoc.ToString
Dim req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "POST"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
req.ContentType = "application/json"
Dim writer = New Newtonsoft.Json.Linq.JTokenWriter()
writer.WriteStartObject()
writer.WritePropertyName("title")
writer.WriteValue(filename)
writer.WritePropertyName("parents")
writer.WriteStartArray()
writer.WriteRawValue("{'id':'" + target + "'}")
writer.WriteEndArray()
writer.WritePropertyName("properties")
writer.WriteStartArray()
writer.WriteRawValue("{'key':'Subject','value':'" + subject + "'},{'key':'MD5','value':'" + localmd5 + "'},{'key':'Author','value':''}")
writer.WriteEndArray()
writer.WriteEndObject()
Dim bodybytes = Text.Encoding.UTF8.GetBytes(writer.Token.ToString)
req.ContentLength = bodybytes.Length
Dim requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
Dim resp As System.Net.HttpWebResponse = req.GetResponse()
Dim response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Dim json As Newtonsoft.Json.Linq.JObject
json = Newtonsoft.Json.Linq.JObject.Parse(response)
Dim fileId = json.SelectToken("id").ToString()
baseaddress = "https://www.googleapis.com/upload/drive/v2/files/" + fileId + "?uploadType=media&convert=" + ConvertToGDoc.ToString
req = Net.HttpWebRequest.Create(baseaddress)
req.Method = "Put"
req.Headers.Add("Authorization", "Bearer " + System.Web.HttpUtility.UrlEncode(accesstoken))
bodybytes = General.GetStreamAsByteArray(fileStream)
req.ContentLength = bodybytes.Length
req.ContentType = mimetype
requestStream = req.GetRequestStream
requestStream.Write(bodybytes, 0, bodybytes.Length)
requestStream.Close()
resp = req.GetResponse()
response = New IO.StreamReader(resp.GetResponseStream, False).ReadToEnd
Return fileId
Catch ex As Exception
Return Nothing
End Try
End Function
Shared Function GetStreamAsByteArray(ByVal stream As System.IO.Stream) As Byte()
Dim streamLength As Integer = Convert.ToInt32(stream.Length)
Dim fileData As Byte() = New Byte(streamLength) {}
stream.Position = 0
' Read the file into a byte array
stream.Read(fileData, 0, streamLength)
stream.Close()
ReDim Preserve fileData(fileData.Length - 2)
Return fileData
End Function
Public Shared Function MD5stream(ByVal File_stream As IO.Stream, Optional ByVal Seperator As String = Nothing) As String
Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
Dim Hash() As Byte = MD5.ComputeHash(File_stream)
Return Replace(BitConverter.ToString(Hash), "-", Seperator)
End Using
End Function
Had anyone else the same problem?