SendGrid V3 api with C# not able to send mail from Console Application - console-application

I am not able to send email with SendGrid using the V3 API in a console application. It works fine in my Web Application. I created a test console project and used the sample code from the SendGrid site. When the command to send the message is called, the application simply exits. I cannot read any response from the call.
This is in VB.Net. Sorry, I think I am the only person on Earth who codes in VB.
If I execute this code in the sample sendgrid-csharp-main from GitHub, it works fine. I cannot find anything in the sample code that looks any different from my code in the section that actually calls the send message part (other than having to convert to VB).
Does anyone see ANYTHING wrong in this code? I am using the .Net 4.7.2 framework.
This is the entirety of the test code. I have been spinning my wheels searching for help for too long and I am desperate now.
Imports System.Net.Http
Imports SendGrid
Imports SendGrid.Helpers.Mail
Module Module1
Sub Main()
TryIt().ConfigureAwait(True)
End Sub
Private Async Function TryIt() As Task
Dim HttpClient As HttpClient = New HttpClient()
Dim apiKey = "my private api key"
Dim client = New SendGridClient(HttpClient, New SendGridClientOptions With {
.ApiKey = apiKey,
.HttpErrorAsException = True
})
Dim from = New EmailAddress("msie#msinvoiceExchange.com", "MSIE")
Dim subject = "Hello World from the Twilio SendGrid CSharp Library Helper!"
Dim toEmail = New EmailAddress("joe#invoicesanywhere.com", "Joe")
Dim plainTextContent = "Hello, Email from the helper [SendSingleEmailAsync]!"
Dim htmlContent = "<strong>Hello, Email from the helper! [SendSingleEmailAsync]</strong>"
Dim msg As New SendGridMessage With {
.From = from,
.Subject = subject,
.PlainTextContent = plainTextContent,
.HtmlContent = htmlContent
}
msg.AddTo(toEmail)
Dim myResponse As Response
myResponse = Await client.SendEmailAsync(msg)
Console.WriteLine(msg.Serialize())
Console.WriteLine(myResponse.StatusCode)
Console.WriteLine(myResponse.Headers)
Console.WriteLine(vbLf & vbLf & "Press <Enter> to continue.")
Console.ReadLine()
End Function
End Module

It figures. As soon as I get desperate enough to post a question, I figure out something that works.
I just hope that someone else has the same problem and finds this answer helpful.
This is the change I had to make to get this to work
Sub Main()
TryIt().Wait()
End Sub

Related

Rally Web Services API: How do I get the URL link of the user story? (getDetailUrl() method)

Please be patient and Do Not flag this as duplicate: Using the Rally REST API, how can I get the non-API (website) URL for a user story?
I want to be able to generate a link for the user story.
Something like this: https://rally1.rallydev.com/#/-/detail/userstory/*********
As opposed to this: https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement/88502329352
The link will be integrated into another application for the managers to see the user story.
I did read about the getDetailUrl() method, but in my case I am creating the user stories by parsing email and linking that to a notification service in Slack.
I am aware of the formattedID and (_ref), but I would have to query for it again, and I am creating batches of userstories through a loop. I need the actual web site link to the user story.
Here is my sample code:
public void CreateUserStory(string workspace, string project, string userstoryName){
//authenticate with Rally
this.EnsureRallyIsAuthenticated();
//DynamicJsonObject for HierarchicalRequirement
DynamicJsonObject toCreate = new DynamicJsonObject();
toCreate[RallyConstant.WorkSpace] = workspace;
toCreate[RallyConstant.Project] = project;
toCreate[RallyConstant.Name] = userstoryName;
try
{
//Create the User Story Here
CreateResult createUserStory = _api.Create(RallyConstant.HierarchicalRequirement, toCreate);
Console.WriteLine("Created Userstory: " + "URL LINK GOES HERE");
}
catch (WebException e)
{
Console.WriteLine(e.Message);
}
}
We don't have a method in the .NET toolkit for doing this, but it's easy to create.
The format is this:
https://rally1.rallydev.com/#/detail/<type>/<objectid>
Just fill in the type (hierarchicalrequirement turns into userstory, but all the others are the same as the wsapi type) and the objectid from the object you just created.
var parameters = new NameValueCollection();
parameters["fetch"] = "FormattedID";
var toCreate = new DynamicJsonObject();
var createResult = restApi.create("hierarchicalrequirement", toCreate, parameters);
var type = Ref.getTypeFromRef(createResult.Reference);
var objectID = Ref.getOidFromRef(createResult.Reference);
var formattedID = createResult.Object["FormattedID"];
And you can specify fetch fields to be returned on the created object so you don't have to re-query for it.

