How to create simpliest PHP Get API with UTF-8 support? - c#

How to create simpliest *(less lines of code, less strange words) PHP Get API *(so any programm made in .Net C# could call url like http://localhost/api.php?astring=your_utf-8_string&bstring=your_utf-8_string ) with UTF-8 support?
What I need Is PHP API with one function - concatinate 2 strings so that a simple .net client like this would be able to use it:
public string setStream(string astring, string bstring)
{
string newAstring =Uri.EscapeDataString(astring);
string newBstring = Uri.EscapeDataString(bstring);
WebClient client = new WebClient();
var result = client.DownloadString(("http://localhost/api.php?" + string.Format("astring={0}&bstring={1}", newAstring, newBstring)).ToString());
return result;
}

public string SetStream(string astring, string bstring)
{
using (var client = new WebClient())
{
var values = new NameValueCollection() {
"astring", astring,
"bstring", bstring
};
var result = client.UploadValues(
"http://localhost/api.php",
"GET",
values
);
return Encoding.Default.GetString(result);
}
}

Dunno if I'm missing something, but:
<?php
function concatinateStrigs($a, $b){
return $a . $b;
}
echo concatinateStrigs($_GET['astring'], $_GET['bstring']);
?>

Related

How does this Google API Translator does work?

I came across this code here and I would like someone to explain it to me(I would like to use something like this for my compiler).
I would like to ask directly below the question, logically, but I can't add a comment.
How does the Google Translate API work in C#? I assume you have to download some Nuget
How do you change the language?
Here is the code:
var toLanguage = "en";//English
var fromLanguage = "de";//Deutsch
var url = $"https://translate.googleapis.com/translate_a/single?client=gtx&sl={fromLanguage}&tl={toLanguage}&dt=t&q={HttpUtility.UrlEncode(word)}";
var webClient = new WebClient
{
Encoding = System.Text.Encoding.UTF8
};
var result = webClient.DownloadString(url);
try
{
result = result.Substring(4, result.IndexOf("\"", 4, StringComparison.Ordinal) - 4);
return result;
}
catch
{
return "Error";
}

Trying to transfer ERC20 token using C# .NET Nethereum package

Can someone help me successfully send ERC20 tokens using the Nethereum package in C# .NET?
I am able to successfully get account balances, but when I try to send, it just sits there....
I am using the Infura.io project api also with the below security:
eth_accounts
eth_call
eth_getBalance
eth_getTransactionReceipt
eth_sendRawTransaction
var client = new EthClient(new RpcUrl("https://mainnet.infura.io/v3/-MyProjectID-"));
Here is the code I am using:
--The call to the transfer method
/* transfer 100 tokens */
var transactionHashTask = client.transferTokens(coinOwnerAddress, coinOwnerPrivateKey, toAddress, contractAddress, 0);
var transactionHash = transactionHashTask.Result.ToString();
lblTransHash.Text = "Transaction hash: " + transactionHash;
--Code that contains the actual method
public async Task<string> transferTokens(string senderAddress, string privateKey, string receiverAddress, string contractAddress, UInt64 tokens)
{
var transactionMessage = new TransferFunction()
{
FromAddress = senderAddress,
To = receiverAddress,
AmountToSend = tokens
};
var transferHandler = web3.Eth.GetContractTransactionHandler<TransferFunction>();
Task<string> transactionHashTask = transferHandler.SendRequestAsync(contractAddress,transactionMessage);
return await transactionHashTask;
}
You are transferring something right? So maybe you have to send extra to account for the gas fees. But i'm no expert. Let me know if you solve this please.
The transfer function doesn't have AmountToSend parameter. It has TokenAmount. So change like below
var transactionMessage = new TransferFunction()
{
To = receiverAddress,
TokenAmount= tokens
};

Get the link of the uploaded file with UnityWebRequest and php

I want to allow the user to use a local image from his machine and upload it to the server.
What I did is use UnityWebRequest in-game, load the image, send it to a PHP file on the server, and wait for the reply to remember the URL where the file si saved(to save it in Playfab later).
This is the code I made so far:
private readonly string setAvatarUrl = "http://myurl.com/setavatar.php";
private readonly string playerIdField = "playfabid";
private readonly string imageField = "img_avatar";
public IEnumerator SaveImageToDB(Texture2D image)
{
byte[] bytes = image.EncodeToPNG();
WWWForm form = new WWWForm();
form.AddField(playerIdField, player.playerId);
form.AddBinaryData(imageField, bytes, "avatar.png", "image/png");
UnityWebRequest www = new UnityWebRequest();
www = UnityWebRequest.Post(setAvatarUrl, form);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError)
{
Debug.LogError(www.error);
}
else
{
string jsonFromDB = www.downloadHandler.text; // Return empty string
string imageUrl = JsonUtility.FromJson<string>(jsonFromDB);
Debug.Log($"JSON returned: {jsonFromDB}");
if (!string.IsNullOrEmpty(imageUrl))
{
// Save the url
}
Debug.Log("Image upload complete!");
}
}
And this is the PHP file:
<?php
ini_set('display_errors',1);
$idplayfab = $_POST['playfabid'];
$path = 'avatar/'.$idplayfab;
if(file_exists($path)) {
//dir exist
$files = glob($path.'/*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
} else {
//not exist
mkdir($path);
}
$uploadfile = $path ."/". basename($_FILES['img_avatar']['name']);
if (move_uploaded_file($_FILES['img_avatar']['tmp_name'], $uploadfile)) {
$array = array('result' => 'ok', 'url' => 'http://myurl.com/'.$uploadfile);
$json = json_encode($array);
return $json;
} else {
$array = array('result' => 'ko');
$json = json_encode($array);
return $json;
}
?>
The image is saved on the server but the problem is when I try to get the JSON to get the URL, the string is empty and I don't understand why.
I tried tons of solutions like this one or this one but I cannot figure it out.
I also tried to use the deprecated WWW instead, but still, it doesn't work.
I'm kinda new to PHP so maybe it could be the PHP part the problem I believe.
Not an PHP expert but:
Afaik return is only used to evaluate certain functions e.g. for success or in order to further handle the result of something before responding to the client on server side.
What you want to do is rather sending your content as the http result to the client
=> You should rather use echo or print which is used to generate the http output.

C# Web Api Post method with simple type parameters

I'm hoping someone can help. I have been asked to write a test application to consume a Web API.
The method I'm trying to consume, has the following signature:
[Transaction]
[HttpPost]
[Route("api2/Token/")]
public ApiToken Token(Guid companyId, DateTime dateTime, string passCode)
I've written a simple C# console application. However whatever I send to the API returns with a 404 error message and I can't see what my issue is.
My code to consume the API is as follows:
_client.BaseAddress = new Uri("http://localhost:1390");
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var companyId = Guid.Parse("4A55A43A-5D58-4245-AD7C-A72300A69865");
var apiKey = Guid.Parse("FD9AEE25-2ABC-4664-9333-B07D25ECE046");
var dateTime = DateTime.Now;
var sha256 = SHA256.Create();
var bytes = Encoding.UTF8.GetBytes(string.Format("{0}:{1:yyyyMMddHHmmss}:{2}", companyId, dateTime, apiKey));
var hash = sha256.ComputeHash(bytes);
var sb = new StringBuilder();
foreach (var b in hash)
{
sb.Append(b.ToString());
}
try
{
Console.WriteLine("Obtain an authorisation token");
var response = await _client.PostAsJsonAsync("api2/Token/", new { companyId = companyId, dateTime = dateTime, passCode = sb.ToString() });
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
All examples I've googled seem to post an object to a Web API method that accepts an object. Is it possible to post multiple simple types?
I don't think it's possible, from the documentation (https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api)
They've stated that
If the parameter is a "simple" type, Web API tries to get the value
from the URI.
For complex types, Web API tries to read the value from the message body
You can try to use uri parameters instead
var response = await _client.PostAsJsonAsync("api2/Token/{companyId}/{dateTime}/{sb.ToString()}");

App doesn't response after got content of URL

I a absolute new beginner with Swift. So i wanted to get a string from URL (in C#:
wc = System.Net.WebClient();
string response = wcDownloadString("url");
)
In Swift i tried that:
func StrToUrl(newURL: String) -> NSURL
{
return NSURL(string: newURL)!;
}
func DataToStr(getData: NSData) -> String
{
var datastring = NSString(data: getData, encoding:NSUTF8StringEncoding) as! String;
return datastring;
}
func getStringFromURL(url: String) -> String
{
return DataToStr(NSData(contentsOfURL: StrToUrl(url))!);
}
func action()
{
let tmpNewsCount = getStringFromURL("http://example.com"); // STUCK HERE
L_lastSeen.setValue("Got String: " + tmpNewsCount);
}
But after i started the function action(), my app doesn't response.
Seems like Mac App functions are running asynchron. So i can start other functions in my App, too!?
Thank You!

Categories

Resources