Starting on web api ( can't locate namespace for HttpClient) - web-services

I'm starting to work with web api and i'm struggling to build my sample program. I get a compile error "The type or namespace name 'HttpClient' could not be found".
static void Main(string[] args)
{
var uri = "https://raw.github.com/AlexZeitler/HttpClient/master/README.md";
var httpClient = new System.Net.htt HttpClient();
httpClient.GetStringAsync(uri).ContinueWith(
t => Console.WriteLine(t.Result));
Console.ReadLine();
}
I have referenced the namespace Sytem.Net.Http but that does not seem to help.
I wonder if someone can tell me what i'm missing.
Thank is advance
B

You need to install this Nuget Package
http://www.nuget.org/packages/Microsoft.Net.Http/

Related

AWS .Net Core SDK Simple Email Service Suppression List Not Working

I am trying to retrieve the SES account-level suppression list using AWS SDK in .Net Core:
Below is my code:
public class SimpleEmailServiceUtility : ISimpleEmailServiceUtility
{
private readonly IAmazonSimpleEmailServiceV2 _client;
public SimpleEmailServiceUtility(IAmazonSimpleEmailServiceV2 client)
{
_client = client;
}
public async Task<ListSuppressedDestinationsResponse> GetSuppressionList()
{
ListSuppressedDestinationsRequest request = new ListSuppressedDestinationsRequest();
request.PageSize = 10;
ListSuppressedDestinationsResponse response = new ListSuppressedDestinationsResponse();
try
{
response = await _client.ListSuppressedDestinationsAsync(request);
}
catch (Exception ex)
{
Console.WriteLine("ListSuppressedDestinationsAsync failed with exception: " + ex.Message);
}
return response;
}
}
But it doesn't seem to be working. The request takes too long and then returns empty response or below error if I remove try/catch:
An unhandled exception occurred while processing the request.
TaskCanceledException: A task was canceled.
System.Threading.Tasks.TaskCompletionSourceWithCancellation<T>.WaitWithCancellationAsync(CancellationToken cancellationToken)
TimeoutException: A task was canceled.
Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken)
Can anyone please guide if I am missing something?
Thank you!
I have tested your code and everything works correctly.
using Amazon;
using Amazon.SimpleEmailV2;
using Amazon.SimpleEmailV2.Model;
internal class Program
{
private async static Task Main(string[] args)
{
var client = new AmazonSimpleEmailServiceV2Client("accessKeyId", "secrectAccessKey", RegionEndpoint.USEast1);
var utility = new SimpleEmailServiceUtility(client);
var result = await utility.GetSuppressionList();
}
}
<PackageReference Include="AWSSDK.SimpleEmailV2" Version="3.7.1.127" />
Things that you can check:
Try again, maybe it was a temporary problem.
Try with the latest version that I am using(if not already)
How far are you from the region that you try to get the list? Try making the same request from an EC2 instance in that region.
Finally found the issue, I was using awsConfig.DefaultClientConfig.UseHttp = true;' in startup` which was causing the issue. Removing it fixed the issue and everything seems to be working fine now.

Send and Receive sms through Java in RingCentral

I am quite new to the ringcentral APIs and currently going through all of them.
Currently going through the following reference: https://developers.ringcentral.com/api-reference/SMS/createSMSMessage
Through Java we can use an API to send SMS, but can we receive a SMS using Java.
Can someone help me in getting the documentation/article or any kind of reference where I can get to know the simple way to send and receive the SMS using Java
A sample send SMS example with Java as follows:
import java.io.IOException;
import com.ringcentral.*;
import com.ringcentral.definitions.*;
public class Send_SMS {
String RECIPIENT_NUMBER = "<ENTER PHONE NUMBER>";
String RINGCENTRAL_CLIENTID = "<ENTER CLIENT ID>";
String RINGCENTRAL_CLIENTSECRET = "<ENTER CLIENT SECRET>";
String RINGCENTRAL_USERNAME = "<YOUR ACCOUNT PHONE NUMBER>";
String RINGCENTRAL_PASSWORD = "<YOUR ACCOUNT PASSWORD>";
String RINGCENTRAL_EXTENSION = "<YOUR EXTENSION, PROBABLY ";
public static void main(String[] args) {
var obj = new Send_SMS();
try {
obj.sendSms();
} catch (RestException | IOException e) {
e.printStackTrace();
}
}
public void sendSms() throws RestException, IOException{
RestClient rc = new RestClient(RINGCENTRAL_CLIENTID, RINGCENTRAL_CLIENTSECRET, RINGCENTRAL_SERVER);
rc.authorize(RINGCENTRAL_USERNAME, RINGCENTRAL_EXTENSION, RINGCENTRAL_PASSWORD);
CreateSMSMessage postParameters = new CreateSMSMessage();
postParameters.from = new MessageStoreCallerInfoRequest().phoneNumber(RINGCENTRAL_USERNAME);
postParameters.to = new MessageStoreCallerInfoRequest[]{new MessageStoreCallerInfoRequest().phoneNumber(RECIPIENT_NUMBER)};
postParameters.text = "Hello World from Java";
var response = rc.restapi().account().extension().sms().post(postParameters);
System.out.println("SMS sent. Message status: " + response.messageStatus);
}
}
You can download the java SDK from here: https://github.com/ringcentral/ringcentral-java
and start with documentation here: https://developers.ringcentral.com/guide/messaging/quick-start/java
Once you get the library in your application, you can start compiling it and running it.
Here is a SMS Java quickstart guide: https://developers.ringcentral.com/guide/sms/quick-start/java
Hope this helps!
Here is the official RingCentral Java SDK: https://github.com/ringcentral/ringcentral-java, it is currently 1.0.0-beta9. We are going to release a stable version this month.
Here is a list of all the API calls that you can invoke: https://github.com/ringcentral/ringcentral-java/blob/master/samples.md, including sms sending: https://github.com/ringcentral/ringcentral-java/blob/master/samples.md#create-smsmms-message
For sms receiving, you can use our subscription and notification feature: https://github.com/ringcentral/ringcentral-java#pubnub-subscriptions--notificatioins
So whenever there is new sms, you will be notified, then you can issue api call to get the message.
For technical details, you can always send email to devsupport#ringcentral.com

