2015-07-03 65 views
-1

我是一個.NET開發人員,和(懺悔時間)我從來沒有用過PHP的任何事情。我發現自己需要轉換一些PHP來測試一個API。我已經完成了大部分的轉換,將我的錯誤數從400增加到了69,但是,我越走越遠,我確信它只會被打破。麻煩轉換一些PHP到C#

因此,我決定拋棄自己的同伴的憐憫,並尋求一些幫助。

我正在轉換的是,這是一個調用API並返回XML或JSON的包裝類。

<?php 

class APIv2 { 
protected $accessToken; 
protected $baseURL; 
protected $functions = array(); 
protected $format = 'json'; 

public function __construct($accountid, $key, $baseURL = 'https://www.eiseverywhere.com') 
{ 
    $this->baseURL = rtrim($baseURL,'/').'/api/v2/'; 
    $request = $this->rawRequest($this->baseURL.'global/authorize.json', 
            array('accountid' => $accountid,'key' => $key)); 
    $response = json_decode($request['response'], true); 
    if (empty($response['accesstoken'])) { 
     throw new \Exception(__CLASS__.': Bad url or parameters given. '.print_r($response,1)); 
    } 
    $this->accessToken = $response['accesstoken']; 
    $response = $this->rawRequest($this->baseURL.'global/listAvailableFunctions.json', 
            array('accesstoken' => $this->accessToken)); 
    $functions = json_decode($response['response'], true); 
    foreach ($functions as $sectionName=>$section) { 
     foreach ($section as $methodName=>$functionArray) { 
      foreach ($functionArray as $functionName) { 
       $this->functions[$functionName] = array('method'=>$methodName, 'section'=>$sectionName); 
      } 
     } 
    } 
} 

public function setFormat($format) 
{ 
    $validFormats = array('xml','json'); 
    if (! in_array($format, $validFormats)) { 
     $message = __CLASS__.": Invalid format: $format. Not one of the following:"; 
     foreach ($validFormats as $value) { 
      $message .= ' '.$value; 
     } 
     throw new \Exception($message); 
    } 
    $this->format = $format; 
} 

public function request($request, $parameters = array()) 
{ 
    $parameters['accesstoken'] = $this->accessToken; 
    if (! array_key_exists($request, $this->functions)) { 
     return array(
      'response' => '', 
      'info' => $this->functions, 
      'errors' => "Unknown function: $request", 
     ); 
    } 
    $function = $this->functions[$request]; 
    $url = $this->baseURL.$function['section'].'/'.$request.'.'.$this->format; 
    return $this->rawRequest($url, $parameters, $function['method']); 
} 

public static function rawRequest($url, $parameters = array(), $method = 'get') 
{ 
    $response = 'Unable to use etouches API, please enable cURL functionality (http://php.net/curl) for your server and try again'; 
    $info = ''; 
    $errors = ''; 
    $method = strtolower($method); 
    if (function_exists('curl_init')) { 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); 
     $paramString = http_build_query($parameters); 
     curl_setopt($ch, CURLOPT_URL, $url . (!empty($paramString)?'?'.$paramString:'')); 
     if ($method == 'post') { 
      foreach ($parameters as &$value) { 
       if (is_array($value)) { 
        $value = http_build_query($value); 
       } 
      } 
      curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters); 
     } else if ($method == 'put') { 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($paramString))); 
      curl_setopt($ch, CURLOPT_POSTFIELDS, $paramString); 
     } 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); 
     curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

     $response = curl_exec($ch); 
     $info = curl_getinfo($ch); 
     $errors = curl_error($ch); 

     curl_close($ch); 
    } 
    return array(
     'response' => $response, 
     'info' => $info, 
     'errors' => $errors 
     ); 
} 

} 

function dump($h1, $var) 
{ 
    echo "<h1>$h1</h1>"; 
    var_dump($var); 
} 

$api = new etouchesAPIv2($yourAccountId, $yourAPIKey); 

$response = $api->request($call = 'listFolders'); 
$folders = json_decode($response['response'], true); 
dump($call, $folders); 

$parameters = array('name' => "New event created by etouches API", 
        'modules' => array('eHome','eMobile','eSelect','eReg','eBooth','eConnect','eSocial','eSeating'),); 
