Docusign API implemention with our web application [closed] - vb.net

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

Related

Uploading File as FormData in vb.net?

I'm having trouble uploading some form data to an API endpoint in vb.net.
Example From Vendor:
curl -X POST -H 'Authorization: Token token=sfg999666t673t7t82'
-H 'Content-Type: multipart/form-data' -H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
-F file=#/Users/user1/Downloads/download.jpeg -F file_name=nameForFile
-F is_shared=true -F targetable_id=1 -F targetable_type=Lead -X POST "https://domain.freshsales.io/api/documents"
VB.NET CODE
Shameless pulled from (Upload files with HTTPWebrequest (multipart/form-data))
Private Sub HttpUploadFile(ByVal filePath As String, ByVal fileParameterName As String, ByVal contentType As String, ByVal otherParameters As Specialized.NameValueCollection)
Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
Dim newLine As String = System.Environment.NewLine
Dim boundaryBytes As Byte() = Text.Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create("https://domain.freshsales.io/api/documents")
request.ContentType = "multipart/form-data; boundary=" & boundary
request.Method = "POST"
request.KeepAlive = True
Using requestStream As IO.Stream = request.GetRequestStream()
Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"
For Each key As String In otherParameters.Keys
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim formItem As String = String.Format(formDataTemplate, key, newLine, otherParameters(key))
Dim formItemBytes As Byte() = Text.Encoding.UTF8.GetBytes(formItem)
requestStream.Write(formItemBytes, 0, formItemBytes.Length)
Next key
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
Dim headerBytes As Byte() = Text.Encoding.UTF8.GetBytes(header)
requestStream.Write(headerBytes, 0, headerBytes.Length)
Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim buffer(4096) As Byte
Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)
Do While (bytesRead > 0)
requestStream.Write(buffer, 0, bytesRead)
bytesRead = fileStream.Read(buffer, 0, buffer.Length)
Loop
End Using
Dim trailer As Byte() = Text.Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
requestStream.Write(trailer, 0, trailer.Length)
End Using
Dim response As Net.WebResponse = Nothing
Try
response = request.GetResponse()
Using responseStream As IO.Stream = response.GetResponseStream()
Using responseReader As New IO.StreamReader(responseStream)
Dim responseText = responseReader.ReadToEnd()
Diagnostics.Debug.Write(responseText)
End Using
End Using
Catch exception As Net.WebException
response = exception.Response
If (response IsNot Nothing) Then
Using reader As New IO.StreamReader(response.GetResponseStream())
Dim responseText = reader.ReadToEnd()
Diagnostics.Debug.Write(responseText)
End Using
response.Close()
End If
Finally
request = Nothing
End Try
End Sub
Calling The Function
Here is my call:
Dim headers As NameValueCollection = New NameValueCollection()
headers.Add("Token", "token=youguessedit;")
Dim nvc As NameValueCollection = New NameValueCollection()
nvc.Add("is_shared", true)
nvc.Add("targetable_id", 1)
nvc.Add("targetable_type", "Lead")
HttpUploadFile("c:\test\file.pdf", "file", "application/pdf", nvc, headers);
I think part of my issue is in the way the headers are attached here:
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3}{2}{2}"
In that the API endpoint is expecting file= and file_name= how can I correct the headers?
Can anyone point out where else I have gone wrong? Is there an easier way of doing this?
Here's a simple Console app example using HttpClient with a MultipartFormDataContent which takes care of all the headers and streaming the file, this example also works as-is thanks to Postman-Echo, if there's a requirement for additional headers (only Token is shown here) be sure to add them to the HttpClient.DefaultRequestHeaders
Dim response As New HttpResponseMessage
Dim path As String = "C:\\Temp\\upload.pdf"
Dim uri As New Uri("https://postman-echo.com/post")
Using form As New MultipartFormDataContent,
fs As New FileStream(path, FileMode.Open),
content As New StreamContent(fs),
httpClient As New HttpClient
form.Add(content)
httpClient.DefaultRequestHeaders.Add("Token", "Super Secret")
response = httpClient.PostAsync(uri, form).GetAwaiter.GetResult()
Console.WriteLine("Is Successfull: " & response.IsSuccessStatusCode)
End Using
EDIT: Cleaned up nested Using statements

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?

Prestashop - Unable to upload a new image product with the prestashop 1.6 webservice

