code C# use the Google OAuth to sign Google Acount - api

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.

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.

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);
}

Render Razor View into String using .Net Core Console Application

I have prepared a .net core console application (Framework version .Net Core 2.2) for sending email as a service. Right now its working completely fine with static html content being hardcoded into service method for generating email body string.
I am in seek of the code which provides me a solution to render a razor view to have a html string with the model data.
Tried to implement the RazorEngine dll in entity framework ver. 4.5. with below code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GenerateEmailUsingRazor.Model;
using RazorEngine.Templating;
namespace GenerateEmailUsingRazor
{
class Program
{
static readonly string TemplateFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EmailTemplates");
static void Main(string[] args)
{
var model = GetUserDetail();
var emailTemplatePath = Path.Combine(TemplateFolderPath, "InviteEmailTemplate.cshtml");
var templateService = new TemplateService();
var emailHtmlBody = templateService.Parse(File.ReadAllText(emailTemplatePath), model, null, null);
Console.WriteLine(emailHtmlBody);
Console.ReadLine();
}
private static UserDetail GetUserDetail()
{
var model = new UserDetail()
{
Id = 1,
Name = "Test User",
Address = "Dummy Address"
};
for (int i = 1; i <= 10; i++)
{
model.PurchasedItems.Add("Item No " + i);
}
return model;
}
}
}
Expected Result:
Console Application should render the razor view and provide me the resultant html string.
I've written a clean library Razor.Templating.Core that works with .NET Core 3.0, 3.1 on both web and console app.
It's available as NuGet package.
After installing, you can call like
var htmlString = await RazorTemplateEngine
.RenderAsync("/Views/ExampleView.cshtml", model, viewData);
Note: Above snippet won't work straight away. Please refer the below working guidance on how to apply it.
Complete Working Guidance: https://medium.com/#soundaranbu/render-razor-view-cshtml-to-string-in-net-core-7d125f32c79
Sample Projects: https://github.com/soundaranbu/RazorTemplating/tree/master/examples

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.

TFS 2012 Backup and Restore BuildDefinitions only