How to get Selenium running in AWS Lambda using .net core

Trying to get an AWS Lambda function to run Selenium on .NET Core. Here is code:
public string FunctionHandler(ILambdaContext context)
{
context.Logger.LogLine("Entering function");
try
{
var driver = new InternetExplorerDriver();
context.Logger.LogLine("Navigating to URL");
driver.Navigate().GoToUrl("http://www.google.com/");
context.Logger.LogLine("Returning Done");
return "Done";
}
catch (Exception e)
{
context.Logger.LogLine("Oops: " + e);
return "Failed";
}
}
The error I get in the AWS console is:
OpenQA.Selenium.WebDriverException: Cannot start the driver service on http://localhost:41663/
at OpenQA.Selenium.DriverService.Start()
at OpenQA.Selenium.Remote.DriverServiceCommandExecutor.Execute(Command commandToExecute)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor(InternetExplorerDriverService service, InternetExplorerOptions options, TimeSpan commandTimeout)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor(InternetExplorerDriverService service, InternetExplorerOptions options)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor(InternetExplorerOptions options)
at OpenQA.Selenium.IE.InternetExplorerDriver..ctor()
at InstagramMagic.Function.FunctionHandler(ILambdaContext context)
It is possible, but so far I've only had luck getting it to work with Chrome. AWS Lambda is running a bare bones version of Amazon Linux. If you want to run something on it beyond the basics, you must package a zip file and deploy it with all of the binaries required. Unfortunately, I doubt IE will run on AWS Lambda. However, there is hope it could run on Azure's equivalent service, which uses what they call a 'Windows Container'.
You have to specify where the Chrome binary is located within Lambda's runtime file system that contains your function, which is going to be /var/task/. This is a node.js example of what you are attempting to do, but using chromedriver.
'use strict';
exports.handler = (event, context, callback) => {
var webdriver = require('selenium-webdriver');
var chrome = require('selenium-webdriver/chrome');
var builder = new webdriver.Builder().forBrowser('chrome');
var chromeOptions = new chrome.Options();
const defaultChromeFlags = [
'--headless',
'--disable-gpu',
'--window-size=1280x1696', // Letter size
'--no-sandbox',
'--user-data-dir=/tmp/user-data',
'--hide-scrollbars',
'--enable-logging',
'--log-level=0',
'--v=99',
'--single-process',
'--data-path=/tmp/data-path',
'--ignore-certificate-errors',
'--homedir=/tmp',
'--disk-cache-dir=/tmp/cache-dir'
];
chromeOptions.setChromeBinaryPath("/var/task/lib/chrome");
chromeOptions.addArguments(defaultChromeFlags);
builder.setChromeOptions(chromeOptions);
var driver = builder.build();
driver.get(event.url);
driver.getTitle().then(function(title) {
console.log("Page title for " + event.url + " is " + title)
callback(null, 'Page title for ' + event.url + ' is ' + title);
});
driver.quit();
};
I actually have a runnable packaged zip of this with a video tutorial on github, with a more detailed explanation. Peak inside the zip file to get an idea how the package should be laid out. https://blackboard.github.io/lambda-selenium/
In addition, I've submitted an issue on your behalf for a runnable .net core example.
https://github.com/blackboard/lambda-selenium/issues/22

Java Cant find Trusted Certificate (JKS)

