Closure Compiler Service API - vb.net

Trying to intergrate the closure compiler service into one of my applications and having some issues.
Error being returned is "(413) Request Entity Too Large." Sounds reasonable but I know for a fact the service accepts files larger then the one I am sending it.
Private _HttpWebRequest As HttpWebRequest
Private _Result As StringBuilder
Private Const ClosureWebServiceURL As String = "http://closure-compiler.appspot.com/compile?output_format=xml&output_info=compiled_code" &
"&output_info=warnings" &
"&output_info=errors" &
"&output_info=statistics" &
"&compilation_level=ADVANCED_OPTIMIZATIONS" &
"&warning_level=default" &
"&js_code={0}"
_Result = New StringBuilder
_HttpWebRequest = DirectCast(WebRequest.Create(String.Format(ClosureWebServiceURL, HttpUtility.UrlEncode(_Script))), HttpWebRequest)
_HttpWebRequest.Method = "POST"
_HttpWebRequest.ContentType = "application/x-www-form-urlencoded"
_HttpWebRequest.ContentLength = 0
Dim response As WebResponse = _HttpWebRequest.GetResponse()
Using responseStream As Stream = response.GetResponseStream
Dim encoding As Encoding = System.Text.Encoding.GetEncoding("utf-8")
Using readStream As New StreamReader(responseStream, encoding)
Dim read(256) As Char
Dim count As Integer = readStream.Read(read, 0, 256)
While count > 0
Dim str As New String(read, 0, count)
_Result.Append(str)
count = readStream.Read(read, 0, 256)
End While
End Using
End Using
Any ideas?

Move your request data over to the POST's RequestStream instead of using the querystring.
Private _HttpWebRequest As HttpWebRequest
Private _Result As StringBuilder
Private Const ClosureWebServiceURL As String = "http://closure-compiler.appspot.com/compile?"
Private Const ClosureWebServicePOSTData As String = "output_format=xml&output_info=compiled_code" &
"&output_info=warnings" &
"&output_info=errors" &
"&output_info=statistics" &
"&compilation_level=ADVANCED_OPTIMIZATIONS" &
"&warning_level=default" &
"&js_code={0}"
'//Build's a large javascript for testing
Dim _Script As String = ""
For I = 1 To 100
_Script &= "function hello_" & I & "(name) { alert('Hello, ' + name);}hello('New user');"
Next
'//Create the POST data
Dim Data = String.Format(ClosureWebServicePOSTData, HttpUtility.UrlEncode(_Script))
_Result = New StringBuilder
_HttpWebRequest = DirectCast(WebRequest.Create(ClosureWebServiceURL), HttpWebRequest)
_HttpWebRequest.Method = "POST"
_HttpWebRequest.ContentType = "application/x-www-form-urlencoded"
'//Set the content length to the length of the data. This might need to change if you're using characters that take more than 256 bytes
_HttpWebRequest.ContentLength = Data.Length
'//Write the request stream
Using SW As New StreamWriter(_HttpWebRequest.GetRequestStream())
SW.Write(Data)
End Using
Dim response As WebResponse = _HttpWebRequest.GetResponse()
Using responseStream As Stream = response.GetResponseStream
Dim encoding As Encoding = System.Text.Encoding.GetEncoding("utf-8")
Using readStream As New StreamReader(responseStream, encoding)
Dim read(256) As Char
Dim count As Integer = readStream.Read(read, 0, 256)
While count > 0
Dim str As New String(read, 0, count)
_Result.Append(str)
count = readStream.Read(read, 0, 256)
End While
End Using
End Using
Trace.WriteLine(_Result)

Related

Can we call JSON POST API from VB.NET Windows App?

