SendGrid 'DeliverAsync()' Not Working - api

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.

Related

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

C#, RestSharp, Type or Namespace name "HttpBasicAuthenticator" could not be found

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using RestSharp;
namespace ConsoleProgram
{
public class TryingOutRest {
public resttest Execute<resttest>(RestRequest request) where resttest : new() {
var client = new RestClient();
client.BaseUrl = new Uri("http://www.ocrwebservice.com");
client.Authenticator = new HttpBasicAuthenticator("apid", "apikey");
// the key and and id are put in as a string, but i removed them for the purposes of this.
var re_quest = new RestRequest();
re_quest.Resource = "/restservices/processDocument";
var response = client.Execute<resttest>(request);
}
}
}
So, hi, trying to get to grips with Rest api, Currently doing a project involving it and OCR, as you can probably tell. Tried this, i thought it would work fine, but I seem to have messed up dearly or some naming has changed and i cant find anything relevant in the autofill menu.
Anyone got any idea what's happening?
P.s. if questions about install, i used NuGet for that, so i assume there'd be no problem.
Try
using RestSharp.Authenticators;
This seems to be the namespace for HttpBasicAuthenticator now. (Github)
Open Nugetpackage manager and install RestSharp
Then you can use
using RestSharp.Authenticators

REST API (JSON) that updates SQL Table using Windows Console Application and Scheduled Tasks

I am a newbie at JSON programming. Most of my experience is in C# and some in XML and Javascript. So I am a bit lost. I will attempt to be as specific as possible.
I have written a windows console application that runs via the task scheduler. Basically the windows application is supposed to take the API from a site that is managed by an outside company but the information is owned by my company and put the information within a SQL table. The API is pretty standard and written in JSON.
I am successful in parsing the JSON language and (for example) displaying it in a command prompt but I need to be able to parse the language and place it into an SQL table. I have read up on SQL injection attacks and I feel fairly confident that we have covered our bases here. So the problem lies in the fact that it does not update the table when the application is run via the scheduler or without the scheduler.
I have included a little bit of the JSON language below along with the language for my console application.
{"date":"2015-09-24","data":[{"cid":"17","rank":1},{"cid":"26","rank":1},{"cid":"80","rank":1},{"cid":"30","rank":1},{"cid":"90","rank":1},{"cid":"62","rank":1},{"cid":"147","rank":1},{"cid":"28","rank":1}"s":1,"e":null}
using System;
using System.Collections;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JsonApiClient
{
class Program
{
static void Main(string[] args)
{
ExecuteRiskSearch();
Console.ReadLine();
}
static void ExecuteRiskSearch()
{
string url = "https://localhost/api/getWatchList/";
string json = new WebClient().DownloadString(url);
JObject results = JObject.Parse(json);
foreach (var result in results)
{
string cid = (string)results["CID"];
JToken rank = results["rank"];
string risk = "";
if (rank is JValue)
{
risk = (string)rank;
}
else if (rank is JArray)
{
risk = (string)((JArray)rank).First;
}
else
{
SqlConnection connection = null;
SqlCommand command = null;
try
{
connection = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=apiData;Data Source=serverName;");
command = new SqlCommand("UPDATE apiData.dbo.API SET [Category] WHERE CID=CID", connection);
connection.Open();
int numrows = command.ExecuteNonQuery();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
finally
{
command.Dispose();
connection.Dispose();
}
}
}
}
}
}
What am I missing to make the JSON data update my SQL table? I have scoured Google search results and I haven't found much information. Any help would be so greatly appreciated.
For the need to foreach with the correct part of the JSON object, what I mean is very simply that your variable results includes the entire JSON object, from the "date" through the "e". You need to start with the "data" object and iterate through its array or your string cid will error out on assignment, as it will be attempting to assign an array to a single value. The same goes for your JToken rank. I believe it should be this:
foreach(datum in results["data"])
{
string cid = datum["cid"];
JToken rank = datum["rank"];
/* ... */
}
In addition, your set command isn't doing anything. You need to use SET columName = " + newValue + " WHERE CID == " + cid to actually affect a change, where columnName is the column you wish to alter and newValue is your C# variable carrying the desired replacement.
It's also a best practice to include a change to an updated date field when updating via an automated process, if there is one present. Generally the convention is to have a created date and an updated date for each row in a table.
I hope this at least points you in the right direction.
-C§
As an alternative, you can send entire text to Sql Server and load it there.
Sql Server 2016 will enable you to store JSON using single command - OPENJSON. In the older versions you can use existing CLR/JSON libraries such as Json4Sql or JsonSelect.

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.

Using SMO Library in SSIS 2008

Good afternoon,
Im having some trouble writing a simple script using SMO objects in C# to validate if an object exists and then create it. This code is within a Script Task Component in SSIS. The code executes successfully, however the new database does not show up on my local instance. Any help would be greatly appreciated.
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Collections;
using System.Data.SqlClient;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
public void Main()
{
//String DBName = Dts.Variables["TmpViewDBName"].Value.ToString();
//String Instance = Dts.Variables["TmpViewDBInstance"].Value.ToString();
String DBName = "localhost";
String Instance = "TmpViewDB";
Server TmpViewServer = new Server(Instance);
//Windows Auth
TmpViewServer.ConnectionContext.LoginSecure = true;
TmpViewServer.ConnectionContext.Connect();
if (TmpViewServer.Databases[DBName] != null)
{
TmpViewServer.Databases[DBName].Drop();
}
Database TmpViewDB = new Database(TmpViewServer, DBName);
if (TmpViewServer.ConnectionContext.IsOpen)
TmpViewServer.ConnectionContext.Disconnect();
Dts.TaskResult = (int)ScriptResults.Success;
}
I believe you need to add a line to actually create the object. As it stands now, you've only instantiated the object but never actually made the call to the database to create the remote object.
Database TmpViewDB = new Database(TmpViewServer, DBName);
TmpViewDB.Create();