I'm trying to upload a new image for a product with the prestashop webservice through a vb .net application, but I get the following error message:
"Unable to save this image".
The URL used to upload the image is this: http://localhost/prestashop/api/images/products/1
And the source code of the function that make the request is this:
Public Sub executeAddImage(ByVal resource As String, ByVal id As String, ByVal imageToAdd As Image)
Dim response As String = Nothing
Try
Dim ms As New MemoryStream()
imageToAdd.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
Dim byteArray As Byte() = ms.ToArray()
Dim requestUrl As String = Me.WebServiceURL & "/" & resource & "/" & id
MsgBox(requestUrl)
Dim webRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(requestUrl), HttpWebRequest)
webRequest.Method = WebServicePrestashop.CRUDMethod.Create
'webRequest.ContentType = "image/jpeg"
webRequest.ContentType = "application/x-www-form-urlencoded"
webRequest.Credentials = New NetworkCredential(Me.LoginName, WebServicePrestashop._password)
webRequest.ContentLength = byteArray.Length
MsgBox(byteArray.Length)
' Get the request stream
Using dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
' Get the response
Using webResponse As HttpWebResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
If webResponse.StatusCode = HttpStatusCode.OK Then
Using reader As New StreamReader(webResponse.GetResponseStream(), Encoding.UTF8)
Dim imageNew As Image = Image.FromStream(webResponse.GetResponseStream())
End Using
End If
End Using
Catch ex As WebException
MsgBox(ex.Message.ToString())
Dim reader As New StreamReader(ex.Response.GetResponseStream)
MsgBox(reader.ReadToEnd)
End Try
End Sub
I'm using the HTTP POST method, and the POST content is the bynary content of the new image.
How can I fix it?.
Here the solution.
I think the key is that I must write the body of the webrequest programatically adding to the stream of the webrequest the boundary (in binary array format), the Content-Type chain (in binary array format) and the content of the image to upload (in binary array format).
Public Sub executeAddImage(ByVal resource As String, ByVal id As String, ByVal imageToAdd As Byte())
Dim response As String = Nothing
Try
Dim requestUrl As String = "urlShop" & "/api/" & resource & "/" & id
MsgBox(requestUrl)
Dim webRequest As HttpWebRequest = DirectCast(System.Net.WebRequest.Create(requestUrl), HttpWebRequest)
webRequest.KeepAlive = True
webRequest.Credentials = New NetworkCredential(Me.LoginName, WebServicePrestashop._password)
webRequest.ContentLength = imageToAdd.Length
webRequest.Method = "POST"
webRequest.ContentType = "image/jpeg"
Dim boundary As String = "----" & DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture)
webRequest.ContentType = "multipart/form-data; boundary=" & boundary
Dim beginPostData = "--" & boundary & vbCrLf & "Content-Disposition: form-data; name=""image""; filename=""torrente.jpg""" & _
vbCrLf & "Content-Type: image/jpeg" & vbCrLf & vbCrLf
Dim boundaryBytes = System.Text.Encoding.ASCII.GetBytes(vbCrLf & "--" & boundary & "--" & vbCrLf)
Dim beginPostDataBytes = System.Text.Encoding.ASCII.GetBytes(beginPostData)
webRequest.ContentLength = beginPostData.Length + imageToAdd.Length + boundaryBytes.Length
' Get the request stream
Using dataStream As Stream = webRequest.GetRequestStream()
dataStream.Write(beginPostDataBytes, 0, beginPostDataBytes.Length)
dataStream.Write(imageToAdd, 0, imageToAdd.Length)
dataStream.Write(boundaryBytes, 0, boundaryBytes.Length)
End Using
' Get the response
Using webResponse As HttpWebResponse = DirectCast(webRequest.GetResponse(), HttpWebResponse)
If webResponse.StatusCode = HttpStatusCode.OK Then
Using reader As New StreamReader(webResponse.GetResponseStream())
response = reader.ReadToEnd()
MsgBox(response)
End Using
End If
End Using
Catch ex As WebException
MsgBox(ex.Message.ToString())
Dim reader As New StreamReader(ex.Response.GetResponseStream)
MsgBox(reader.ReadToEnd)
End Try
End Sub

vb.net httpwebrequest to login to EmpireAvenue.com

