0

I'm working on a little project for school. I need to convert a PHP-cUrl file into C#.

Somehow I can't solve it, I used google but didn't help. I used libcurl.NET binding to solve it but no chance for me.

Now I would like to ask you if you could help me with my problem. I need to convert this Code:

<?php

class Curl {

const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';

const CURL_TIMEOUT_IN_SECS = 15;

public static $successFullHttpCodes = array(200, 201, 204);

public function call($url, $urlParams = array(), $postParams = null, $method = self::METHOD_GET, $headers = array()) {
    $finalUrl = $url . $this->getUrlParameterString($urlParams);
    $data = $this->makeCurlCall($finalUrl, $postParams, $method, $headers);
    return $data;
}

/**
 * Creates a curl call for the given url, automatically validates the return value for errors.
 * If an error has been found a new Exception will be thrown.
 * 
 * @param string $url
 * @param array $postParams Parameters for Post and Put-Requests
 * @param string $method HTTP-Method (GET, PUT, POST, DELETE)
 * @param string $headers HTTP-Headers
 * @throws Exception
 */
private function makeCurlCall($url, $postParams = array(), $method = self::METHOD_GET, $headers = array()) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_VERBOSE, 0);
    curl_setopt($curl, CURLOPT_TIMEOUT, self::CURL_TIMEOUT_IN_SECS);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);

    if ($headers) {
        $usableHeaders = array();
        foreach ($headers as $name => $value) {
            $usableHeaders[] = sprintf('%s: %s', $name, $value);
        }

        curl_setopt($curl, CURLOPT_HTTPHEADER, $usableHeaders);
    }

    if ($postParams) {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postParams);
    }

    $data = curl_exec($curl);
    $this->checkForError($curl, $data);

    return $data;
}

/**
 * Checks for any errors in the api response.
 * If an error has been found a new Exception will be thrown.
 *
 * @param string $data the resulting data
 * @throws Exception
 */
private function checkForError($curl, $data) {
    $curlInfo = curl_getinfo($curl);
    if (isset($curlInfo['http_code']) && !in_array($curlInfo['http_code'], self::$successFullHttpCodes)) {
        throw new Exception($curlInfo['http_code'] ? $data : 'could not get a response from the service', $curlInfo['http_code'] ? $curlInfo['http_code'] : 500);
    }
}

/**
 * Builds a valid http query
 *
 * @param array $urlParams
 * @return string
 */
private function getUrlParameterString(array $urlParams) {
    if (!$urlParams) {
        return "";
    }

    return "?" . http_build_query($urlParams);
}

}

?>

Need to convert this file 1to1 to use it in my Project.

Right now I got this C# code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SeasideResearch.LibCurlNet;

namespace ConsoleApplication1
{

class CurlCall
{
    const String method_get = "GET";
    const String method_post = "POST";
    const String method_put = "PUT";
    const String method_delete = "DELETE";

    const int curl_timeout_in_secs = 15;
    public static int[] successFullHttpCodes = { 200, 201, 204 };

    public String call(String url, String[] urlParams, String postParams, String method, String[] header)
    {
        String data = "";
        String finalUrl = "";

        finalUrl = url + this.getUrlParameterString(urlParams);

        return data;
    }

    private String makeCurlCall(String url, String[] postParams, String method, String[] header)
    {
        try
        {
            Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);

            Easy easy = new Easy();
            Easy.WriteFunction wf = OnWriteData;

            easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYPEER, 0);
            easy.SetOpt(CURLoption.CURLOPT_SSL_VERIFYHOST, 2);
            easy.SetOpt(CURLoption.CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
            easy.SetOpt(CURLoption.CURLOPT_WRITEFUNCTION, wf);
            easy.SetOpt(CURLoption.CURLOPT_URL, "http://google.com/index.html");
            easy.SetOpt(CURLoption.CURLOPT_VERBOSE, 0);
            easy.SetOpt(CURLoption.CURLOPT_TIMEOUT, curl_timeout_in_secs);
            easy.SetOpt(CURLoption.CURLOPT_CUSTOMREQUEST, method);

            if(header != null)
            {
                String[] usableHeaders;
                for(int i = 0; i <= header.Length; i++)
                {
                    usableHeaders[i] = string.Format("%s: %s", header[i], i);
                }
                easy.SetOpt(CURLoption.CURLOPT_HTTPHEADER, usableHeaders);
            }

            if (postParams != null)
            {
                easy.SetOpt(CURLoption.CURLOPT_POSTFIELDS, postParams);
            }

            easy.Perform();
            easy.Cleanup();

            Curl.GlobalCleanup();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            Console.ReadKey();
        }
        String data;
        data = "0";
        this.checkForError("", data);
        return data;
    }

    private void checkForError(String curl, String data)
    {
        String curlInfo;
        Curl.GlobalInit((int)CURLinitFlag.CURL_GLOBAL_ALL);
        Easy easy = new Easy();
        curlinfo = easy.GetInfo(CURLINFO, curl);
        if()
        {

        }
    }
    private String getUrlParameterString(String[] urlParams)
    {
        if(urlParams != null)
        {
            return "";
        }

        return "?";
    }
    public static Int32 OnWriteData(Byte[] buf, Int32 size, Int32 nmemb,
    Object extraData)
    {
        Console.Write(System.Text.Encoding.UTF8.GetString(buf));
        Console.ReadKey();
        return size * nmemb;
    }

}

}

I couldn't convert this part, I don't understand the self:: key.

$method = self::METHOD_GET

Also don't know if I converted this parts right.

if ($headers) {



if ($postParams) {

On this code I get an error.

$usableHeaders[] = sprintf('%s: %s', $name, $value);
Error: "Use of unassigned local variable 'usableHeaders'

On the checkForError function I didn't understand what's the $curl variable... Also didn't know hot to use getinfo $curlInfo = curl_getinfo($curl);

Here I didn't found sometihng equal to this part

http_build_query($urlParams);

Hope you guys can help me out.

Btw excuse my english.

Sandeep Nambiar
  • 1,656
  • 3
  • 22
  • 38
Mihawk
  • 815
  • 3
  • 14
  • 31

1 Answers1

1

I try to answer one by one:

I couldn't convert this part, I don't understand the self:: key.

self::METHOD_GET points to your class-internal const String method_get = "GET"; so you could write it like this.method_get.

Also don't know if I converted this parts right.

Nearly. A line like this

if ($headers) {

is in C# like that:

if (header != null && header.lenght > 0) { 

this is not complety, check if it is an array too! Same for the $postParam parameter.

On this code I get an error.

PHP or C#?

On the checkForError function I didn't understand what's the $curl variable.

Like Dependency Injection, you give your configurated variable with all the curl settings to your function with call-by-value.

Also didn't know hot to use getinfo $curlInfo = curl_getinfo($curl);

Tricky, and i do know either, maybe you search in the Microsoft MSDN, starting with a search for curl and then ... i found a link, maybe it helps: http://uniapple.net/blog/?p=1992

Here I didn't found sometihng equal to this part http_build_query($urlParams);

see How to build a query string for a URL in C#?

Community
  • 1
  • 1
Paladin
  • 1,637
  • 13
  • 28
  • Hey there, thanks for your answer. The self:: part didn't worked with the keyword "this.". If I try to do it like in the PHP-File i'll get an error. Somehow I don't get this why I Need to pass the variable already in the param. declaration. The IF-query worked fine. About the error part.. I'll get it in my C#-file. The "checkForError " and "http_build_query($urlParams);" part didn't worked as well – Mihawk Oct 06 '15 at 15:38