Unit Testing - dependency injection zf2

In one of controller I have following code to send email and sms using dependency injection. which works fine
$message = new \Application\SendMessage\Message();
$message->toName = $toName;
$message->toEmail = $toEmail;
$message->fromEmail = $fromemail;
$message->emailBodyText = $emailBodyText;
$message->smsMessage = $emailBodyText;
$message->toMobile = $toMobile;
$seSMS = new \Application\SendMessage\SendSMS($message);
$suSMS = new \Application\SendMessage\SendMessage($seSMS);
$statusMsg = $suSMS->releaseMsg();
$seEmail = new \Application\SendMessage\SendEmail($message);
$suEmail = new \Application\SendMessage\SendMessage($seEmail);
$statusMsgEmail = $suEmail->releaseMsg();
and I am testing it, using following code
public function testcreateActionCanBeAccessed()
{
$postData = array(
// variables here
);
$this->dispatch('/mycontroller/myaction', 'POST', $postData);
$this->assertResponseStatusCode(200);
}
Which works fine and give me 100 percent code coverage, Only problem is, every time I run unit test, it sends the email and release the sms text message as well. which is good sometimes, as it also tests email sending and text messaging feature.
But if you have to run your test again and again it is kind of annoying, How can I mock above code so it will still give me 100 percent code coverage but will not send sms text and email.
One way would be to utilize the "Service Locator Pattern" http://en.wikipedia.org/wiki/Service_locator_pattern
Instead of:
$message = new \Application\SendMessage\Message();
You would have something like:
$message = $service_locator->new('Application\SendMessage\Message');
In your test, you could then utilize mocking (http://phpunit.de/manual/3.7/en/test-doubles.html) to return "dummy" messages/sendmessages that don't actually send an email, but still ensure the proper methods get called.

Unable to access WMI on remote machine using vb.net

I've had a scout around and can't seem to find the answer anywhere, so need to ask.
I'm trying to query the WMI on a remote machine, but I need to do so as the admin account and I'm having problems doing so.
The code I am using is:
Public Sub OperatingSystem(ByVal computeritem As String)
'set Username and Password which system will access the network with.
Dim options As ConnectionOptions
options = New ConnectionOptions()
options.Authority = "ntdlmdomain:" & ipaddress
options.Username = "Username"
options.Password = "Password"
scope = New ManagementScope("\\" & ipaddress & "\root\cimv2", options)
scope.Connect()
Dim query As ObjectQuery
query = New ObjectQuery("SELECT * FROM Win32_OperatingSystem")
Dim searcher As ManagementObjectSearcher
searcher = New ManagementObjectSearcher(scope, query)
the query continues to go and pull all kinds of information through to a spradsheet.. well it would if it worked!
The line of code that is falling over is:
scope = New ManagementScope("\\" & ipaddress & "\root\cimv2", options)
scope.Connect()
It's giving me an error message that just says 'Invalid parameter'. When I go to view detail, there's nothing in inner exception and the only thing that I can see of any value is ErrorCode:ManagementStatus.InvalidParameter
I apologize if this is something really simple.. I am still fairly new to this but if someone could give me some guidance that would really be appreciated.
Many Thanks.
It looks like the reference to ipaddress is not initialized. Since computeritem is passed as a parameter to the sub, your code might work better with:
scope = New ManagementScope("\\" & computeritem & "\root\cimv2", options)

Salesforce - Data type for webservice response

Im trying to execute/consume a webservice and wondering if I am using the correct data type to return the results. String seems to work, but I receive an empty string. The service should be returning a simple string value without XML. There is a working version written in JS below, I have been asked to recreate it in Apex.
JS version (Working) - executed when a button is clicked
{!REQUIRESCRIPT("/soap/ajax/24.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/24.0/apex.js")}
var xfolder = "TestFolder"
var parentid = "22K22"
var myvar = sforce.apex.execute("myWS","invokeWs", {folderName:xfolder,ObjectID:parentid});
window.alert('LiveLink folder created: ' + myvar);
APEX version (not working)
public with sharing class myTest {
public String getWSXMLResult() {
String tmpFolderName2 = 'TestFolder';
String tmpObjectID2 = '22K22';
String myWSXMLResult = myWS.invokeWs(tmpFolderName2,tmpObjectID2);
System.debug('XIXWS|' + myWSXMLResult);
return myWSXMLResult;
}
}
One thing I just noted while typing this out. I didn't specify the argument names for invokeWs, just the values..do I need to specify those values in the call to the WS? Such as..
myWS.invokeWs(folderName=tmpFolderName2,ObjectID=tmpObjectID2); -- this errors out btw
Thanks again everyone.

Classic Asp Web Service Problem

I'm trying to create a code to allow an existing classic asp program to use an asp.net web service. Updating from the classic asp is not an option, as I'm working in a big company and things are the way they are.
I've been browsing through a chunk of tutorials supposedly helping in this, but I haven't managed to get them to work yet. As a beginner I might've made some real obvious mistakes but I just don't know what.
First, the web service is located on an external server. The method "Greeting" needs a String parameter by which it determines which String is sent back. Inputting "g" to it procudes this xml:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://server1/Logger_WebService/">Greetings and welcome!</string>
I assume the xpath for getting the contents is either "string/*" or "*"?
Next, my web service itself looks like this:
<WebMethod()> _
Public Function Greeting(ByVal stringel As String) As String
If stringel.ToLower = "g" Then
Return "Greetings and welcome!"
Else
Return "Bye then!"
End If
End Function
The web service works fine from a regular asp.net solution.
Now here's the problem, the classic asp code looks like this (4 different ways I've tried to get this to work, SOAP toolkit is installed on the web service server, all examples taken and modified from tutorials):
'******* USING GET METHOD
Dim wsurl="http://server1/Logger_WebService/service.asmx/Greeting?g"
Dim xmlhttp
Set xmlhttp=Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "GET",wsurl,false
xmlhttp.send
Dim rValue
'rValue=xmlhttp.responseXML.selectSingleNode("string") 'use XPATH as input argument
' or you can get response XML
rValue=xmlhttp.responseXML
Set xmlhttp=nothing
'------------------------------------------------------
'******* USING POST METHOD
Dim wsurl="http://server1/Logger_WebService/service.asmx/Greeting"
Dim xmlhttp
Set xmlhttp=Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "POST",wsurl,false
xmlhttp.send "stringeli=g"
Dim rValue
rValue=xmlhttp.responseXML.selectSingleNode("string")
' or you can get response XML
' rValue=xmlhttp.responseXML
Set xmlhttp=nothing
'------------------------------------------------------
Response.Write consumeWebService()
Function consumeWebService()
Dim webServiceUrl, httpReq, node, myXmlDoc
webServiceUrl = "http://server1/Logger_WebService/service.asmx/Greeting?stringel=g"
Set httpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "GET", webServiceUrl, False
httpReq.Send
Set myXmlDoc =Server.CreateObject("MSXML.DOMDocument")
myXmlDoc.load(httpReq.responseBody)
Set httpReq = Nothing
Set node = myXmlDoc.documentElement.selectSingleNode("string/*")
consumeWebService = " " & node.text
End Function
'------------------------------------------------------
Response.Write(Helou())
Public Function Helou()
SET objSoapClient = Server.CreateObject("MSSOAP.SoapClient")
objSoapClient.ClientProperty("ServerHTTPRequest") = True
' needs to be updated with the url of your Web Service WSDL and is
' followed by the Web Service name
Call objSoapClient.mssoapinit("http://server1/Logger_WebService/service.asmx?WSDL", "Service")
' use the SOAP object to call the Web Method Required
Helou = objSoapClient.Greeting("g")
End Function
I seriously have no idea why nothing works, I've tried them every which way with loads of different settings etc. One possible issue is that the web service is located on a server which in ASP.Net required me to input this "[ServiceVariableName].Credentials = System.Net.CredentialCache.DefaultCredentials". I do this from within company network, and there are some security and authorization issues.
I only need to be able to send information anyhow, not receive, as the actual method I will be using is going to insert information into a database. But for now, just getting the Hello World thingie to work seems to provide enough challenge. :)
Thx for all the help. I'll try to check back on holiday hours to check and reply to the comments, I've undoubtedly left out needed information.
Please, talk as you would to an idiot, I'm new to this so chances are I can understand better that way. :)
You might consider writing a bit of .NET wrapper code to consume the web service. Then expose the .NET code as a COM object that the ASP can call directly. As you've seen, there is no tooling to help you in classic ASP, so consider using as much .NET as possible, for the tooling. Then, use COM to interoperate between the two.
A colleague finally got it working after putting a whole day into it. It was decided that it's easier by far to send information than it is to receive it. Since the eventual purpose of the web service is to write data to the DB and not get any message back, we attempted the thing by simply writing a file in the web service.
The following changes were needed:
First, in order to get it to work through the company networks, anonymous access had to be enabled in IIS.
The web service needed the following change in the web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
And the web service code-behind was changed like so:
<WebMethod()> _
Public Function Greeting(ByVal stringel As String) As String
Dim kirj As StreamWriter
'kirj = File.CreateText("\\server1\MyDir\Logger_WebService\test.txt")
'if run locally, the line above would need to be used, otherwise the one below
kirj = File.CreateText("C:\Inetpub\serverroot\MyDir\Logger_WebService\test.txt")
kirj.WriteLine(stringel)
kirj.Close()
kirj.Dispose()
Return stringel
End Function
As we got the above to work, it was a simple matter of applying the same to the big web method that would parse and check the info and insert it into the database.
The classic asp code itself that needs to be added to the old page, which was the biggest problem, turned out to be relatively simple in the end.
function works()
message = "http://server1/mydir/logger_webservice/service.asmx/Greeting?" & _
"stringel=" & "it works"
Set objRequest = Server.createobject("MSXML2.XMLHTTP")
With objRequest
.open "GET", message, False
.setRequestHeader "Content-Type", "text/xml"
.send
End With
works = objRequest.responseText
end function
works()
Took about a week's worth of work to get this solved. :/ The hardest part was simply not ever knowing what was wrong at any one time.
You might be missing the SOAPAction header. Here's a working example:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class GreetingService : WebService
{
[WebMethod]
public string Greet(string name)
{
return string.Format("Hello {0}", name);
}
}
And the calling VBS script:
Dim SoapRequest
Set SoapRequest = CreateObject("MSXML2.XMLHTTP")
Dim myXML
Set myXML = CreateObject("MSXML.DOMDocument")
myXML.Async=False
SoapRequest.Open "POST", "http://localhost:4625/GreetingService.asmx", False
SoapRequest.setRequestHeader "Content-Type","text/xml;charset=utf-8"
SoapRequest.setRequestHeader "SOAPAction", """http://tempuri.org/Greet"""
Dim DataToSend
DataToSend= _
"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/"">" & _
"<soapenv:Header/>" & _
"<soapenv:Body>" & _
"<tem:Greet>" & _
"<tem:name>John</tem:name>" & _
"</tem:Greet>" & _
"</soapenv:Body>" & _
"</soapenv:Envelope>"
SoapRequest.Send DataToSend
If myXML.load(SoapRequest.responseXML) Then
Dim Node
Set Node = myXML.documentElement.selectSingleNode("//GreetResult")
msgbox Node.Text
Set Node = Nothing
End If
Set SoapRequest = Nothing
Set myXML = Nothing
Might want to double-check the version of the MSXML components. Are you using Windows Authentication? I've noticed some odd XML parsing problems with IIS 7, Classic ASP, and MSXML.
It would also help to get a useful error. Check the ** myXML.parseError.errorCode** and if its not 0 write out the error.
Reference Code:
If (myXML.parseError.errorCode <> 0) then
Response.Write "XML error: " & myXML.parseError.reason
Else
'no error, do whatever here
End If
'You get the idea...