if (count($folders)) { 
    $parameters['folder'] = $folders[0]['folderid']; 
} 
$api->setFormat('xml'); 
$response = $api->request($call = 'createEvent', $parameters); 
$newEvent = new SimpleXMLElement($response['response']); 
dump($call, $newEvent); 

$api->setFormat('json'); 
$response = $api->request($call = 'listEvents'); 
$events = json_decode($response['response'], true); 
dump($call, $events); 

$api->setFormat('xml'); 
$response = $api->request($call = 'listSpeakers', array('eventid' => $events[0]['eventid'])); 
$speakers = new SimpleXMLElement($response['response']); 
dump($call, $speakers); 

$response = $api->request($call = 'getEvent', array('eventid' => $events[0]['eventid'])); 
$event = new SimpleXMLElement($response['response']); 
dump($call, $event); 

$response = $api->request($call = 'cloneEvent', array('eventid' => $events[0]['eventid'],'name'=>"Event cloned via etouches API")); 
$clonedEvent = new SimpleXMLElement($response['response']); 
dump($call, $clonedEvent); 

我最麻煩的地方是PHP方法調用。我一直在盡我所能地查找c#等價物,但最終結果並不美觀。所以,請你參考一下'PHP到C#'的工具或轉換參考,或者幫我拿出CURL,__CLASS__和其他PHP細節?

我應該注意,我已經看過Phalanger,如果可能的話,寧願不要使用它。到目前爲止,我還沒有找到任何全面的PHP到C#的轉換工具或指南。

預先感謝您!

編輯:

按照要求,這裏是我在嘗試轉換(。我知道,這是凌亂的,我不感到自豪的是未完全轉換,通量)

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Script.Serialization; 
using System.Net; 
using System.Diagnostics; 
using System.Xml; 

namespace Test { 
    public partial class _Default : System.Web.UI.Page { 
     protected static string accessToken; 
     protected static string baseURL; 
     protected Dictionary<string, string> functions = new Dictionary<string,string>(); 
     protected string format = "json"; 

    XmlDocument xml = new XmlDocument(); 

    protected void Page_Load(object sender, EventArgs e) { 
     string accountid = (ACCOUNTID); 
     string key = (KEY); 
     string baseURL = "https://www.eiseverywhere.com"; 

     baseURL = baseURL.Remove(baseURL.LastIndexOf("/"),1).TrimEnd() + "/api/v2/";//rtrim(baseURL,"/")+"/api/v2/"; 

     Debug.WriteLine("baseURL: " + baseURL); 

     string request = RawRequest(baseURL+"global/authorize.json", 
             new string[]{accountid,key}); 
     //string response = json_decode(request["response"], true); 
     var data = new Dictionary<string, string>(); //REF:http://stackoverflow.com/questions/7699972/how-to-decode-a-json-string-using-c 
     //data.Add("foo", "baa"); 
     JavaScriptSerializer ser = new JavaScriptSerializer(); 
     var JSONString = ser.Serialize(data); 
     var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); 

     string response = JSONObj["response"]; 

     //if (empty(response["accesstoken"])) { 
     // throw new Exception(__CLASS__+": Bad url or parameters given. "+print_r(response,1)); 
     //} 
     accessToken = JSONObj["accesstoken"]; //response["accesstoken"]; 
     response = RawRequest(baseURL+"global/listAvailableFunctions.json", new string[]{accessToken}); 
     functions = JSONObj;//json_decode(response["response"], true); 
     foreach (var section in functions) { 
      foreach (var functionArray in section) { 
       foreach (var functionName in functionArray) { 
        this.functions[functionName] = new List<string>{methodName, sectionName}; 
       } 
      } 
     } 


     //_Default api = new _Default(); 

     string call = "listFolders"; 

     response = Request(call); 
     string folders = json_decode(response["response"], true); 
     //Dump(call, folders); 

     string[] parameters = new string[]{"New event created by etouches API","eHome","eMobile","eSelect","eReg","eBooth","eConnect","eSocial","eSeating"}; 
     if (count(folders)) { 
      parameters["folder"] = folders[0]["folderid"]; 
     } 

     xml.LoadXml(SomeXMLString); 
     string itemID = xml.GetElementsByTagName("itemID")(0).InnerText; 

     call="createEvent"; 
     this.SetFormat("xml"); 
     response = Request(call, parameters); 
     string newEvent = new SimpleXMLElement(response["response"]); 
     //Dump(call, newEvent); 

