using SendGrid email service with the Azure SDK - sendgrid

I'm building an email service into my app, has anyone any experience using it with the Azure SDK to test it locally ? or is it only possible in an actual azure app ?

or is it only possible in an actual azure app ?
We could use SendGrid email service both for local and azure app. We could get more detail steps from Azure official tutorials. The following is my test demo code
var apiKey ="ApiKey";//System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("x#example.com", "Send Grid"),
Subject = "Hello World from the SendGrid CSharp SDK!",
PlainTextContent = "Hello, Email!",
HtmlContent = "<strong>Hello, Email!</strong>"
};
msg.AddTo(new EmailAddress("y#example.com", "Test User"));
client.SendEmailAsync(msg).Wait();

Related

DevOps : Non-Interactive login in new DevOps(VSTS) not working getting error 'TF30063: You are not authorized to access

I am trying to connect to Azure DevOps previously known as VSTS using c#. I want to connect to it without the login screen of azure DevOps. I am currently trying the following code but some how it is not working
NetworkCredential netCred = new NetworkCredential("test#hotmail.com", "test");
Uri tfsuri = new Uri("https://dev.azure.com/test10");
VssBasicCredential bsCred = new VssBasicCredential(netCred);
VssCredentials vssCred = new VssClientCredentials(bsCred);
TfsTeamProjectCollection collection = new TfsTeamProjectCollection(tfsuri, vssCred);
collection.Authenticate();
var witClient = collection.GetClient<ProjectHttpClient>();
var listOfProjects = witClient.GetProjects().Result;
libraries I am using
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Operations;
using Microsoft.VisualStudio.Services.WebApi;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi;
The code prompts a login screen, on which if I enter the password the auth still does not work. I dont want the login screen to appear and only want to connect with the username and password.
With alternate credentials this method is working but it is not my requirement and I can not use alternate credentials.
I have tried following the samples from the official site but no solution is working for the new DevOps.
Any Solution how can I authenticate with usernanme/password in the new DevOps without the login screen
The class TfsTeamProjectCollection is from the old .Net libraries, try the new Azure DevOps .Net libraries, and you can authenticate in a few ways:
NTLM
The most basic one is constructing a VssCredentials instance with no parameter at all and what you’ll be using is simply put integrated authentication / NTLM:
var visualStudioServicesConnection = new VssConnection(new Uri(baseUri), new VssCredentials());
Basic Authentication
VSTS and TFS also provide means to utilize Basic authentication (HTTP AUTH) which you need to create and enable first (see VSTS guidelines) and once you’ve done so, you can use them via the API like this:
var visualStudioServicesConnection = new VssConnection(new Uri(baseUri), new VssBasicCredential(username, password));
Personal Access Tokens
Next up are Personal Access Tokens (PAT) which you can easily create following the VSTS guidelines and those PATs are a means of authenticating separately from your actual credentials with a fine-grained & per access token scopes of security. Simply put it allows you to create a PAT for every use-case or even application and thereby enabling a secure and clearly separated way of giving an application or 3rd party access to your VSTS or TFS system on your behalf.
To use these via the API, you use the exact same mechanism as via Basic Authentication but you simply don’t provide any username (well – an empty one to be precise), and the PAT itself is used as the password:
var visualStudioServicesConnection = new VssConnection(new Uri(baseUri), new VssBasicCredential(string.Empty, pat));
Visual Studio Sign-in Prompt
Moreover, another way of authenticating is using the standard VS Sign-In prompt which is similarly easy and exposed via the VssClientCredentials class:
var visualStudioServicesConnection = new VssConnection(new Uri(baseUri), new VssClientCredentials());
OAuth Authentication
OAuth is a widely used but a slightly more tedious authorization protocol to implement but luckily there’s a thorough sample application available at CodePlex specifically for VSTS / VSO (which also works for on-premises).
Once you have the corresponding access token, you can use it to VSTS / TFS utilizing the VssOAuthCredential class:
var visualStudioServicesConnection = new VssConnection(new Uri(baseUri), new VssOAuthCredential(accessToken));
Azure Active Directory Authentication
Last but not least you can utilize Azure Active Directory identities to authenticate against a VSTS or TFS system via the VssAadCredential class:
var visualStudioServicesConnection = new VssConnection(new Uri(baseUri), new VssAadCredential(username, password));

Send an email on Sails.JS using Mailgun?

