How to SendRequest with correct body by using wininet in mql4 - wininet

I have dummy web service with URL: http://47.91.231.122:5002/token which return data in JSON I want to call this service using WINInet APi in mql.Can anybody help me how to use contruct "HttpSendRequest" method to add header and data to call this service?
enter image description here
Get the access token from the server by enter all the required data in the call body.
URL: http://47.91.231.122:5002/token
username:admin#admin.com
password:111111
grant_type:password
Below is my code.
Please guide me how to do it correctly. Thanks
#import "Wininet.dll"
int InternetOpenW(string name, int config, string, string, int);
int InternetConnectW(int hopen, string, int, string, string, int, int, int);
int HttpRequestW(int hconnect, string, string, int, string, int, string, int);
int InternetOpenUrlW(int, string, string, int, int, int);
bool InternetReadFile(int, uchar &sBuffer[], int, int& OneInt);
bool InternetCloseHandle(int); [enter image description here][1]
int HttpOpenRequestA(int, string, string, string, string, string& AcceptTypes[], int, int);
bool HttpSendRequestA(int, string, int, string, int);
#import
#import "kernel32.dll"
int GetLastError(void);
#import
is the header and body data correct?
int init()
{
string headers = "Content-Type: application/x-www-form-urlencoded\r\n";
string data = "{\"username\":\"admin#admin.com\",\"password\":\"111111\",\"grant_type\":\"password\"}";
string acceptTypes[1] = {"*/*"};
int httpconnect=0;
int HttpRequest =0;
int httpopen = Wininet::InternetOpenW("Phoenix_API", 0, " "," ",0 );
int e=kernel32::GetLastError();
printf("HttpOpen=0 = "+httpopen+", "+e);
if (e==0)
{
Base on the picture, am i code it correct to connect it?
httpconnect = Wininet::InternetConnectW(httpopen, "47.91.231.122", 5002, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
printf("httpconnect=0 = "+httpconnect+", "+e);
e=kernel32::GetLastError();
if (e==0)
{
HttpRequest = HttpOpenRequestA(httpconnect, "POST", "/token", NULL, NULL, acceptTypes, 0, 1);
e=kernel32::GetLastError();
printf("HttpRequest = "+HttpRequest+", "+e);
if (e==0)
{
bool A = HttpSendRequestA(HttpRequest, headers, StringLen(headers), "", 0);
e=kernel32::GetLastError();
printf("A = "+A+", "+e);
i get a dummy message DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
//--- Define buffers
uchar ch[512]={0,0,0,0};
string temp="";
//--- Retrieve data from file
int cnt=0;
while(Wininet::InternetReadFile(HttpRequest,ch,512,cnt))
{
if(cnt<=0) break;
temp=temp+CharArrayToString(ch,0,cnt);
printf(temp);
}
MessageBox(temp, "HTTP READ:", 0x00000030);
}
}
}
//--- Close connection
if (HttpRequest > 0) InternetCloseHandle(HttpRequest);
if (httpconnect > 0) InternetCloseHandle(httpconnect);
if (httpopen > 0) InternetCloseHandle(httpopen);
}

Related

How to filter JSON data based off an empty field?

I'm calling an API and trying to parse the body response to filter out data. I've created a conditional for-loop to go through each object and check whether this field: Relationships.CurrentConfigurationVersion.Data is empty.
Here is my first attempt:
func (s *Server) getEmptyWorkSpaces(w http.ResponseWriter, r *http.Request) {
// omitted API calls for brevity
// body holds the JSON response
body, err := ioutil.ReadAll(resp.Body)
// label my struct type as data
var data WorkspacesJSON
err = json.Unmarshal(body, data)
if err != nil {
panic(err)
}
var data2 []*WorkspacesJSON
for _, v := range data.Data {
if v.Relationships.CurrentConfigurationVersion.Data == " " {
data2 = append(data2, v)
}
}
}
The error occurs in the conditional statement because I'm comparing a struct type to a string.
cannot convert "" (untyped string constant) to struct{ID string "json:"id""; Type string "json:"type""}
Attempt 2
After some searching around I tried another attempt from information I learned:
func (s *Server) getEmptyWorkSpaces(w http.ResponseWriter, r *http.Request) {
// omitted API calls for brevity
// body holds the JSON response
body, err := ioutil.ReadAll(resp.Body)
// label my struct type as data, this time attach []*
var data []*WorkspacesJSON
// added & in this new attempt
err = json.Unmarshal(body, &data)
if err != nil {
panic(err)
}
var data2 []*WorkspacesJSON
for _, v := range data.Data {
if v.Relationships.CurrentConfigurationVersion.Data == " " {
data2 = append(data2, v)
}
}
}
The compiler throw another error but this time targeting v.Relationships.CurrentConfigurationVersion.Data saying:
v.Relationships undefined (type *WorkspacesJSON has no field or method Relationships)compilerMissingFieldOrMethod
I'm not sure why I'm getting this error because in my first attempt this was not a problem? Clearly I am not understanding this.
Here is my type struct:
It's fairly long but the only field of important is Data.Relationships.CurrentConfigurationVersion.Data
type WorkspacesJSON struct {
Data []struct {
ID string `json:"id"`
Type string `json:"type"`
Attributes struct {
AllowDestroyPlan bool `json:"allow-destroy-plan"`
AutoApply bool `json:"auto-apply"`
AutoDestroyAt interface{} `json:"auto-destroy-at"`
CreatedAt time.Time `json:"created-at"`
Environment string `json:"environment"`
Locked bool `json:"locked"`
Name string `json:"name"`
QueueAllRuns bool `json:"queue-all-runs"`
SpeculativeEnabled bool `json:"speculative-enabled"`
StructuredRunOutputEnabled bool `json:"structured-run-output-enabled"`
TerraformVersion string `json:"terraform-version"`
WorkingDirectory string `json:"working-directory"`
GlobalRemoteState bool `json:"global-remote-state"`
UpdatedAt time.Time `json:"updated-at"`
ResourceCount int `json:"resource-count"`
ApplyDurationAverage int `json:"apply-duration-average"`
PlanDurationAverage int `json:"plan-duration-average"`
PolicyCheckFailures int `json:"policy-check-failures"`
RunFailures int `json:"run-failures"`
WorkspaceKpisRunsCount int `json:"workspace-kpis-runs-count"`
LatestChangeAt time.Time `json:"latest-change-at"`
Operations bool `json:"operations"`
ExecutionMode string `json:"execution-mode"`
VcsRepo struct {
Branch string `json:"branch"`
IngressSubmodules bool `json:"ingress-submodules"`
Identifier string `json:"identifier"`
DisplayIdentifier string `json:"display-identifier"`
OauthTokenID string `json:"oauth-token-id"`
WebhookURL string `json:"webhook-url"`
RepositoryHTTPURL string `json:"repository-http-url"`
ServiceProvider string `json:"service-provider"`
} `json:"vcs-repo"`
VcsRepoIdentifier string `json:"vcs-repo-identifier"`
Permissions struct {
CanUpdate bool `json:"can-update"`
CanDestroy bool `json:"can-destroy"`
CanQueueDestroy bool `json:"can-queue-destroy"`
CanQueueRun bool `json:"can-queue-run"`
CanQueueApply bool `json:"can-queue-apply"`
CanReadStateVersions bool `json:"can-read-state-versions"`
CanCreateStateVersions bool `json:"can-create-state-versions"`
CanReadVariable bool `json:"can-read-variable"`
CanUpdateVariable bool `json:"can-update-variable"`
CanLock bool `json:"can-lock"`
CanUnlock bool `json:"can-unlock"`
CanForceUnlock bool `json:"can-force-unlock"`
CanReadSettings bool `json:"can-read-settings"`
CanManageTags bool `json:"can-manage-tags"`
} `json:"permissions"`
Actions struct {
IsDestroyable bool `json:"is-destroyable"`
} `json:"actions"`
Description interface{} `json:"description"`
FileTriggersEnabled bool `json:"file-triggers-enabled"`
TriggerPrefixes []interface{} `json:"trigger-prefixes"`
Source string `json:"source"`
SourceName interface{} `json:"source-name"`
SourceURL interface{} `json:"source-url"`
TagNames []interface{} `json:"tag-names"`
} `json:"attributes"`
Relationships struct {
Organization struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
} `json:"organization"`
CurrentRun struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"current-run"`
LatestRun struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"latest-run"`
Outputs struct {
Data []interface{} `json:"data"`
} `json:"outputs"`
RemoteStateConsumers struct {
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"remote-state-consumers"`
CurrentStateVersion struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"current-state-version"`
CurrentConfigurationVersion struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
Links struct {
Related string `json:"related"`
} `json:"links"`
} `json:"current-configuration-version"`
AgentPool struct {
Data interface{} `json:"data"`
} `json:"agent-pool"`
Readme struct {
Data struct {
ID string `json:"id"`
Type string `json:"type"`
} `json:"data"`
} `json:"readme"`
} `json:"relationships"`
Links struct {
Self string `json:"self"`
} `json:"links"`
} `json:"data"`
Links struct {
Self string `json:"self"`
First string `json:"first"`
Prev interface{} `json:"prev"`
Next string `json:"next"`
Last string `json:"last"`
} `json:"links"`
Meta struct {
StatusCounts struct {
Pending int `json:"pending"`
PlanQueued int `json:"plan-queued"`
Planning int `json:"planning"`
Planned int `json:"planned"`
Confirmed int `json:"confirmed"`
ApplyQueued int `json:"apply-queued"`
Applying int `json:"applying"`
Applied int `json:"applied"`
Discarded int `json:"discarded"`
Errored int `json:"errored"`
Canceled int `json:"canceled"`
CostEstimating int `json:"cost-estimating"`
CostEstimated int `json:"cost-estimated"`
PolicyChecking int `json:"policy-checking"`
PolicyOverride int `json:"policy-override"`
PolicyChecked int `json:"policy-checked"`
PolicySoftFailed int `json:"policy-soft-failed"`
PlannedAndFinished int `json:"planned-and-finished"`
PostPlanRunning int `json:"post-plan-running"`
PostPlanCompleted int `json:"post-plan-completed"`
PreApplyRunning int `json:"pre-apply-running"`
PreApplyCompleted int `json:"pre-apply-completed"`
Fetching int `json:"fetching"`
None int `json:"none"`
Total int `json:"total"`
} `json:"status-counts"`
Pagination struct {
CurrentPage int `json:"current-page"`
PageSize int `json:"page-size"`
PrevPage interface{} `json:"prev-page"`
NextPage int `json:"next-page"`
TotalPages int `json:"total-pages"`
TotalCount int `json:"total-count"`
} `json:"pagination"`
} `json:"meta"`
}
I'm stuck in an eternal loop of those two same errors above, and trying to create hacky functions to get the job done, but no luck.
I'm very new to Go, I have experience with Python and working with JSON in Py is much easier for me but I want to try this using Go. Thanks in advance for your guidance.
How can I filter my JSON body using a conditional to check if a field is empty?
EDIT:
In my second attempt, How would I be able to select the field I'm looking for, Relationships.CurrentConfigurationVersion.Data? Once I figure that out I think I will be okay. Currently its saying that WorkspaceJSON has no field of method forRelationships. This was not the case for my first attempt.
There are lots of ways to check is struct empty or not, which is discussed here: How to check for an empty struct?
Also the append part of the code, must have the same type; as the following code:
data2 := WorkspacesJSON{}
for _, v := range data.Data {
if fmt.Sprintf("%v", v.Relationships.CurrentConfigurationVersion.Data) == "{ }" {
data2.Data = append(data2.Data, v)
}
}

