Unity error while trying to send data to an online post api - api

I'am trying to make a post api work on unity with a dummy post api online before working on a real post api that is part of my internship's project.
I dont really know why the post api is not working on unity despite that i entered the right arguments and it works on postman.
i have commented my code a little bit that might help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class API: MonoBehaviour {
private const string URL = "http://dummy.restapiexample.com/api/v1/create";
public Text responseText;
public void Request() {
WWWForm FORM = new WWWForm();
FORM.AddField("name", "tarek");
FORM.AddField("salary", "9001");
FORM.AddField("age", "26");
byte[] rawFormData = FORM.data;
WWW request = new WWW(URL, rawFormData);
StartCoroutine(Reponse(request));
Debug.Log("text :" + request.text);
}
private IEnumerator Reponse(WWW req) {
yield
return new WaitForSeconds(2.0 f);
yield
return req;
responseText.text = req.text;
Debug.Log("end : " + req.text);
}

Related

google translate api with oauth2.0

I have a low-volume chat server. Some of the customers speak different languages so I have been using google translate and it had been working fine for years up to a couple weeks ago. I had been using a simple program like this:
// mcs -debug -out:TestTranslate.exe TestTranslate.cs
// mono --debug TestTranslate.exe
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
public class TestTranslate {
public static void Main (string[] args)
{
string apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string message = "hello";
string srclc = "en";
string dstlc = "fr";
string query = "key=" + UrlEncode (apikey) +
"&q=" + UrlEncode (message) +
"&source=" + UrlEncode (srclc) +
"&target=" + UrlEncode (dstlc);
WebRequest request = WebRequest.Create ("https://www.googleapis.com/language/translate/v2?" + query);
request.Method = "GET";
request.Timeout = 3000;
string reply = new StreamReader (request.GetResponse ().GetResponseStream ()).ReadToEnd ();
Console.WriteLine (reply);
}
public static string UrlEncode (string text)
{
return text.Replace (" ", "+");
}
...but now it gets a '403' error. I suspect it is because I am not using OAuth2.0. I can't make any sense of the Google doc, it just goes round and round. Does anyone know how to make it work? I'm pretty sure I am using what they call 'service account', ie, one of my servers talking to one of their servers without any end-user authentication. I was able to download the OAuth2.0 json credential file. I would like to use C#/mono but Java is ok too.

SendGrid 'DeliverAsync()' Not Working

I'm trying to send an email with Azure and SendGrid. I have it all set up (I think) and my code is as per below, but the 'DeliverAsync()' method is not working and there is no 'Deliver()' option available.
Here are my using statements:
using System;
using System.Web;
using System.Web.UI;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Net.Mail;
using SendGrid;
Here is my code: 'transportWeb.DeliverAsync(myMessage)' is showing as plain black text.
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
myMessage.AddTo("d#gmail.com");
myMessage.From = new MailAddress("d#gmail.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";
var apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// create a Web transport, using API Key
var transportWeb = new Web(apiKey);
// Send the email, which returns an awaitable task.
transportWeb.DeliverAsync(myMessage);
I'm hoping someone has seen this before and knows the solution. There are a lot of similar problems online, but none I've found with a fix to this. I am using SendGrid v6.3.4. I have tried reverting to v6.3.3 but it didnt help. My stats in SendGrid show zero for everything, no emails sent, no requests, no bounces etc.
UPDATE:
I have tried creating a new Email class to remove any clutter and make this clearer, the 'DeliverAsync' method is still not being recognized after transportWeb.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Mail;
using SendGrid;
using System.Threading.Tasks;
namespace CPWebsite
{
public class Email
{
static async void Main()
{
try
{
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
myMessage.AddTo("d#gmail.com");
myMessage.From = new MailAddress("d#gmail.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";
var apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// create a Web transport, using API Key
var transportWeb = new Web(apiKey);
// Send the email, which returns an awaitable task.
await transportWeb.DeliverAsync(myMessage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
I have also tried changing var myMessage = new SendGridMessage(); to SendGridMessage myMessage = new SendGridMessage(); but no luck. Only the following using statements are showing as necessary.
using System;
using System.Net.Mail;
using SendGrid;
Im trying anything at this point!
Is this a console app currently? You'll need to await the method otherwise the console apps main thread will complete execution and cause the worker threads to be killed before they successfully deliver the message.
Try:
await transportWeb.DeliverAsync(myMessage);
Also add the following to your using statements:
using System.Threading.Tasks;
My project (Windows Service) was essentially synchronous with respect to specific thread where SendGrid was called, and hence what I had to do to make it work is to add .Wait() after the .DeliverAsync().
And so, try:
static void Main()
and later:
transportWeb.DeliverAsync(myMessage).Wait();
There is actually a little foot-note in SendGrid documentation eluding to this technique.
Cheers.
I don't know if this has been resolved but try using myMessage.Html for the body instead of myMessage.Text. Especially if you are using html in the body. I have pretty much the same setup and my code works fine.

Accessing the Request.Content in the new ASP.NET vnext web api way of doing things?

I have searched high and low for this one and can't seem to find a way of accessing the Request.Content in an MVC web api. I basically am trying to create a File Service to and from Azure Blob and Table storage (table for storing metadata about the file, blob for the actual file)....
I was converting the steps in the following link, but this is where I have come unstuck
the back end I have working but can't find a way of the new unified controller passing a fileobject from json post through to the service! Any ideas would be greatly appreciated as always... or am I just going about this the wrong way?
Article here....
UPDATE: so to clarify, what I am trying to do in the new MVC 6 (where you no longer have an apicontroller to inherit from) is to access a file that has been uploaded to the api from a JSON post. That is the long and short of what I am trying to achieve.
I am trying to use the article based on the old Web API which uses the Request.Content to access it, however even if I use the WebAPIShim which they provide I still come unstuck with other objects or properties that are no longer available so I'm wondering if I need to approach it a different way, but either way, all I am trying to do is to get a file from a JSON post to a MVC 6 Web api and pass that file to my back end service....
ANY IDEAS?
Here is an example without relying on model binding.
You can always find the request data in Request.Body, or use Request.Form to get the request body as a form.
[HttpPost]
public async Task<IActionResult> UploadFile()
{
if (Request.Form.Files != null && Request.Form.Files.Count > 0)
{
var file = Request.Form.Files[0];
var contentType = file.ContentType;
using (var fileStream = file.OpenReadStream())
{
using (var memoryStream = new MemoryStream())
{
await fileStream.CopyToAsync(memoryStream);
// do what you want with memoryStream.ToArray()
}
}
}
return new JsonResult(new { });
}
If the only thing in your request is a File you can use the IFormFile class in your action:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}

code C# use the Google OAuth to sign Google Acount

My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Blogger.v3;
using Google.Apis.Blogger.v3.Data;
using Google.Apis.Services;
using System.Diagnostics;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Util;
namespace BloggerTest
{
class Program
{
static void Main(string[] args)
{
string apiKey= "{API-KEY}";
string blogUrl= "{BLOG-URL}";
string clientID = "{CLIENT_ID}";
string clientSec = "{CLIENT_SECRET}";
NativeApplicationClient provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = clientID,
ClientSecret = clientSec
};
OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, getAuth);
BloggerService blogService = new BloggerService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "BloggerTest"
});
BlogsResource.GetByUrlRequest getReq = blogService.Blogs.GetByUrl(blogUrl);
getReq.Key = apiKey;
Blog blog = getReq.Execute();
Console.WriteLine(blog.Id);
Console.ReadKey();
}
private static IAuthorizationState getAuth(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[] { BloggerService.Scopes.Blogger.GetStringValue() })
{
Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl)
};
Uri authUri = arg.RequestUserAuthorization(state);
Process.Start(authUri.ToString());
Console.WriteLine("Please enter auth code:");
string authCode = Console.ReadLine();
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
And it have 2 error:
'Google.Apis.Services.BaseClientService.Initializer' does not contain a definition for 'Authenticator'
'Google.Apis.Blogger.v3.BloggerService' does not contain a definition for 'Scopes'
Can you help me fix. Thank you very much!
I get code from: http://garyngzhongbo.blogspot.com/2013/10/bloggerc-blogger-api-v3-6oauth-20.html
There are two common problems faced by beginners when the implement Google APIs. These are both due to the API libraries being unstable, and changing from one release to the next.
When the API changes, the sample apps don't. So developers try to use out of date code with the latest API.
Links to old versions of the API libraries are not purged. So developers can find themselves downloading old libraries.
So 1 and 2 are kinda the opposite, but both occur. Problem 1 is the more common.
So in this case, check that you have downloaded the very latest versions of the API library, and check if the missing definitions have in fact been withdrawn, in which case you'll need to find a more up to date example.

How To Use Groovy HTTPBuilder To Get Stories from AgileZen?

I would like to pull stories from Agile Zen using their REST API.
I read:
http://help.agilezen.com/kb/api/overview
http://help.agilezen.com/kb/api/security
Also, I got this to work: http://groovy.codehaus.org/HTTP+Builder
How would one combine the above in order to get Groovy client code to access AgileZen stories?
Here is the code sample which makes one story with id of 1 show up for a specific project whose id is 16854:
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.JSON
public class StoryGetter {
public static void main(String[] args) {
new StoryGetter().getStories()
}
void getStories() {
// http://agilezen.com/project/16854/story/4
// /api/v1/project/16854/story/2
def http = new HTTPBuilder( 'http://agilezen.com' )
http.request( GET, JSON ) {
uri.path = '/api/v1/project/16854/story/1'
headers.'X-Zen-ApiKey' = 'PUT YOUR OWN API KEY HERE'
response.success = { resp, json ->
println "json size is " + json.size()
println json.toString()
}
}
}
}
I had to put in a fake API key in this post since I should not share my API key.
(By the way, this is not using SSL. A follow up question in regards to doing this for a SSL enabled project may come soon.)