I am new to Google Compute Engine. Some one please help me with creating Google Compute Engine VMs programmatically using REST APIs in C#.
Here [1] you can found the API documentation to create an instance and at the bottom of the document the C# examples [2]:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Compute.v1;
using Google.Apis.Services;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using Data = Google.Apis.Compute.v1.Data;
namespace ComputeSample
{
public class ComputeExample
{
public static void Main(string[] args)
{
ComputeService computeService = new ComputeService(new BaseClientService.Initializer
{
HttpClientInitializer = GetCredential(),
ApplicationName = "Google-ComputeSample/0.1",
});
// Project ID for this request.
string project = "my-project"; // TODO: Update placeholder value.
// The name of the zone for this request.
string zone = "my-zone"; // TODO: Update placeholder value.
// TODO: Assign values to desired properties of `requestBody`:
Data.Instance requestBody = new Data.Instance();
InstancesResource.InsertRequest request = computeService.Instances.Insert(requestBody, project, zone);
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
Data.Operation response = request.Execute();
// Data.Operation response = await request.ExecuteAsync();
// TODO: Change code below to process the `response` object:
Console.WriteLine(JsonConvert.SerializeObject(response));
}
public static GoogleCredential GetCredential()
{
GoogleCredential credential = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
}
return credential;
}
}
}
[1] https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert
[2] https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert#examples
Related
Here is my code:
using System;
using System.Net;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Auth.OAuth2;
using System.Threading;
using System.Linq;
namespace WebsiteTextExtractor {
class Program {
async static Task Main(string[] args) {
string websiteURL = "CensoredURLThatWorks";
WebClient client = new WebClient();
string websiteText = client.DownloadString(websiteURL);
//File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+ "\\ElieCours.ics", websiteText);
// Console.WriteLine($"ElieCours.ics Updated at {Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ElieCours.ics"}.");
string[] scopes = new string[] { CalendarService.Scope.Calendar };
var credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets {
ClientId = "[redacted]",
ClientSecret = "[redacted]"
},
scopes,
"MyClient",
CancellationToken.None
).Result;
var service = new CalendarService(new BaseClientService.Initializer() {
HttpClientInitializer = credentials,
ApplicationName = "CalendarCleaner"
});
var events = service.Events.List("fc47dab8b05e7b6d0e549ff3207b9f400adfb8ff96b50ecc4ed51a9ecc75ebbe#group.calendar.google.com").Execute().Items;
//Deleting all events
ParallelOptions parallel = new() {
MaxDegreeOfParallelism = 3,
};
Console.WriteLine(events.Count);
await Parallel.ForEachAsync(events, parallel, async (ev, token) => {
await Task.Delay(300, token);
await service.Events.Delete("fc47dab8b05e7b6d0e549ff3207b9f400adfb8ff96b50ecc4ed51a9ecc75ebbe#group.calendar.google.com", ev.Id).ExecuteAsync(token);
});
Ical.Net.Calendar calendarICS = Ical.Net.Calendar.Load(websiteText);
var eventsICS = calendarICS.Events;
await Parallel.ForEachAsync(eventsICS, parallel, async (ev, token) => {
Event newEvent = new() {
Summary = ev.Summary,
Start = new EventDateTime { DateTime = ev.Start.AsSystemLocal },
End = new EventDateTime { DateTime = ev.End.AsSystemLocal },
Description = ev.Description,
};
await Task.Delay(300, token);
await service.Events.Insert(newEvent, "fc47dab8b05e7b6d0e549ff3207b9f400adfb8ff96b50ecc4ed51a9ecc75ebbe#group.calendar.google.com").ExecuteAsync(token);
});
}
}
}
the part where i'm supposed to be getting the events that are in the "events" var is troubling me: the array is empty. But the adding events part just below is working perfectly. Why?
I saw this post: Google Calendar Events Response is Empty
and i was even more confused, because my methods has nothing to do with what they have.
i tried adding a service account, freshly created, to my agenda: nothing. Making my agenda public: nothing. Whatever i do, this array is empty. Best thing is that it wasn't earlier this morning, and now it is. And i know this might be dumb to specify, but i triplechecked my agenda, and it's not empty.
Worst thing is : deleting used to work.
EDIT: saw this post: Google Calendar v3 API [Events: list] request return Empty List
An answer was really interesting... Detailed the way google doesn't really deleted the events or so...? I'm so confused.
"There is no way I know of to return all events in one call. You need to loop through the process getting a page at a time until the "NextPageToken" is no longer returned. This makes sense, because for users that have huge calendars with 1000's of appointments, it's inefficient to return everything in one request." Even more here, never heard of nextpagetoken or so
I am trying to send text message to phone. Can someone tell me why my return statement is not working? If i write only string message in my return statement then it shows that message but if i use below mentioned return statement it doesn't work. Any suggestions?
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Twilio;
using Twilio.AspNet.Mvc;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace TwilioSendSMS.Controllers
{
public class SMSController : TwilioController
{
// GET: SMS ----- outbound----
public ActionResult SendSms()
{
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "ACxxxxxxxxx";
const string authToken = "71xxxxxxxxxx";
// Initialize the Twilio client
TwilioClient.Init(accountSid, authToken);
// make an associative array of people we know, indexed by phone number
var people = new Dictionary<string, string>() {
{"+18180000000", "Kim"},
{"+14401112222", "Raj"}
};
// Iterate over all our friends
foreach (var person in people)
{
// Send a new outgoing SMS by POSTing to the Messages resource
MessageResource.Create(
from: new PhoneNumber("+15005550006"), // From number, must be an SMS-enabled Twilio number
to: new PhoneNumber(person.Key), // To number, if using Sandbox see note above
// Message content
body: $"Hey {person.Value} Party is at 6PM! Don't forget to bring gift.");
}
//return Content($"Message has been sent!");
return Content($"Sent message to {person.Value}");
}
}
}
Below is the working code!
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Twilio;
using Twilio.AspNet.Mvc;
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
namespace TwilioSendSMS.Controllers
{
public class SMSController : TwilioController
{
// GET: SMS ----- outbound----
public ActionResult SendSms()
{
// Find your Account Sid and Auth Token at twilio.com/user/account
const string accountSid = "ACxxxxxxxxx";
const string authToken = "71xxxxxxxxxx";
// Initialize the Twilio client
TwilioClient.Init(accountSid, authToken);
// make an associative array of people we know, indexed by phone number
var people = new Dictionary<string, string>() {
{"+18180000000", "Kim"},
{"+14401112222", "Raj"}
};
// Iterate over all our friends
var name ="";
foreach (var person in people)
{
// Send a new outgoing SMS by POSTing to the Messages resource
MessageResource.Create(
from: new PhoneNumber("+15005550006"), // From number, must be an SMS-enabled Twilio number
to: new PhoneNumber(person.Key), // To number, if using Sandbox see note above
// Message content
body: $"Hey {person.Value} Party is at 6PM! Don't forget to bring gift.");
name = $"{name} {person.Value}";
}
return Content($"Sent message to {name}");
}
}
}
I am working on a Windows app and am having some issues with cookies. Please note that I am working with Windows.Web.Http, not the System namespace HttpClient.
The API I'm working with uses an auth-header for authentication. Basically after a POST to login, I need a way to get the cookies returned and then use those cookies to perform the subsequent API calls. I posted an example of what I currently have, which succeeds. I can see the cookies in the result object. I'm just not entirely sure where to go from here / how to proceed. Thanks! Any ideas?
using MyApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Http;
using Newtonsoft.Json;
using MyApi.Models.Auth;
using MyApi.Models;
namespace MyApi
{
public class MyService
{
private const string MyBaseUrl = "http://api.my.com:3000";
private readonly HttpClient _httpClient = new HttpClient();
public async Task<SignInResponse> AttemptLogin(string username, string password)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
throw new ArgumentException("Username or password is null or empty");
var uri = new Uri(string.Format("{0}/{1}", MyBaseUrl, "auth/signin"));
var authSignIn = new Models.Auth.SignInRequest();
authSignIn.Email = username;
authSignIn.Password = password;
var myObject = JsonConvert.SerializeObject(authSignIn);
// I see the headers in the result object, but I'm not
// sure the best way to a) get them out and b) shove them into
// all of the next calls
var result = await _httpClient.PostAsync(uri,
new HttpStringContent(myObject.ToString(),
Windows.Storage.Streams.UnicodeEncoding.Utf8,
"application/json"));
var content = await result.Content.ReadAsStringAsync();
var successResponse = new SignInResponse();
try
{
successResponse = JsonConvert.DeserializeObject<SignInResponse>(content);
}
catch (Exception)
{
var failResponse = JsonConvert.DeserializeObject<ErrorResponse>(content);
throw new Exception(failResponse.message);
}
return successResponse;
}
}
}
You can use HttpBaseProtocolFilter.CookieManager, e.g.:
var filter = new HttpBaseProtocolFilter();
var cookieManager = filter.CookieManager;
var uri = new Uri("http://api.my.com:3000");
foreach (var cookie in cookieManager.GetCookies(uri))
{
Debug.WriteLine(cookie.Name);
Debug.WriteLine(cookie.Value);
}
Notice, if the cookies are already in the HttpCookieContainer, the cookies will be automatically added in the next requests to http://api.my.com:3000, and no action is required from your side.
If you want to modify them or delete them, the HttpCookieContainer has methods to do that.
Take a look at Flurl. It presents a fluent interface over the Http bits, so you can say something like this to authenticate and reuse the connection with the cookies:
using (var fc = new FlurlClient().EnableCookies())
{
var url = new Url( "http://api.com/endpoint" ) ;
await url
.AppendPathSegment("login")
.WithClient(fc)
.PostUrlEncodedAsync(new { user = "user", pass = "pass" });
var page = await url
.AppendPathSegment("home")
.WithClient(fc)
.GetStringAsync();
// Need to inspect the cookies? FlurlClient exposes them as a dictionary.
var sessionId = fc.Cookies["session_id"].Value;
}
Hi guys I'm having trouble fetching products from amazon web api.
I have used this code from the internet, adding all the neccessary references. I tried adding a view and chose itemsearchresponce as the model class but it does not display the product, I get the following error:
Unable to generate a temporary class (result=1).
error CS0029: Cannot implicitly convert type 'AmazonProduct.com.amazon.webservices.ImageSet' to
'AmazonProduct.com.amazon.webservices.ImageSet[]'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AmazonProduct.com.amazon.webservices;
namespace Forest.Controllers
{
public class AmazonController : Controller
{
private AmazonProduct.com.amazon.webservices.AWSECommerceService _Products;
public AmazonController()
{
_Products = new AmazonProduct.com.amazon.webservices.AWSECommerceService();
}
[HttpGet]
public ActionResult listProducts()
{
var searchIndex = "Shoes";
var keywords = "jordan";
// Create an ItemSearch wrapper
ItemSearch search = new ItemSearch();
search.AssociateTag = "[Your Associate ID]";
search.AWSAccessKeyId = "MyKey";
// search.Version= "2011-08-01";
// Create a request object
ItemSearchRequest request = new ItemSearchRequest();
// Fill the request object with request parameters
request.ResponseGroup = new string[] { "ItemAttributes" };
// Set SearchIndex and Keywords
request.SearchIndex = searchIndex;
request.Keywords = keywords;
// Set the request on the search wrapper
search.Request = new ItemSearchRequest[] { request };
ItemSearchResponse response = _Products.ItemSearch(search);
return View(response);
}
}
}
Go to the generated proxy and replace ImageSet[][] with ImageSet[].
Also take a look at Amazon Product Advertising API C# if you already haven't.
I'm trying to write an online application to access my google analytics data using a google service account. Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GA_server2server_POC.Models
{
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Util;
using Google.Apis.Services;
using Google.Apis.Requests;
public class Oauth_With_API
{
public static void ApiTest()
{
log4net.Config.XmlConfigurator.Configure();
const string ServiceAccountId = "xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
const string ServiceAccountUser = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdeveloper.gserviceaccount.com";
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, new X509Certificate2("C:\\Users\\rcarter\\Downloads\\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
{
Scope = "https://www.googleapis.com/auth/analytics.readonly",
ServiceAccountId = ServiceAccountUser
};
OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
{
Authenticator = authenticator
});
string profileId = "ga:xxxxxxxx";
string startDate = "2013-07-01";
string endDate = "2013-07-15";
string metrics = "ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
request.Dimensions = "ga:date";
GaData data = request.Execute(); //error occurs here. After this, thread exits.
Console.WriteLine(data.TotalResults);
}
}
}
So far my code executes, but I get the following output:
WebDev.WebServer40.exe Information: 0 : DotNetOpenAuth, Version=4.0.0.11165, Culture=neutral, PublicKeyToken=2780ccd10d57b246 (official)
WebDev.WebServer40.exe Information: 0 : Preparing to send AssertionFlowMessage (2.0) message.
WebDev.WebServer40.exe Information: 0 : Sending AssertionFlowMessage request.
WebDev.WebServer40.exe Information: 0 : HTTP POST https://accounts.google.com/o/oauth2/token
WebDev.WebServer40.exe Information: 0 : The following required parameters were missing from the DotNetOpenAuth.OAuth2.Messages.AccessTokenFailedResponse message: {error,
}
WebDev.WebServer40.exe Information: 0 : Received UnauthorizedResponse response.
After this, the thread exits, and the program refuses to print any of the data. The trouble seems to occur at request.Execute();. The part that I find especially confusing, is that if I put a breakpoint on Console.WriteLine(data.TotalResults);, I can see the data I want in the local variable data. It contains everything I want to print, but I can't identify the cause of the error keeping it from doing anything after request.Execute();. After much searching, I haven't found much at all about the error listed above.
The code I'm using is based on the answer given to this question here. A few things have changed in the google analytics libraries since that question was answered, but much of my code is the same.
I've checked and re-checked all the account-specific variables. To test this, I'm running it on my local machine as a ASP.NET MVC 4 Web App.
Any help or advice on how to troubleshoot this issue is appreciated. Please let me know if I can provide more information which might help. Thanks for reading.
Try following one
using System.Security.Cryptography.X509Certificates;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Services;
private void TestMethod()
{
try
{
string scope_url = "https://www.googleapis.com/auth/analytics.readonly";
//client_id: This is the "Email Address" one, not the "Client ID" one... oddly...
string client_id = "************-***********************#developer.gserviceaccount.com";
//key_file: This is the physical path to the key file you downloaded when you created your Service Account
string key_file = #"***************************************-privatekey.p12";
//key_pass: This is probably the password for all key files, but if you're given a different one, use that.
string key_pass = "notasecret";
AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;
//key: Load up and decrypt the key
X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable);
//client: we're using the AssertionFlowClient, because we're logging in with our certificate
AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope_url };
OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
//gas: An instance of the AnalyticsService we can query
// AnalyticsService gas = null;// new AnalyticsService(auth);
var gas = new AnalyticsService(new BaseClientService.Initializer()
{
Authenticator = auth
});
//r: Creating our query
DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:*******", "2012-09-26", "2012-10-10", "ga:visitors");
//d: Execute and fetch the results of our query
GaData d = r.Fetch();
}
catch (Exception ex)
{
throw;
}
}