Here I am always getting "The remote server returned an error: (500) Internal Server Error.". Even the API is correct and working nicely through POSTMAN and in other languages also. Please guide me so solve this issue. I am attaching the function which is calling the API directly.
Private Function SendRequest() As String
Dim response As String
Dim request As WebRequest
Dim encoding As New System.Text.ASCIIEncoding
Dim uri = ""
Dim Tran = "15"
Dim Amount As Integer = 1000
Dim ReferenceID = "015bfa15-15ec-4dc7-903c-053ffacb6688"
Dim POS = "57290070"
Dim Store = "RESTSIM00000001"
Dim Chain = "J#P-Reg"
Dim JSONString = "{""tran"":""" & Tran & """,""amount"":""" & Amount & """,""reference"":""" & ReferenceID & """,""pos"":""" & POS & """,""store"":""" & Store & """,""chain"":""" & Chain & """}"
Dim jsonDataBytes() As Byte = encoding.GetBytes(JsonConvert.SerializeObject(JSONString))
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = "application/json"
request.Method = "POST"
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using
Return response
End Function

Docusign API implemention with our web application [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I want sample codes for send files envelope for signing with specify template, recipients and once signed by all recipients file need to download. I have accessToken, account key with demo sandbox login,Could u provide exact code in vb.net better, if not, then in c#.
2 steps
1.Pass file with recipients (multiple recipients also)
2.Once signed by all recipients get back files instead replay in sender mail
regards,
Aravind
There are plenty of materials for what you are trying to accomplish. You can first start by downloading the c# launcher from https://github.com/docusign/code-examples-csharp. It has 31 examples. You can register for our webinars if you want to ask specific questions here https://www.docusign.com/company/events. You can start as well by reading our guides https://developers.docusign.com/docs/esign-rest-api/how-to/. Another place you can find useful information is https://www.docusign.com/blog/developers.
Here is a basic VB example for DocuSign.
You will need to add OAuth authentication to use it in production.
' DocuSign Builder example. Generated: Wed, 12 Aug 2020 16:35:59 GMT
' DocuSign Ⓒ 2020. MIT License -- https://opensource.org/licenses/MIT
' #see DocuSign Developer Center
Imports System.Net
Imports System.Text
Imports System.IO
Imports Newtonsoft.Json.Linq
Module Program
Const accountId As String = ""
Const accessToken As String = ""
Const baseUri As String = "https://demo.docusign.net"
Const documentDir = "Assets"
Function SendDocuSignEnvelope() As String ' RETURNS envelopeId
' Note: The JSON string constant uses the VB interpolated format.
' See https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/strings/interpolated-strings
' This format enables you to use the JSON as a template within your app, and
' replace values with interpolated/dynamic values. Remember that string values must be
' escaped per the JSON string rules. (Escape " as \")
Dim envelopeDefinition As String = $"{{
""emailSubject"": ""Please sign the attached document"",
""status"": ""sent"",
""documents"": [
{{
""name"": ""Example document"",
""fileExtension"": ""pdf"",
""documentId"": ""1""
}}
],
""recipients"": {{
""signers"": [
{{
""email"": ""signer_email#example.com"",
""name"": ""Signer's name"",
""recipientId"": ""1"",
""clientUserId"": ""1000"",
""tabs"": {{
""signHereTabs"": [
{{
""anchorString"": ""/sig1/"",
""anchorXOffset"": ""20"",
""anchorUnits"": ""pixels""
}}
]
}}
}}
]
}}
}}"
Dim documents = {
(mimeType:="application/pdf", filename:="Example document", documentId:="1", diskFilename:="anchorfields.pdf")
}
Dim url As String = $"{baseUri}/restapi/v2.1/accounts/{accountId}/envelopes"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
Dim CRLF As String = vbCrLf
Dim boundary As String = "multipartboundary_multipartboundary"
Dim hyphens As String = "--"
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.ContentType = $"multipart/form-data; boundary={boundary}"
postReq.Accept = "application/json"
postReq.Headers.Add("Authorization", $"Bearer {accessToken}")
postReq.UserAgent = "DS Builder tool VB"
' Send request as a multipart mime message with the
' documents included in binary format (not Base64 encoded)
Dim encoding As New UTF8Encoding
Dim byteData As Byte()
Dim stringBuffer As String
Dim postreqstream As Stream = postReq.GetRequestStream()
Dim postLength As Int32 = 0
Dim rawFilePath As String = Directory.GetCurrentDirectory() ' \\Mac\Home\www\VB_Example\VB_Example\bin\Debug\netcoreapp3.1\
Dim docFilePath As String = Path.GetFullPath(Path.Combine(rawFilePath, "..\..\..\" & documentDir & "\"))
Dim document As (mimeType As String, filename As String, documentId As String, diskFilename As String)
stringBuffer = 'Send preamble and JSON request
hyphens & boundary & CRLF & "Content-Type: application/json" &
CRLF & "Content-Disposition: form-data" & CRLF & CRLF & envelopeDefinition
byteData = encoding.GetBytes(stringBuffer)
postreqstream.Write(byteData, 0, byteData.Length)
postLength += byteData.Length
For Each document In documents
stringBuffer = CRLF & hyphens & boundary & CRLF & $"Content-Type: {document.mimeType}" &
CRLF & $"Content-Disposition: file; filename=""{document.filename}"";documentid={document.documentId}" & CRLF & CRLF
byteData = encoding.GetBytes(stringBuffer)
postreqstream.Write(byteData, 0, byteData.Length)
postLength += byteData.Length
' add the file's contents
Dim inputFile = File.Open(docFilePath & document.diskFilename, FileMode.Open)
' 1/2 Megabyte buffer. Dim statements specifies last index, so we subtract 1
Dim bufferSize As Integer = 1024 * 512
Dim bytes = New Byte(bufferSize - 1) {}
Dim bytesRead As Int32 = inputFile.Read(bytes, 0, bufferSize)
While bytesRead > 0
postreqstream.Write(bytes, 0, bytesRead)
postLength += bytesRead
bytesRead = inputFile.Read(bytes, 0, bufferSize)
End While
inputFile.Close()
Next
stringBuffer = CRLF & hyphens & boundary & hyphens & CRLF 'Send postamble
byteData = encoding.GetBytes(stringBuffer)
postreqstream.Write(byteData, 0, byteData.Length)
postLength += byteData.Length
postReq.ContentLength = postLength
Try
Dim postresponse As HttpWebResponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
Dim postreqreader = New StreamReader(postresponse.GetResponseStream())
Dim resultsJSON As String = postreqreader.ReadToEnd
Console.WriteLine($"Create envelope results: {resultsJSON}")
Dim resultsJObj As JObject = JObject.Parse(resultsJSON)
Dim envelopeId As String = resultsJObj("envelopeId")
Console.WriteLine($"EnvelopeId: {envelopeId}")
Return envelopeId
Catch Ex As WebException
Console.WriteLine($"Error while creating envelope! {Ex.Message}")
If Ex.Response IsNot Nothing Then
Console.WriteLine($"Error response: {New StreamReader(Ex.Response.GetResponseStream).ReadToEnd}")
End If
Return ""
End Try
End Function
Sub RecipientView(envelopeId As String)
Dim doRecipientView As Boolean = True
Dim recipientViewRequest As String = $"{{
""returnUrl"": ""https://docusign.com"",
""authenticationMethod"": ""none"",
""clientUserId"": ""1000"",
""email"": ""signer_email#example.com"",
""userName"": ""Signer's name""
}}"
Dim url As String = $"{baseUri}/restapi/v2.1/accounts/{accountId}/envelopes/{envelopeId}/views/recipient"
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = False
postReq.ContentType = "application/json"
postReq.Accept = "application/json"
postReq.Headers.Add("Authorization", $"Bearer {accessToken}")
postReq.UserAgent = "DS Builder tool VB"
Dim encoding As New UTF8Encoding
Dim byteData As Byte()
Dim postreqstream As Stream = postReq.GetRequestStream()
byteData = encoding.GetBytes(recipientViewRequest)
postreqstream.Write(byteData, 0, byteData.Length)
postReq.ContentLength = byteData.Length
Try
Dim postresponse As HttpWebResponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
Dim postreqreader = New StreamReader(postresponse.GetResponseStream())
Dim resultsJSON As String = postreqreader.ReadToEnd
Dim resultsJObj As JObject = JObject.Parse(resultsJSON)
Dim viewUrl As String = resultsJObj("url")
Console.WriteLine("Create recipient view succeeded.")
Console.WriteLine("Open the signing ceremony's long URL within 5 minutes:")
Console.WriteLine(viewUrl)
Catch Ex As WebException
Console.WriteLine($"Error requesting recipient view! {Ex.Message}")
If Ex.Response IsNot Nothing Then
Console.WriteLine($"Error response: {New StreamReader(Ex.Response.GetResponseStream).ReadToEnd}")
End If
End Try
End Sub
' The mainline
Sub Main(args As String())
Console.WriteLine("Starting...")
Dim envelopeId As String = SendDocuSignEnvelope()
RecipientView(envelopeId)
Console.WriteLine("Done.")
End Sub
End Module

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?

REST WebService: how to get zip file from web service to a client

I'm trying to create a function to download a zip file made ​​available from a REST WebService with a client that calls the Web Service(both written in VB.Net).
WebService side I have the following code:
Public Function DownloadZipFile(filename As String) As Stream Implements ILiveUpdateWS.DownloadZipFile
WebOperationContext.Current.OutgoingResponse.ContentType = "application/txt"
Dim f As New FileStream(DESTINATION_PATH_ZIP_FILE + "Upgrade_Package.zip",FileMode.Open)
Dim length As Integer = CType(f.Length, Integer)
WebOperationContext.Current.OutgoingResponse.ContentLength = length
Dim buffer As Byte() = New Byte(length) {}
Dim sum As Integer = 0
Dim count As Integer
While ((count = f.Read(buffer, sum, length - sum)) > 0)
sum += count
End While
f.Close()
Dim mimeType = ""
WebOperationContext.Current.OutgoingResponse.ContentType = mimeType
Return New MemoryStream(buffer)
End Function
Client side I have the following code:
sUri = "http://localhost:35299/LiveUpdateWS/Download?" & "piv"
....
Dim req As HttpWebRequest = WebRequest.Create(sUri.ToString())
req.Method = "GET"
req.KeepAlive = False
Dim response As HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
Response has ContentLenght = 242699, so seems to receive the stream, but StIn seems to be empty. What is the best solution to solve the problem?
I think you've forgot to read from the StreamReader to the file.
Dim inSaveFile As String = "C:\stream\test.doc"
If Dir(inSaveFile) <> vbNullString Then
Kill(inSaveFile)
End If
Dim swFile As System.IO.StreamWriter
Dim fs As System.IO.FileStream = System.IO.File.Open(inSaveFile, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)
swFile = New System.IO.StreamWriter(fs, System.Text.Encoding.Default)
Dim response1 As System.Net.HttpWebResponse = req.GetResponse()
Dim resp As Net.HttpWebResponse = DirectCast(req.GetResponse(), Net.HttpWebResponse)
Dim stIn As IO.StreamReader = New IO.StreamReader(response1.GetResponseStream(), encoding:=System.Text.Encoding.Default)
swFile.WriteLine(stIn.ReadToEnd)
swFile.Close()
fs.Close()

Having problems with httpost json string through vb.net

Here's my code that I am using to send as post to the specified URL.
Dim url = "http://www.abc.com/new/process"
Dim data As String = nvc.ToString
Dim postAddress = New Uri(Url)
Dim request = DirectCast(WebRequest.Create(postAddress), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/json"
Dim postByteData As Byte() = UTF8Encoding.UTF8.GetBytes(data)
request.ContentLength = postByteData.Length
Using postStream As Stream = request.GetRequestStream()
postStream.Write(postByteData, 0, postByteData.Length)
End Using
Using resp = TryCast(request.GetResponse(), HttpWebResponse)
Dim reader = New StreamReader(resp.GetResponseStream())
result.Response = reader.ReadToEnd()
End Using
Now the problem is I don't get any exception here, but the response I'm supposed to get after posting (success or error) is not coming to my end. The URL is fine, I checked it. Am I sending it the right way?
I believe the issue is that ReadToEnd method on StreamReader internally uses the Length property. This will be null if the server doesn't send a length in the http header. Try using memory stream and a buffer instead:
Dim url = "http://my.posturl.com"
Dim data As String = nvc.ToString()
Dim postAddress = New Uri(url)
Dim request As HttpWebRequest = WebRequest.Create(postAddress)
request.Method = "POST"
request.ContentType = "application/json"
Dim postByteData As Byte() = UTF8Encoding.UTF8.GetBytes(data)
request.ContentLength = postByteData.Length
Using postStream As Stream = request.GetRequestStream()
postStream.Write(postByteData, 0, postByteData.Length)
End Using
Using resp = TryCast(request.GetResponse(), HttpWebResponse)
Dim b As Byte() = Nothing
Using stream As Stream = resp.GetResponseStream()
Using ms As New MemoryStream()
Dim count As Integer = 0
Do
Dim buf As Byte() = New Byte(1023) {}
count = stream.Read(buf, 0, 1024)
ms.Write(buf, 0, count)
Loop While stream.CanRead AndAlso count > 0
b = ms.ToArray()
End Using
End Using
Console.WriteLine("Response: " + Encoding.UTF8.GetString(b))
Console.ReadLine()
End Using