如何从MQL4将数据发布到C#Web服务

时间:2018-07-21 07:15:51

标签: c# post asp.net-web-api mql4

我正在尝试将使用MQL4的Metatrader中的历史记录数据发布到以C#编写的Web服务中。我的问题是MQL4中的字符串是Unicode,占用2个字节,而C#中的字符串是ANSI。因此,看起来接收方的每个字符之间都有一个空格。

    String query = "delete from dbmahasiswa where NIM=@NIM AND Password=@Password";
    class_Mahasiswa cm = new class_Mahasiswa();
    try
    {
        connect.Open();
        MySqlCommand cmd = new MySqlCommand(query, connect);
        cmd.Parameters.AddWithValue("@NIM", nim);
        cmd.Parameters.AddWithValue("@Password", pass);
        int rows = cmd.ExecuteNonQuery();
        if (rows > 0)
        {
            System.Windows.Forms.MessageBox.Show("sukses!", "Status");
            return true;
        }
        else
        {
            System.Windows.Forms.MessageBox.Show("akun tidak ditemukan", "Status");
            return false;
        }
    }
    catch (Exception e)
    {
        System.Windows.Forms.MessageBox.Show(e.Message, "Warning");
        return false;
    }
    finally
    {
        connect.Close();
    }
}

在C#端看起来像这样:

#import  "Wininet.dll"
   int InternetOpenW(string, int, string, string, int);
   int InternetOpenUrl(int, string, string, int, int, int);
   int InternetCloseHandle(int); 
   int HttpOpenRequestW(int, string, string, string, string, string& AcceptTypes[], int, int);
   bool HttpSendRequestW(int, string, int, string, int);
   int InternetConnectW(int, string, int, string, string, int, int, int);
#import
#import "kernel32.dll"
   int GetLastError(void);
#import

void SendHistory()
{
   int i,hstTotal=HistoryTotal();
   for(i=0;i<hstTotal;i++)
   {
      if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==true)
      {
         if(OrderSymbol()!="") // Skip balance statements for now
         {
            string body=GetBody();

            //--- Reset the last error code
            ResetLastError();
            // Only send newer Tickets
            if (OrderTicket() > lastOrderSent)
            {
               string headers = "Content-Type: application/x-www-form-urlencoded";
               string data = "";
               string acceptTypes[1] = {"application/json"};

               int HttpOpen = InternetOpenW(" ", 0, " ", "", 0);  
               int HttpConnect = InternetConnectW(HttpOpen, serverName, 27408, "", "", 3, 0, 0);
               int HttpRequest = HttpOpenRequestW(HttpConnect, "POST","/api/Transactions", "", "", acceptTypes, 0, 0);   
               bool result = HttpSendRequestW(HttpRequest, headers, StringLen(headers), body), StringLen(body));
               string lastError = kernel32::GetLastError();
               Print ("Last MSDN Error =: ", lastError);
               int read[1];
               Print("This is the POST result: ", result);
               InternetCloseHandle(HttpOpen);
               InternetCloseHandle(HttpRequest);            
            }          
         }
      }
   }
   return;
}
string GetBody()
{
   string bodyPart1=
     StringConcatenate("{","\"Order\"",":",OrderTicket(),",",
       "\"Time\"",":","\"",GetTimeString(OrderOpenTime()),"\"",",",
       "\"Type\"",":",OrderType(),",",
       "\"Lots\"",":",OrderLots(),",",
       "\"Symbol\"",":","\"",OrderSymbol(),"\"",",",
       "\"Price\"",":",OrderOpenPrice(),",",
       "\"StopLoss\"",":",OrderStopLoss(),",",
       "\"TakeProfit\"",":",OrderTakeProfit(),",",
       "\"CloseTime\"",":","\"",GetTimeString(OrderCloseTime()),"\"",","
       );
   string bodyPart2=
     StringConcatenate("\"ClosePrice\"",":",OrderClosePrice(),",",
       "\"Swap\"",":",OrderSwap(),",",
       "\"Profit\"",":",OrderProfit(),",",
       "\"Comment\"",":","\"",OrderComment(),"\"",",",
       "\"Commission\"",":",OrderCommission(),",",
       "\"Expiration\"",":","\"",OrderExpiration(),"\"",",",
       "\"MagicNumber\"",":",OrderMagicNumber(),",",
       "\"AccountNumber\"",":","\"",AccountNumber(),"\"",",",
       "\"Id\"",":","\"",OrderTicket(),"\"","}"
       );
   return(StringConcatenate(bodyPart1,bodyPart2));
}

交易类是

// POST: api/Transactions
[ResponseType(typeof(Transaction))]
public async Task<IHttpActionResult> PostTransaction(Transaction transaction)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    db.Transactions.Add(transaction);
    try
    {
        await db.SaveChangesAsync();
    }
    catch (DbUpdateException)
    {
        if (TransactionExists(transaction.Id))
        {
            return Conflict();
        }
        else
        {
            throw;
        }
    }

    return CreatedAtRoute("DefaultApi", new { id = transaction.Id }, transaction);
}

但是由于在字符串处理方面Unicode与ANSI的不同,因此Web Api控制器接收到的Transaction对象始终为空。 我尝试使用StringToCharArray将Unicode字符串转换为ANSI,但是HttpSendRequestW希望将字符串作为主体参数。 Wininet.dll的Internet * A功能甚至都不会到达Web Api端点,因为URL也是Unicode,并且它尝试调用http://localhost而不是http://l

由于端口80和443的限制,我无法使用WebRequest。我的端口(至少用于测试)是27408。

任何人都可以帮助我们完成这项工作吗?

0 个答案:

没有答案