google translate api with oauth2.0 - api

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.

Related

How to send automatic emails in aspnet core?

I would like to send automatic email notifications to users after 30 days of inactivity.
For now i can send them manually (one by one), but this is time consuming.
How can i do it automatically, in the background?
Aspnet Core 6.0 C# + Bootstrap 5 + SQL Server
In my humble opinion, you need a trigger to help query inactive users and sent email to them at times. And I used to use Azure function time trigger to do it. And here's my test for your scenario.
Firstly, I have to expose API which is used to query the inactive users, and another one is used to send email.
public string sendEmail(string emailAddress) {
return "send to "+ emailAddress + " successfully";
}
public string queryInactive() {
return "user1#xx.com";
}
Then creating an Azure function time trigger to set it triggered every 9 am. Then write code to let the function call these 2 apis.
#r "Newtonsoft.Json"
using System;
using System.Net;
using System.Text;
using System.IO;
using System.IO.Compression;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static void Run(TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxx/home/queryInactive");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(myResponseStream, Encoding.UTF8);
String userAddress = reader.ReadToEnd();
log.LogInformation(userAddress);
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create("https://xxxx/home/sendEmail?emailAddress="+userAddress);
request.Method = "GET";
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
Stream myResponseStream2 = response2.GetResponseStream();
StreamReader reader2 = new StreamReader(myResponseStream2, Encoding.UTF8);
String responseString = reader2.ReadToEnd();
log.LogInformation(responseString);
}
And this is my test result.

Unity error while trying to send data to an online post 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);
}

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.

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.

Passing a list of parameters from a sql task in SSIS to Web Services URL with a variable

I have a sql query that is generating a list of order numbers...I can place these order numbers individually in the web request URL to Web Services and collect the details of that order. I know how to do that if I had a WSDL file available but the We services is using a RestFul service client and has no WSDL file. I do have a C# code that will work only if I declare the order number and was trying to find out how can I replace this parameter with a DTS variable and use a Foreach loop container to run the rest of the order numbers in the list. Here's the code that I have so far:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using System.Xml;
/**
* A test code to consuming a RESTFUL web service.
* You need to just parse the xml - either save it in memory/Cache to parse immediatly,
* or wrire to file and do read and parse it.
* #author: Jbisht
*/
namespace JbishtApplication
{
class CallWeb
{
static void Main(string[] args)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
String Xml;
String salesOrderNo = "S3107634";
String file_ext = ".xml";
String file_name = salesOrderNo + file_ext;
String file_path = "C:/";
// Create the web request - Zones Test Environment - Orderws URL
// request = WebRequest.Create("http://test2:8080/orderws/order/" + salesOrderNo) as HttpWebRequest;
// Create the web request - My instance - Orderws for test only
request = WebRequest.Create("http://dev2:10580/orderws/order/" + salesOrderNo) as HttpWebRequest;
// Get response
using (response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
Xml = reader.ReadToEnd();
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(Xml);
xdoc.Save(file_path + file_name); // it will save your response xml to file location;
}
// Console xml output
Console.WriteLine(Xml); //see if we get the xml response, (YES we do)
Console.ReadLine(); // Just wrote to keep console window open after writing to console.
}
}
}
In general, you will need a SQL task as the starting point which gets the list of order numbers from database, and saves query result into a variable of Object type, say "OrderNumberList". Then you have a foreach loop container to loop through the "OrderNumberList" variable, and assigning the current value into another variable "OrderNumber".
(If you have not done all of these before, HERE is a link shows how to loop through a database query result set.)
Place a Script task inside the foreach container, and choose "OrderNumber" as readonly variable, so you can reference the variable in the script. Then in the script, "OrderNumber" can be referenced as:
request = WebRequest.Create("http://dev2:10580/orderws/order/" +
((string) Dts.Variables["OrderNumber"].Value)) as HttpWebRequest;