I installed a TFS2012 as a test system and doing some tests before we go productive.
This includes to define many BuildDefinitions which was a lot of work.
After the tests are successful, an new server will be installed with TFS2012 on it.
For this new server - which operates then as the productive system - i would like to restore the BuildDefinitions from the test system. But only the BuildDefinitions, not the whole TeamCollections. Because i ran test checkins and i don`t want these on my productive server.
Now, is it possible to backup and restore BuildDefinitions only?
Maybe it is possible directly throught the Sql database?, but i`am a little affraid of references there, pointing on some other tables.
Best Regards, Peter Bucher
Build definitions are not source controlled. The only option is relying on the TFS database backup where can restore or view the tbl_BuildDefinition* tables in the Tfs_DefaultCollection database.
There is a user voice for this feature and also you can use TFS API to do it.
Add a vote on uservoice:
provide a way to version-control build definitions
Using TFS API
How can I copy a TFS 2010 Build Definition?
Finally i decided not to touch the database, because there are references to a lot of other tables.
I used the TFS API v11 (TFS2012) and a bit C# Code, which i fitted to my needs from this base: How can I copy a TFS 2010 Build Definition?
It copies all Build Definitions from one TFS2012 Server to another. For both servers there is the need to specifiy a TeamCollection and a TeamProject.
So, the copy-task has to be done per TeamProject.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
namespace TFSBuildDefinitionCreator
{
internal class Program
{
private static void Main(string[] args)
{
// Copies build definitions from one server to another.
// Uses the TeamFoundation API V11 (TFS2012).
// Code was used to copy b uild definitions from a test server to a productive.
string sourceServer = "http://testTfs:8080/tfs/MyTeamCollection";
string sourceTeamProject = "MyTeamProject";
string targetServer = "https://productiveTfs:8080/tfs/MyTeamCollection";
string targetTeamProject = "MyTeamProject";
// DropLocation for defininitions: Share on which the build should be dropped.
string defaultDropLocation = "\\\\MyBuildserver\\Builds$";
// Change the DefaultProcessTemplate in the following method below: GetDefaultProcessTemplateByServerPathFromBuildServer.
CopyBuildDefinitions(sourceServer, sourceTeamProject, targetServer, targetTeamProject, defaultDropLocation);
Console.Read();
}
private static IBuildServer GetBuildServerFromServerUrl(string serverUrl)
{
var tfs = TeamFoundationServerFactory.GetServer(serverUrl);
return (IBuildServer)tfs.GetService(typeof(IBuildServer));
}
private static IBuildController GetDefaultBuildControllerFromBuildServer(IBuildServer buildServer)
{
return buildServer.QueryBuildControllers()[0];
}
private static IProcessTemplate GetDefaultProcessTemplateByServerPathFromBuildServer(IBuildServer buildServer, string teamProject)
{
var processTemplates = buildServer.QueryProcessTemplates(teamProject);
var result = processTemplates.First(t => t.ServerPath.Contains("/BuildProcessTemplates/MyDefaultTemplate.xaml"));
return result;
}
private static void CopyBuildDefinitions(string sourceServer, string sourceTeamProject, string targetServer,
string targetTeamProject, string defaultDropLocation)
{
var sourceBuildServer = GetBuildServerFromServerUrl(sourceServer);
var sourceBuildDetails = sourceBuildServer.QueryBuildDefinitions(sourceTeamProject);
foreach (var sourceBuildDetail in sourceBuildDetails)
{
CopyBuildDefinition(sourceBuildDetail, targetServer, targetTeamProject, defaultDropLocation);
}
}
private static void CopyBuildDefinition(IBuildDefinition buildDefinition, string targetServer, string targetTeamProject, string defaultDropLocation)
{
var targetBuildServer = GetBuildServerFromServerUrl(targetServer);
var buildDefinitionClone = targetBuildServer.CreateBuildDefinition(targetTeamProject);
buildDefinitionClone.BuildController = GetDefaultBuildControllerFromBuildServer(targetBuildServer);
buildDefinitionClone.ContinuousIntegrationType = buildDefinition.ContinuousIntegrationType;
buildDefinitionClone.ContinuousIntegrationQuietPeriod = buildDefinition.ContinuousIntegrationQuietPeriod;
// Noch ändern.
//buildDefinitionClone.DefaultDropLocation = buildDefinition.DefaultDropLocation;
buildDefinitionClone.DefaultDropLocation = defaultDropLocation;
buildDefinitionClone.Description = buildDefinition.Description;
buildDefinitionClone.Enabled = buildDefinition.Enabled;
//buildDefinitionClone.Name = String.Format("Copy of {0}", buildDefinition.Name);
buildDefinitionClone.Name = buildDefinition.Name;
//buildDefinitionClone.Process = buildDefinition.Process;
buildDefinitionClone.Process = GetDefaultProcessTemplateByServerPathFromBuildServer(targetBuildServer, targetTeamProject);
buildDefinitionClone.ProcessParameters = buildDefinition.ProcessParameters;
foreach (var schedule in buildDefinition.Schedules)
{
var newSchedule = buildDefinitionClone.AddSchedule();
newSchedule.DaysToBuild = schedule.DaysToBuild;
newSchedule.StartTime = schedule.StartTime;
newSchedule.TimeZone = schedule.TimeZone;
}
foreach (var mapping in buildDefinition.Workspace.Mappings)
{
buildDefinitionClone.Workspace.AddMapping(
mapping.ServerItem, mapping.LocalItem, mapping.MappingType, mapping.Depth);
}
buildDefinitionClone.RetentionPolicyList.Clear();
foreach (var policy in buildDefinition.RetentionPolicyList)
{
buildDefinitionClone.AddRetentionPolicy(
policy.BuildReason, policy.BuildStatus, policy.NumberToKeep, policy.DeleteOptions);
}
buildDefinitionClone.Save();
}
}
}
Hope that helps others.