How to access secondary constructor parameter outside constructor block in Kotlin

I am new to Kotlin and working through the tutorials that are available.
However now I seem to have a problem with a secondary constructor:
Parameters declared in the primary constructor can be accessed in a function,
but when I try to do this with a parameter from the secondary constructor I get an error: Unresolved reference:nbr
The code:
class Test(_name: String) {
val name: String = _name
constructor(_name: String, _nbr: Int) : this(_name) {
val nbr: Int = _nbr
}
fun printNameAndNumber() {
println("Name: $name")
println("Number: $nbr")
}
}
It is clear to me that I am doing something basically wrong but who can tell me what?
nbr should be a variable, because in this specific case it is optional:
class Test(_name: String) {
val name: String = _name
var nbr: Int? = null
constructor(_name: String, _nbr: Int) : this(_name) {
this.nbr = _nbr
}
fun printNameAndNumber() {
println("Name: $name")
println("Number: $nbr")
}
}
Parameters of the primary constructor are not available in member functions. Fields are. Fortunately Kotlin has a short syntax to make primary constructor parameters member properties right away.
What do you expect nbr to be when constructed using the primary constructor? I suggest you to swap your constructors, so it's clear what are properties and what are just parameters:
class Test(val name: String, val nbr: Int) {
constructor(name: String) : this(name, 0)
fun printNameAndNumber() {
println("Name: $name")
println("Number: $nbr")
}
}
fun main(args : Array<String>) {
Test("Péter").printNameAndNumber()
}
name is accessible because it is a member.
nbr is not accessible because it is a local (immutable) variable inside the secondary constructor.
If you declare nbr as member: putting val nbr: Int for example below the val name line, it will be accessible, however it will not compile if nbr is defined as immutable (val).
A simpler structure would be:
class Test(_name: String, _nbr: Int = 0) {
val name: String = _name
val nbr: Int = _nbr
fun printNameAndNumber() {
println("Name: $name")
println("Number: $nbr")
}
}
or even simpler
class Test(val name: String, val nbr: Int = 0) {
fun printNameAndNumber() {
println("Name: $name")
println("Number: $nbr")
}
}
If you want your nbr member as nullable, you couldgo with the suggestion of #gil.fernandes.