I need to consume a service using CXF and I am facing the following issue.
Even though I had my Java key store (JKS) workig o SOAP UI, for example, when I use it on my java program it always give me the message
sun.security.validator.ValidatorException: No trusted certificate found
I have checked the JKS file and the certificate is in there, so when I put it on the SOAPUI project, it is recognized and the service successful called, with no problems. I am using as base the code provided by the cxf web site (http://svn.apache.org/viewvc/cxf/trunk/distribution/src/main/release/samples/wsdl_first_https/src/main/java/demo/hw_https/client/ClientNonSpring.java?view=log) , as follow:
public static void setupTLS(Object port) throws FileNotFoundException, IOException, GeneralSecurityException
{
final String keyStoreLoc = "d:/certs/mykeystore.jks";
HTTPConduit httpConduit = (HTTPConduit) ClientProxy.getClient(port).getConduit();
TLSClientParameters tlsCP = new TLSClientParameters();
final String keyPassword ="password";
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(keyStoreLoc), keyPassword.toCharArray());
KeyManager[] myKeyManagers = getKeyManagers(keyStore, keyPassword);
tlsCP.setKeyManagers(myKeyManagers);
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream(keyStoreLoc), keyPassword.toCharArray());
TrustManager[] myTrustStoreKeyManagers = getTrustManagers(trustStore);
tlsCP.setTrustManagers(myTrustStoreKeyManagers);
httpConduit.setTlsClientParameters(tlsCP);
}
private static TrustManager[] getTrustManagers(KeyStore trustStore)
throws NoSuchAlgorithmException, KeyStoreException
{
String alg = KeyManagerFactory.getDefaultAlgorithm();
TrustManagerFactory fac = TrustManagerFactory.getInstance(alg);
fac.init(trustStore);
return fac.getTrustManagers();
}
private static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword)
throws GeneralSecurityException, IOException
{
String alg = KeyManagerFactory.getDefaultAlgorithm();
char[] keyPass = keyPassword != null ? keyPassword.toCharArray() : null;
KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
fac.init(keyStore, keyPass);
return fac.getKeyManagers();
}
When debugging, I can see that the certs are loaded and the keystore and keystrustmanagers are populated accordingly, so after days trying to figure out what is happening, I am running out of ideas. So if you guys have any tip that can help,please help me out.
Thanks in advance.
After running some more tests it was clear that the certificate was the problem. I changed the jks for a valid one and now its running perfectly.
For the ones that need a solution like that, the example that I based my solution (http://svn.apache.org/viewvc/cxf/trunk/distribution/src/main/release/samples/wsdl_first_https/src/main/java/demo/hw_https/client/ClientNonSpring.java?view=log) works like a charm.

The method execute() is undefined for the type Mirror.Accounts.Insert

I am creating a server side Dynamic Web Project using Java and Eclipse IDE for Google Glass Mirror API. In my web project I have a lib folder under WEB-INF
In the lib folder i have added the following .jar files
google-api-client-1.18.0-rc-sources.jar
google-api-services-mirror-v1-rev66-1.19.0.jar
google-collections-1.0-rc2.jar
google-http-client-1.18.0-rc.jar
google-http-client-jackson-1.19.0.jar
My server side code is
#SuppressWarnings("serial")
public class GlassAuthenticateUser extends HttpServlet{
public static Mirror getMirrorService() throws GeneralSecurityException,
IOException, URISyntaxException {
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(MIRROR_ACCOUNT_SCOPES)
.setServiceAccountPrivateKeyFromP12File(
new java.io.File(SERVICE_ACCOUNT_PKCS12_FILE_PATH))
.build();
Mirror service = new Mirror.Builder(httpTransport, jsonFactory, null)
.setHttpRequestInitializer(credential).build();
return service;
}
public static void createAccount(Mirror mirror, String userToken, String accountName,
String authTokenType, String authToken) {
try {
Account account = new Account();
List<AuthToken> authTokens = Lists.newArrayList(
new AuthToken().setType(authTokenType).setAuthToken(authToken));
account.setAuthTokens(authTokens);
mirror.accounts().insert(
userToken, ACCOUNT_TYPE, accountName, account).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException{
//TO DO
}
}
}
I am getting the following error
The method execute() is undefined for the type Mirror.Accounts.Insert
Why is that so? I have download the latest Google API java client and used them in my project. However, it is unable to also resolve the GoogleCredential class
Can anyone suggest which .jar files should I be adding to resolve this issue?
It looks like you have the source jar for google-api-client-1.18.0-rc, when you need the class jar. You should be able to download the latest bundle from https://code.google.com/p/google-api-java-client/wiki/Downloads?tm=2 and then extracting google-api-java-client/libs/google-api-client-1.18.0-rc.jar from the downloaded zip file.