     this.SetFormat("json"); 
     response = Request(call = "listEvents"); 
     string events = json_decode(response["response"], true); 
     //Dump(call, events); 

     this.SetFormat("xml"); 
     response = Request(call = "listSpeakers", new string[]{events[0]["eventid"]}); 
     string speakers = new SimpleXMLElement(response["response"]); 
     //Dump(call, speakers); 

     response = Request(call = "getEvent", new string[]{events[0]["eventid"]}); 
     string eventt = new SimpleXMLElement(response["response"]); 
     //Dump(call, eventt); 

     response = Request(call = "cloneEvent", new string[]{events[0]["eventid"],"Event cloned via etouches API"}); 
     string clonedEvent = new SimpleXMLElement(response["response"]); 
     //Dump(call, clonedEvent); 

    } 

    public void SetFormat(string format) 
    { 
     string[] validFormats = new string[]{"xml","json"}; 
     if (!validFormats.Contains(format)) { 
      string message = __CLASS__+": Invalid format: " + format + " Not one of the following:"; 
      foreach (var value in validFormats) { 
       message = " "+value; 
      } 
      throw new Exception(message); 
     } 
     this.format = format; 
    } 

    public static string Request(string request, string[] parameters) 
    { 
     parameters["accesstoken"] = accessToken; 
     if (! array_key_exists(request, functions)) { 
      return new string[]{ 
       "", 
       functions, 
       "Unknown function: request", 
     }; 
     } 
     string[] function = functions[request]; 
     string url = baseURL.function["section"]+"/"+request+"+"+this.format; 
     return RawRequest(url, parameters, function["method"]); 
    } 

    public static string RawRequest(string url, string[] parameters) 
    { 
     string[] result; 
     string method = "get"; 
     string response = "Unable to use etouches API, please enable cURL functionality (http://php.net/curl) for your server and try again"; 
     string info = ""; 
     string errors = ""; 
     method = method.ToLower(); 

     //string ch = curl_init(); 
     HttpWebRequest ch = (HttpWebRequest)WebRequest.Create(this.Request.Url.Scheme); 
     curl_setopt(ch, CURLOPT_CUSTOMREQUEST, method); 
     string paramString = http_build_query(parameters); 
     curl_setopt(ch, CURLOPT_URL, url . (!empty(paramString)?"?"+paramString:"")); 
     if (method == "post") { 
      foreach (var value in parameters) { 
       if (is_array(value)) { 
        value = http_build_query(value); 
       } 
      } 
      curl_setopt(ch, CURLOPT_POSTFIELDS, parameters); 
     } else if (method == "put") { 
      curl_setopt(ch, CURLOPT_RETURNTRANSFER, true); 
      curl_setopt(ch, CURLOPT_HTTPHEADER, new string[]{"Content-Length: " , paramString.Length}); 
      curl_setopt(ch, CURLOPT_POSTFIELDS, paramString); 
     } 
     curl_setopt(ch, CURLOPT_RETURNTRANSFER, true); 
     curl_setopt(ch, CURLOPT_CONNECTTIMEOUT, 10); 
     curl_setopt(ch, CURLOPT_TIMEOUT, 30); 
     curl_setopt(ch, CURLOPT_SSL_VERIFYPEER, false); 

     response = curl_exec(ch); 
     info = curl_getinfo(ch); 
     errors = curl_error(ch); 

     curl_close(ch); 


     result = new string[]{response,info,errors}; 

     return result; 
    } 

    //private void Dump(string h1, string var) 
    //{ 
    // Response.Write("<h1>" + h1 + "</h1>"); 
    // var_dump(var); 
    //} 
}//class 
+3

至少發表了迄今爲止所做的工作。 – Cyral

+2

PHP代碼看起來有點過時。不知道是否可以幫助你,但最有可能的是,它不僅可以在PHP中壓縮,還可以在.NET中壓縮。也許你更容易理解它的功能,然後在.NET中從頭開始編寫功能。 – hakre

+0

非常感謝,誠實地說,我絕對傾向於這種方式。 – sabastienfyrre

回答

1

我創建了一個新的問答,名爲「How to Convert PHP to .NET For Beginners」。這是我對該主題的所有研究成果,並解釋了對我有用的東西。我希望它能幫助你找到一個快速簡單的解決方案。

+0

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/18857045) – pirho