Additional Data types (such as Unsigned SmallInt, Datetime and Decimal) in Swift Vapor/Fluent Model?

I'm trying to create a Model with Vapor, and in the prepare method, I can't seem to figure out how to add some data types into the statement.
Looking into the Vapor source code, there seems to be some data types that can be stored:
extension Schema {
/**
Various types of fields
that can be used in a Schema.
*/
public struct Field {
public var name: String
public var type: DataType
public var optional: Bool
public enum DataType {
case id
case int
case string(length: Int?)
case double
case bool
case data
}
public init(name: String, type: DataType, optional: Bool = false) {
self.name = name
self.type = type
self.optional = optional
}
}
}
So Data Types like Int, String (VARCHAR), Double, Bool and Data (BLOB) can be stored, but I can't find the ones I'm looking for, specifically:
Unsigned SMALLINT (UInt16)
DATETIME
DECIMAL (The MySQL Decimal, NOT Double or Float)
How would I make these?
At the moment, the feature is not present in Vapor / Fluent, however it's in the making.
Here's the issues page of Vapor regarding DATETIME

Golang Passing Function Arguments with Arbitrary Interfaces

The following code works nicely:
package main
import (
"fmt"
)
func WrapperFunc(fn func(int,int) int) int{
return fn(3,4)
}
func add(a,b int) int{
return a + b
}
func main(){
fmt.Println(WrapperFunc(add))
}
I want to pass additional parameters that implements a specific interface. For instance, I modify the code as follows:
import (
"fmt"
)
type RequestBody interface {
GetDescription() string
}
type LoginRequest struct {
Username string
Password string
}
func (lr LoginRequest) GetDescription() string{
return "cool function"
}
func WrapperFunc(fn func(int, int, RequestBody) int) int {
lr := LoginRequest{}
return fn(3, 4, lr)
}
func add(a, b int, lr LoginRequest) int {
fmt.Println(lr.GetDescription())
return a + b
}
func main() {
fmt.Println(WrapperFunc(add))
}
It fails with the error below:
cannot use add (type func(int, int, LoginRequest) int) as type func(int, int, RequestBody) int in argument to WrapperFunc
However, when I do not implement the GetDescription as below:
package main
import (
"fmt"
)
type RequestBody interface {
GetDescription() string
}
type LoginRequest struct {
Username string
Password string
}
func WrapperFunc(fn func(int, int, RequestBody) int) int {
lr := LoginRequest{}
return fn(3, 4, lr)
}
func add(a, b int, lr LoginRequest) int {
return a + b
}
func main() {
fmt.Println(WrapperFunc(add))
}
It fails with second error, as interface is not implemented (as expected).
cannot use lr (type LoginRequest) as type RequestBody in argument to fn:
LoginRequest does not implement RequestBody (missing GetDescription method)
cannot use add (type func(int, int, LoginRequest) int) as type func(int, int, RequestBody) int in argument to WrapperFunc
So, it understands that, in WrapperFunc body, I can only call fn with int, int and an RequestBody interface that implements the GetDescription, yet I still cannot pass it in the function phase. How can I accomplish this? I want to wrap functions that can have parameters that their type can change.
The problem is that WrapperFunc() expects a value of function type:
func(int, int, RequestBody) int
And you try to pass add to it which has a function type:
func(int, int, LoginRequest) int
2 function types are equal if both have the same parameter and result types. This does not hold in the above mentioned 2 function types: RequestBody and LoginRequest are different types, and so function types having these as (or among) parameters are different types.
You may only pass add to WrapperFunc() if you change its parameters to match the required type:
func add(a, b int, lr RequestBody) int {
fmt.Println(lr.GetDescription())
return a + b
}
Now add() has the same function type as fn in the parameters of WrapperFunc(), so your code will compile and run.
Output (try it on the Go Playground)
cool function
7
Notes:
Now lr parameter in add() is of type RequestBody and not LoginRequest. You may use it like a RequestBody, which is you may call its GetDescription() method. In WrapperFunc() you don't have to change anything, as LoginRequest implements RequestBody, so it is allowed to call fn() with a value of LoginRequest, and an interface value of type RequestBody will automatically, implicitly be created and passed to fn (which is add() in your case).
Note that in add() since parameter is now a RequestBody, you can't refer to fields of LoginRequest. You may if the value implementing the interface is indeed a value of type LoginRequest, in which case you may use type assertion to obtain the wrapped LoginRequest value should you need it.

Grails: Convert int to enum in JSON unmarshalling

I'm using HttpBuilder to call a REST service. I need to convert JSON response into a POGO.
Here a simplified REST call:
def http = new HTTPBuilder('http://www.example.com/api')
http.request(Method.POST, ContentType.JSON) {
/* ... */
response.success { resp, json ->
MyPogo pogo = (MyPogo) json
}
}
It usually works.
But now I hava a JSON like this:
{ persons: [{ name:"Jhon", gender:0 }, { name:"Mary", gender:1 }] }
And MyPogo has a Gendern enum, like this:
class MyPogo implements Serializable {
String name
Gender gender
}
enum Gender {
MALE(0),
FEMALE(1)
private final int key
Gender(int key) { this.key = key }
}
Using this POGO, HttpBuilder throws a GrailsCastException (cannot cast Integer to Gender).
I know how convert an int to an enum and how to register a custom JSON marshaller, but how can I register a custom unmarshaller only for Gender enum?
EDIT: Type definition in enum constructor.
Try to add type definition in constructor:
enum Gender {
MALE(0),
FEMALE(1)
private final int key
Gender(int key) {
this.key = key
}
}