I'm trying to send an email on Sails.JS but I don't know how to do it. I saw a lot of tutorials but none of the tutorials helped me to send an email. I can send an email with the console using curl.
I tried to configure Mailgun but I don't have a Domain. I'm trying to do it free and I'm also very new on Mailgun and Sails.JS. My purpose is to send an email on Sails.JS, but I don't know how.
Follow the steps below to send email from sailsjs using mailgun
Install mailgun module
npm install mailgun-js --save
Create custom variables in config/custom.js file
mailgunDomain: 'yourmailgundomain',
mailgunSecret: 'yourmailgunkey',
mailgunFrom:'yourmailgunfrommail',
Create a helper
sails generate helper send-single-email
var mailgun = require('mailgun-js')({apiKey: sails.config.custom.mailgunSecret, domain: sails.config.custom.mailgunDomain});
module.exports = {
friendlyName: 'Send single email',
description: '',
inputs: {
options:{
type:'json'
}
},
exits: {
},
fn: async function (inputs, exits) {
mailgun.messages().send(inputs.options, function (error, body) {
if(error){
return exits.error(error)
}
// All done.
return exits.success(body);
});
}
};
Call your helper from any controller
await sails.helpers.mail.sendSingleEmail({
to:'destination#email.com',
from:sails.config.custom.mailgunFrom,
subject:'Subject',
text:'Your message'
})
To use Mailgun, you'll need to sign up for an account. (While this is a paid service at higher usage levels, you should be able to use Mailgun as much as you need to in development without having to provide any credit card information.)
After you've created an account, you'll need to add your Mailgun domain and API secret to your custom config. (In development, this will be either in config/custom.js, or in a local.js file you add to your config/ folder. For your staging or production deployment, you'll want to set these using system environment variables -- aka "config variables" in Heroku.)
If you already own a domain for your app, you can follow Mailgun's instructions for configuring a sending domain.
Otherwise, to send emails from this app without configuring a sending domain, you can use the sandbox domain & test API secret that comes with your Mailgun account. Just be sure to configure the authorized recipents for your sandbox domain first, or there will be errors from the endpoints that attempt to send emails.
~~Copied from Sails.js FAQ page when downloading a new app

azure sdk for net login is takes too long

I am using Fluent Library to develop a web app which can create a sql server on azure. The console app works great but when I implement the code to a web api it stuck in authentication step. I'm sure about the credentials which are true and I have a Service Principal.
// Authenticate
var credentials = new AzureCredentials(new ServicePrincipalLoginInformation { ClientId = ClientId, ClientSecret = Password }, tenantId, AzureEnvironment.AzureGlobalCloud);
var azure = Azure.Configure().Authenticate(credentials).WithDefaultSubscription();
I also can repro it on my side. I try to debug it with following code and add quick watch for azureauth.WithDefaultSubscription(), then get value The function evaluation requires all threads to run. So I guess that it may run some threads that WebAPI can't handle.
var azureauth = Azure.Configure().Authenticate(credentials);
azureauth.WithDefaultSubscription()
Please have a try to use following code to use specified subscriptionId as workaround. It works correctly on my side.
var azure = Azure.Configure().Authenticate(credentials).WithSubscription("subscriptionId");

How to set up different azure sendgrid accounts for different environments?

We are using azure for publishing our application and we are having three different web apps for dev, stage and prod.
By referring the below link
https://azure.microsoft.com/en-us/documentation/articles/sendgrid-dotnet-how-to-send-email/
We configured the sendgrid account in azure and we are able to send email without any issue in all three environments dev, stag and prod.
Note: We are using same sendgrid account for dev, stage and prod.
Issue:
Now, for tracking and billing purpose we decided to use different sendgrid accounts for dev, stag and prod. i.e.,
Azure SendGrid account 1 - dev
Azure SendGrid account 2 - stag
Azure SendGrid account 3 - prod
But we don't know how to accomplish via azure portal and when we tried it's not allowing.
Please, suggest some steps or links to accomplish this so that we can plan out for release. Thanks in advance
SendGrid supports subusers, so you could have your parent account and two or three subusers depending on if you wanted to send via the parent account as well. You can read about subusers on the SendGrid docs. Let me know if you have any questions.
About halfway down in the article you provided a link for you'll see:
and
You could add more app settings such as:
SENDGRID_DEV_APIKEY, SENDGRID_STAGE_APIKEY, SENDGRID_PROD_APIKEY
Then in your code check what environment the code is running and use the appropriate app setting/api key.
var apiKey = "";
//GetCurrentEnvironment() is a method you would write that contains logic to determine what "environment" is being used.
if (GetCurrentEnvironment() == "dev") {
apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_DEV_APIKEY");
} else if (GetCurrentEnvironment() == "stage") {
apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_STAGE_APIKEY");
} else if (GetCurrentEnvironment() == "prod") {
apiKey = System.Environment.GetEnvironmentVariable("SENDGRID_PROD_APIKEY");
}
var transportWeb = new Web(apiKey);

Error consuming customerLicense App Marketplace with Service Account OAuth2

SOLUTION
I figured out how to solve this problem.
First of all here is my implementation with Service Account:
// Build service account credential.
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/appsmarketplace.license"))
.setServiceAccountPrivateKeyFromP12File(new File("/path/to/mykey/key.p12"))
// .setServiceAccountUser("NOT SET THIS LINE")
.build();
License build = new License.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("My Application").build();
Licenses execute = build.customerLicense().get("9999999999", "domain.test.com").execute();
This License Builder object is myself implementation based on the new google-api-client 1.17 and above. If someone could advice me how can i share with the rest of the community i will be glad to do it.
Best,
I have posted another thread, Google Apps Marketplace API customerLicense with OAuth2, explaining about my intentions to consume this API with OAuth2 Service Account strategy.
I have tried every method and officials library present and I always get Invalid OAuth header message or UNLICENSED
I am going to detail what is the scenery and what things i have tried:
I have and Google App Marketplace which use Service Account OAuth2 because all task are being perform on background.
This API Project has Service Account keys and Client Web Account keys too.
I published app restricted for my domain only because i am yet developing. So I installed App for my domain.
At this point it is suppose if I queried Customer License with API Project ID and Customer Id, which is domain name, I have to see the APP LICENSE for my domain.
I have used this jars https://developers.google.com/google-apps/marketplace/v2/developers_guide to access License API.
This is my code:
String appName = "MY APP";
AppsMarketService service = new AppsMarketService();
service.appId = "NUMBER_APP_ID";
service.appName = appName;
service.endpoint = "https://www.googleapis.com/appsmarket/v2/";
service.consumerKey = service.appId + ".apps.googleusercontent.com";
service.consumerSecret = "CLIENT_SECRET_FROM_WEB_OAUTH2_API_PROJECT";
service.authorize();
I get 403 forbidden if i use this code.
If i changed appId for prefix clientId from my API Project web OAuth2, I get 200 but with body UNLICENSED.
I have added scope to my app https://www.googleapis.com/auth/appsmarketplace.license and i still get the same result.
I have tried also getting Access Token from Admin user with Service Account handshake and then use that Oauth2 Access Token to access API License and the same result Invalid OAuth Token
My questions are:
Is there any way to access this API with Services Account keys, taking into consideration there is not consumer Secret in Service Accounts keys, only Client ID and private Key file?
Is there any updated library to use this with OAuth2 because i am seeing all this libraries are using OAuth1 with two-legged auth?
It would be great if someone can help me because we are trying to migrate our 7 Google App Old Marketplace Apps from OAuth1 to OAuth2 as per Google request but we have some black holes in our implementation if we would not be able to query what domains have our App Installed.
Best,
There is no need for any other libraries than OAuth2 lib. You can impmement this using urlfetch.
...
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.appengine.api.urlfetch.FetchOptions.Builder;
import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
...
String SERVICE_ACCOUNT_EMAIL = "...#developer.gserviceaccount.com";
String P12 = "...-privatekey.p12";
// appid is the same id that you have in the google cloud project that has the Google Apps Marketplace API and SDK enabled
String appid = "";
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(new NetHttpTransport())
.setJsonFactory(new JacksonFactory())
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton("https://www.googleapis.com/auth/appsmarketplace.license"))
.setServiceAccountPrivateKeyFromP12File(new File(P12))
.build();
credential.refreshToken();
String token = credential.getAccessToken();
URL url = new URL("https://www.googleapis.com/appsmarket/v2/licenseNotification/"+appid);
HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, Builder.allowTruncate());
request.setHeader(new HTTPHeader("Authorization", "Bearer "+token));
HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
You need to install the OAuth2 package for this to work. In eclipse its under Google > Add Google Apis.