swagger-ui auto replaces escaped characters like "" - vb.net

Basically I am using .Net VB to pass in a JSON String format into Swagger-UI for Response Body.
But the Response Body displays characters like "\"
I want to get rid of that.
my Json string looks something like this in VB
sJSON = "{""csid"":""" + customer.CSID.ToString() + """}"
The Current Result is:
{\"csid\":\"1234\"}
Desired Result is:
{"csid":"1234"}
New Edits:
The string is generated from my custom print JSON class
It's the default method that came with the Controller class I mimic from HomeControllers.
I am guessing it needs to set the "application/JSON" content type?
Public Function GetValue(ByVal id As Integer) As String
Return PrintJSON()
End Function
Function PrintJSON()
Dim sJSON As String
' Begin JSON object
sJSON = "{"
' Timestamp
sJSON = sJSON + """date"":""" + DateTime.Today().ToShortDateString + ""","
sJSON = sJSON + """time"":""" + DateTime.Today().ToShortTimeString + ""","
' Return list of parameters in a JSON object
sJSON = sJSON + ""
sJSON = sJSON + """record"":["
For Each customer In Customers
sJSON = sJSON + "{"
sJSON = sJSON + """csid"":""" + customer.CSID.ToString() + """"
sJSON = sJSON + "}"
If customer.Equals(Customers.Last) Then
sJSON = sJSON + "]"
Else
sJSON = sJSON + ","
End If
Next
sJSON = sJSON + "}"
Return sJSON
End Function

Ok, I found the solution. The GetValue method can just return a data transfer object class.
Swagger will automatically display the class in JSON format.
I sure hope this was explained clearer in the Swagger tutorial.

Related

Integrating Amazon Polly with VBA

I want to use Amazon Polly in an PowerPoint VBA Project to convert notes to mp3.
I think there is no SDK for this, but it is possible through the API with the signing?
See VBA Module and VBA Class below which I recently constructed, permitting direct calls to the Amazon web service Polly from within MS Office, saving the resulting MP3 to a file. A couple of notes:
I have only confirmed successful calls to Amazon Polly with Office 365 versions of MS Word and MS Excel on Windows 10, but given my past VBA experience, don't have any reason to believe the code won't work on other variations.
The entry point is callAwsPolly.
You will need to adjust the AWS parameters accordingly (ie, aws.host, aws.region, aws.service, & aws.uri).
The credentials (aws.accessKey & aws.secretKey) are the standard AWS example credentials, and will obviously need to be replaced with your own AWS credentials.
Note that it is very bad practice to embed credentials in code. Am not sure of your specific application, but in my case, I created my own key store, using optionally a passphrase or the MAC address as the decryption key for the key store. The concept of credential management is another subject, which I am not addressing here...
To incorporate the functionality into an MS Office product, add the following as a VBA module...
Option Explicit
Sub callAwsPolly()
Dim aws As amazonWebService
Set aws = New amazonWebService
aws.host = "polly.us-east-2.amazonaws.com"
aws.region = Split(aws.host, ".")(1)
aws.service = "polly"
aws.uri = "/v1/speech"
' !!! NOTE: The following is very bad practice to embed credentials in code!!!
aws.accessKey = "AKIAIOSFODNN7EXAMPLE"
aws.secretKey = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
Dim requestParameters As String
requestParameters = "{#OutputFormat#: #mp3#, #Text#: #Polly want a cracker?#, #TextType#: #ssml#, #VoiceId#: #Emma#}"
requestParameters = Replace(requestParameters, "#", """")
Dim httpResponse As Object
Set httpResponse = aws.callWebService("application/json", requestParameters)
If httpResponse Is Nothing Then
MsgBox "Call to AWS Polly failed."
ElseIf httpResponse.Status = 200 Then
MsgBox "Call to AWS Polly succeeded! MP3 file being saved."
Dim iFile As Long: iFile = FreeFile
Open ActiveWorkbook.FullName & ".mp3" For Binary Access Write As #iFile
Put iFile, , httpResponse.Responsebody
Close #iFile
Else
MsgBox "Call to AWS Polly failed:" + CStr(httpResponse.Status) + " " + httpResponse.StatusText + " " + httpResponse.ResponseText
End If
End Sub
' Adapted from https://stackoverflow.com/questions/36384741/cant-use-getbytes-and-computehash-methods-on-vba
Public Function hmacSha256(key As Variant, stringToHash As Variant) As Byte()
Dim ssc As Object
Set ssc = CreateObject("System.Security.Cryptography.HMACSHA256")
ssc.key = str2byte(key)
hmacSha256 = ssc.ComputeHash_2(str2byte(stringToHash))
Set ssc = Nothing
End Function
Public Function sha256(stringToHash As Variant) As Byte()
Dim ssc As Object
Set ssc = CreateObject("System.Security.Cryptography.SHA256Managed")
sha256 = ssc.ComputeHash_2(str2byte(stringToHash))
Set ssc = Nothing
End Function
Public Function str2byte(s As Variant) As Byte()
If VarType(s) = vbArray + vbByte Then
str2byte = s
ElseIf VarType(s) = vbString Then
str2byte = StrConv(s, vbFromUnicode)
Else
Exit Function
End If
End Function
Public Function byte2hex(byteArray() As Byte) As String
Dim i As Long
For i = 0 To UBound(byteArray)
byte2hex = byte2hex & Right(Hex(256 Or byteArray(i)), 2)
Next
byte2hex = LCase(byte2hex)
End Function
...and add the following code as a VBA Class Module, naming it "amazonWebService"...
'
' Class Module: amazonWebService
'
Private className As String
Public host As String
Public region As String
Public service As String
Public uri As String
Public accessKey As String
Public secretKey As String
Private Sub Class_Initialize()
className = "amazonWebService"
host = ""
region = ""
uri = ""
service = ""
accessKey = ""
secretKey = ""
End Sub
Public Function callWebService(contentType As String, requestParameters As String) As Object
If host = "" Or region = "" Or uri = "" Or service = "" Or accessKey = "" Or secretKey = "" Then
Err.Raise _
1000, _
className, _
className + ": Please set properties before calling the amazon web service: host, region, uri, service, accessKey, and secretKey."
callWebService = Null
Exit Function
End If
Dim amzDate As String, dateStamp As String
amzDate = date2iso8601(GMT())
dateStamp = Left(amzDate, 8)
' ************* TASK 1: CREATE A CANONICAL REQUEST *************
' http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
'Step 1 is to define the verb (GET, POST, etc.)
Dim method As String
method = "POST"
' Step 2: Create canonical URI (set by the calling program)
Dim canonicalUri As String
canonicalUri = uri
' Step 3: Create the canonical query string. In this example (POST), request
' parameters are passed in the body of the request and the query string
' is blank.
Dim canonicalQueryString As String
canonicalQueryString = ""
' Step 4: Create the canonical headers. Header names must be trimmed
' and lowercase, and sorted in code point order from low to high.
' Note that there is a trailing \n.
Dim canonicalHeaders As String
canonicalHeaders = _
"host:" + host + vbLf + _
"x-amz-date:" + amzDate + vbLf
' Step 5: Create the list of signed headers. This lists the headers
' in the canonical_headers list, delimited with ";" and in alpha order.
' Note: The request can include any headers; canonical_headers and
' signed_headers include those that you want to be included in the
' hash of the request. "Host" and "x-amz-date" are always required.
Dim signedHeaders As String
signedHeaders = "host;x-amz-date"
' Step 6: Create payload hash. In this example, the payload (body of
' the request) contains the request parameters.
Dim payloadHash As String
payloadHash = byte2hex(sha256(requestParameters))
' Step 7: Combine elements to create canonical request
Dim canonicalRequest As String
canonicalRequest = method + vbLf + _
canonicalUri + vbLf + _
canonicalQueryString + vbLf + _
canonicalHeaders + vbLf + _
signedHeaders + vbLf + _
payloadHash
' ************* TASK 2: CREATE THE STRING TO SIGN*************
' Match the algorithm to the hashing algorithm you use, either SHA-1 or
' SHA-256 (recommended)
Dim algorithm As String, credentialScope As String, stringToSign As String
algorithm = "AWS4-HMAC-SHA256"
credentialScope = dateStamp + "/" + region + "/" + service + "/aws4_request"
stringToSign = _
algorithm + vbLf + _
amzDate + vbLf + _
credentialScope + vbLf + _
byte2hex(sha256(canonicalRequest))
' ************* TASK 3: CALCULATE THE SIGNATURE *************
' Create the signing key using the function defined above.
Dim signingKey() As Byte, signature As String
signingKey = getSignatureKey(secretKey, dateStamp, region, service)
' Sign the string_to_sign using the signing_key
signature = byte2hex(hmacSha256(signingKey, stringToSign))
' ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
' Put the signature information in a header named Authorization.
Dim authorizationHeader As String
authorizationHeader = _
algorithm + " " + _
"Credential=" + accessKey + "/" + credentialScope + ", " + _
"SignedHeaders=" + signedHeaders + ", " + _
"Signature=" + signature
' ************* SEND THE REQUEST TO AWS! *************
Dim http As Object
Set http = CreateObject("WinHttp.WinHttpRequest.5.1")
http.Open "POST", "https://" + host + uri, False
http.setrequestheader "content-type", contentType
http.setrequestheader "host", host
http.setrequestheader "x-amz-date", amzDate
http.setrequestheader "authorization", authorizationHeader
http.Send requestParameters
' If the result is 403 Forbidden, then clear the current selected credentials.
If http.Status = 403 Then
accessKey = ""
secretKey = ""
End If
' Return the HTTP response back to the calling program.
Set callWebService = http
End Function
Private Function GMT() As Date
Dim dt As Object
Set dt = CreateObject("WbemScripting.SWbemDateTime")
dt.SetVarDate Now
GMT = dt.GetVarDate(False)
Set dt = Nothing
End Function
Private Function date2iso8601(dateTime As Date) As String
date2iso8601 = Format(dateTime, "yyyymmdd\Thhnnss\Z")
End Function
Private Function getSignatureKey(key As String, dateStamp As String, regionName As String, serviceName As String) As Byte()
Dim kDate() As Byte, kRegion() As Byte, kService() As Byte, kSigning() As Byte
kDate = hmacSha256("AWS4" + key, dateStamp)
kRegion = hmacSha256(kDate, regionName)
kService = hmacSha256(kRegion, serviceName)
kSigning = hmacSha256(kService, "aws4_request")
getSignatureKey = kSigning
End Function

How to terminate a process if it has specific folder name in its path?

I run an application from PowerBuilder and terminate it when i dont need it. But the application when running, it executes other processes from a specific folder.
I want to kill all processes if they run from a specific folder.
How to get the process handles of all those processes that have specif folder name in their path?
Here an example to show how to terminate all running instance of Notepad.exe
OleObject wsh
integer li_rc
wsh = CREATE OleObject
wsh.ConnectToNewObject( "MSScriptControl.ScriptControl" )
wsh.language = "vbscript"
wsh.AddCode('function terminatenotepad() ~n ' + &
'strComputer = "." ~n ' + &
'Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") ~n ' + &
'Set colItems = objWMIService.ExecQuery("Select * from Win32_Process where name = ~'notepad.exe~'") ~n ' + &
'For Each objItem in colItems ~n ' + &
' objItem.Terminate ~n ' + &
'Next ~n ' + &
'end function ~n ' )
wsh.executestatement('terminatenotepad()')
wsh.DisconnectObject()
DESTROY wsh
Try to change the where clause
where name = ~'notepad.exe~'" ...
for
where commandline = ~'" + ls_commandline + "~'" ...
where ls_commandline is the command line used to start your process.
See "Win32_Process class" for more infos.
/// This is simple code example Terminate a Running Process if here is specific
/// folder name in the path of the running program (\EagleGet\)
/// Two variable SelectThis and TheWhere can be changed to get different
/// results. Many things are not dynamic in this script and certainly not the
/// best way of writing code. but its just ok for a little quick work.`
OleObject wsh
Integer li_rc
String LineFeed = ' ~r~n '
String TheComputer = "." //local computer
String TheCode = "no need to set it here"
String FunctionName = "Whatever()" //any name you like
String SelectThis = "?" //only the columns/expressions
String TheWhere = "?" //only the where clause without keyword WHERE
String DoWhat = "?" //the action to perform for example 'Terminate' without quotes
String TheQuery = "no need to set here"
String WMIClass = "Win32_Process" /// The WMI class of running processes
String TheFolderName = "The folder name from which the creapy process is running (path) "
/// You just set DoWhat, SelectThis and TheWhere. Rest of the variables, you dont need to set here
/// SelectThis = is the columns or expressions you want returned by the Query
SelectThis = "*"
/// TheFolderName = set it to the name of the folder that exist in the path
///of the ruuning process you want to terminate
TheFolderName = "EagleGet"
/// TheWhere is the WHERE clause expressions
TheWhere = "ExecutablePath LIKE ~'%\\" + TheFolderName + "\\%~' "
/// DoWhat is the final function call of the WMI Class
DoWhat = "Terminate"
/// There is no need to chage anything from this point onward.
/// without double quotes, and you dont have to change TheQuery here
TheQuery = " SELECT " + SelectThis + " FROM " + WMIClass + " WHERE " + TheWhere
TheCode = "Function " + FunctionName + LineFeed + &
"strComputer = ~"" + TheComputer + "~"" + LineFeed + &
"Set objWMIService = GetObject(~"winmgmts:\\~" & strComputer & ~"\root\cimv2~")" + LineFeed + &
"Set colItems = objWMIService.ExecQuery(~"" + Trim(TheQuery) + "~" )" + LineFeed + &
"For Each objItem in colItems" + LineFeed + &
"objItem." + Trim(DoWhat) + LineFeed + &
"Next " + LineFeed + &
"END Function " + LineFeed
wsh = CREATE OleObject
wsh.ConnectToNewObject("MSScriptControl.ScriptControl")
wsh.Language = "VBScript"
wsh.AddCode(TheCode)
TRY
wsh.ExecuteStatement(FunctionName)
CATCH (RunTimeError Re01)
MessageBox("Query Error", "Following code has some problems.~r~n~r~n" + TheCode, StopSign!)
END TRY
wsh.DisconnectObject()
DESTROY wsh

xlively conversion from Pachube Feed VB.net

Trying to convert and old Pachube feed to Xively using Visual Studio 2013. Receive a 400 error.
Here is a snippet of my code base.It still works with my old pachube feed but after changing to xlivey api no longer works.
Dim PachubeStream As String = timestamp + "," + PT1Meter + "," + PT2Meter + "," + LevelOffset + "," + CurrentLevel + "," + PT1Raw + "," + PT2Raw + "," + PT1Offset + "," + PT2Offset + "," + RateofRise + "," + PeakRateofRise
'prepare to Upload the latest changed data to pachube for on-line data storage and plotting
Dim myWebClient As New WebClient()
uploaddatapachubekey = TextBox7.Text
myWebClient.Headers.Add("X-ApiKey", uploaddatapachubekey)
' Apply ASCII Encoding to obtain the string as a byte array.
Dim byteArray As Byte() = Encoding.ASCII.GetBytes(PachubeStream)
'added 11/11/2010
'configure uploaddata pachube port url
uploaddatapachubeport = "https://api.xively.com/v2/feeds/" + pachubeport + ".csv"
'UploadData input string using Http 1.0 PUT Method if not in test mode
'added 11/11/2010
If TestMode = False Then myWebClient.UploadData(uploaddatapachubeport, "put", byteArray)
Solved my own problem. Issue was the new format of all data submission is
"Channel Name",Timestamp UTC Format,Channel Data VBCRLF
i.e.
Dim PachubeStream As String = "PT1Meter"+","+timestamp+","+PT1Meter

Label Conversion from string to double isn't valid

I have the following code , It's for countdown timer
Dim countdown As Integer = SharpTextBox6.Text
Label1.Text = "Sending to " + "" + SharpTextBox4.Text + "" + "For" + countdown.ToString - 1
the problem is it says " Conversation from string "The value ..." to double isn't valid . Why does it covert into to double ? and how I can solve this problem
You can try this :
Label1.Text = "Sending to " + SharpTextBox4.Text + "For" + (countdown - 1).ToString
MSDN: When you use the + operator, you may not be able to determine whether addition or string concatenation will occur. Use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.
Label1.Text = "Sending to " & SharpTextBox4.Text & " For " & (countdown - 1)

vb.net string concatenation string + function output + string = string + function output and no more

The following output produces a string with no closing xml tag.
m_rFlight.Layout = m_rFlight.Layout + "<G3Grid:Spots>" + Me.gvwSpots.LayoutToString() + "</G3Grid:Spots>"
This following code works correctly
m_rFlight.Layout = m_rFlight.Layout + "<G3Grid:Spots>" + Me.gvwSpots.LayoutToString()
m_rFlight.Layout = m_rFlight.Layout + "</G3Grid:Spots>" 'add closing tag
What's going on here, what's the reason the first example isnt working and the second is?
The gvwSpots.LayoutToString() function returns a string.
As Meta-Knight said, except that I would recommend using the StringBuilder class:
Dim myString As New System.Text.StringBuilder
myString.Append("<G3Grid:Spots>")
myString.Append(Me.gvwSpots.LayoutToString())
myString.Append("</G3Grid:Spots>")
m_rFlight.Layout = myString.ToString()
Consider the following code that should be the equivalent of your code:
Dim someString As String = String.Empty
someString = someString + "<G3Grid:Spots>" + "SomeValue" + "</G3Grid:Spots>"
Console.WriteLine(someString)
someString = String.Empty
someString = someString + "<G3Grid:Spots>" + "SomeValue"
someString = someString + "</G3Grid:Spots>"
Console.WriteLine(someString)
I tested it and in both cases the output is: <G3Grid:Spots>SomeValue</G3Grid:Spots>
If you don't get the same results then it's because either m_rFlight.Layout is not a string, or Me.gvwSpots.LayoutToString() doesn't return a string and does something strange with the + operator. You can use the & operator instead to make sure that only string concatenation is performed.
You can use string.concat
m_rFlight.Layout = string.concat(m_rFlight.Layout, "<G3Grid:Spots>",_
Me.gvwSpots.LayoutToString(), "</G3Grid:Spots>")
or, as Meta-Knight mentioned, & instead of +. (It will always convert to string before concatenation.)
m_rFlight.Layout &= "<G3Grid:Spots>" & Me.gvwSpots.LayoutToString() & "</G3Grid:Spots>"