This is driving me insane. I know I have to be close on this. My requests matches a real one as far as I can see except the cookies are a bit different. I appear to be missing the google analytics ones. Not sure if that is the issue or not. I get redirected like I am supposed to but on the redirect page it is asking me to login again. Any help is appreciated. Here is my code:
Private Function eaLogin(ByVal ticker As String, ByVal password As String)
Try
ServicePointManager.Expect100Continue = False
Dim request As HttpWebRequest = httpWebRequest.Create("http://www.empireavenue.com")
request.Credentials = CredentialCache.DefaultCredentials
request.CookieContainer = cookieJar
Dim response As HttpWebResponse = request.GetResponse()
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
Dim session As String = ""
ServicePointManager.Expect100Continue = False
'Set the initial parameters
Dim UserID As String = ticker ' Username
Dim PWord As String = HttpUtility.UrlEncode(password) ' Password
Dim domain As String = "https://www.empireavenue.com/user/login/do"
Dim encoding As New System.Text.ASCIIEncoding
' Use the appropriate HTML field names to stuff into the post header
Dim PostData As String = _
"login_username=" & ticker & _
"&login_password=" & PWord
Dim Data() As Byte = encoding.GetBytes(PostData)
' Initialise the request
Dim LoginReq As Net.HttpWebRequest = Net.WebRequest.Create(domain) ' Login location taken from the form action
With LoginReq
.KeepAlive = True
.Method = "POST"
' Note: if the page uses a redirect if will fail
.AllowAutoRedirect = False
.ContentType = "application/x-www-form-urlencoded"
.ContentLength = Data.Length
' Set empty container
.CookieContainer = cookieJar
.Referer = "http://www.empireavenue.com/"
.UserAgent = userAgent
.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
.Host = "www.empireavenue.com"
End With
' Add the POST data
Dim SendReq As IO.Stream = LoginReq.GetRequestStream
LoginReq.Headers.Add("Accept-Language", "en-US,en;q=0.5")
LoginReq.Headers.Add("Accept-Encoding", "gzip, deflate")
SendReq.Write(Data, 0, Data.Length)
SendReq.Close()
' Obtain the response
Dim LoginRes As Net.HttpWebResponse = LoginReq.GetResponse()
' Retreive the headers from the request (e.g. the location header)
Dim Redirect As String = LoginRes.Headers("Location")
' Add any returned cookies to the cookie collection
cookieJar.Add(LoginRes.Cookies)
' Move to the redirected page as a GET request...
Dim newUrl As String = ""
If Not (Redirect Is Nothing) Then
If Redirect.StartsWith("http://") Then
newUrl = Redirect
Else
newUrl = "https://www.empireavenue.com" & Redirect
End If
LoginReq = Net.WebRequest.Create(newUrl)
With LoginReq
.KeepAlive = False
.Method = "GET"
.ContentType = "application/x-www-form-urlencoded"
.AllowAutoRedirect = True
.CookieContainer = cookieJar
End With
' Perform the navigate and output the HTML
LoginRes = LoginReq.GetResponse()
Dim sReader As IO.StreamReader = New IO.StreamReader(LoginRes.GetResponseStream)
Dim HTML As String = sReader.ReadToEnd
If HTML.Contains(ticker) Then
MessageBox.Show("yay!")
Return True
Else
MessageBox.Show("no!")
Return False
End If
Else
MessageBox.Show("no too!")
Return False
End If
Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
Return False
End Try
End Function
I couldn't try it on the empirevenue because of the restrictions at work but try this:
Dim tempCookies As CookieContainer
ServicePointManager.Expect100Continue = False
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://www.empireavenue.com/user/login/do"), HttpWebRequest)
Dim postData As String = "login_username=" & ticker & "&login_password=" & PWord
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.CookieContainer = tempCookies
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.Referer = "http://www.empireavenue.com/"
postReq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20120427 Firefox/15.0a1"
postReq.ContentLength = byteData.Length
Dim postreqstream As Stream = postReq.GetRequestStream()
postreqstream.Write(byteData, 0, byteData.Length)
postreqstream.Close()
Dim postresponse As HttpWebResponse
postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
tempCookies.Add(postresponse.Cookies)
logincookie = tempCookies
Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
Dim thepage As String = postreqreader.ReadToEnd
Hope it will work for you

Closure Compiler Service API

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)