HttpWebRequest.GetResponseAsync is not working for NodusPayFabric Xamrin.Android - xamarin.android

Purpose: I am creating here a method which generates the token for payment gateway.
Code to generate and get the response from Nodus Payfabric is in PCL and the same code is working for Xamarin.IOS but not for Xamarin.Android.
The method is as below:
public async Task<HttpWebResponse> GetWebResponseForSecurityToken(string deviceID)
{
try
{
HttpWebRequest httpWebRequest = WebRequest.Create("https://sandbox.payfabric.com/v2/rest/api/token/create") as HttpWebRequest;
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "GET";
httpWebRequest.Headers["authorization"] = deviceID;
return await httpWebRequest.GetResponseAsync() as HttpWebResponse; // ISSUE LINE
}
catch (Exception)
{
return null;
}
}
As mentioned in above method issue is in return line which is not generating any error or returning the response, instead debug mode is closed after executing this line.
Is there anything I am missing to support this code with Xamarin.Android?

Related

How to Implement Flutter Web SSL Certificate (SSL Pinning)

I am building a flutter web app and I need to use SSL to talk to the server using a .pem certificate.
I am using HttpClient and IOClient to get it to work and the code for this looks as following:
fetchData()async{
HttpClient _client = HttpClient(context: await globalContext);
_client.badCertificateCallback =
(X509Certificate cert, String host, int port) => false;
IOClient _ioClient = new IOClient(_client);
var response = await _ioClient.get(Uri.parse('https://appapi2.test.bankid.com/rp/v5.1'));
print(response.body);
}
Future<SecurityContext> get globalContext async {
final sslCert1 = await
rootBundle.load('assets/certificates/bankid/cert.pem');
SecurityContext sc = new SecurityContext(withTrustedRoots: false);
sc.setTrustedCertificatesBytes(sslCert1.buffer.asInt8List());
return sc;
}
I get the following error when trying to run fetchData:
Unsupported operation: SecurityContext constructor
I have also tried using the flutter plugin DIO that looks like this:
void bid() async {
final dio = Dio();
ByteData bytes = await rootBundle
.load('assets/certificates/bankid/FPTestcert4_20220818.pem');
(dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(client) {
SecurityContext sc = SecurityContext();
sc.setTrustedCertificatesBytes(bytes.buffer.asUint8List());
HttpClient httpClient = HttpClient(context: sc);
return httpClient;
};
try {
var response = await dio.get('https://appapi2.test.bankid.com/rp/v5.1');
print(response.data);
} catch (error) {
if (error is DioError) {
print(error.toString());
} else {
print('Unexpected Error');
}
}
}
When running this I get the following error:
Error: Expected a value of type 'DefaultHttpClientAdapter', but got one of type
'BrowserHttpClientAdapter'
I understand that I get the error above because of the casting that the httpClientAdapter is used as a DefaultHttpClientAdapter but since the app is running in the browser its using BrowserHttpClientAdapter, but how do I solve this?
Is it possible to make this work?

MS Graph - how to check for return code 204 after subscription is deleted?

Just new to ms graph and also to .net.
I'm trying to write a method that deletes a notification subscription. The code itself seems to work. But i need to know how to look up the actual return code from the upstream API instead of just sending back a 204.
Here's the code:
[Route("msgraphnotification/{subscriptionId}")]
[HttpDelete]
[AllowAnonymous]
public async Task<Int> delete(string subscriptionId)
{
try{
GraphServiceClient graphClient = await getAuthToken();
await graphClient.Subscriptions["{subscription-id}"]
.Request()
.DeleteAsync();
return 204; // this is what I want to fix.
}
catch(Exception ex){
Console.Write(ex);
return 404;
}
}
If you really need to know the response code you can send HTTP request with the .Net Microsoft Graph client library.
// Get the request URL for deleting a subscription
var requestUrl = client.Subscriptions["{subscription-id}"].Request().RequestUrl;
// Create the request message.
var hrm = new HttpRequestMessage(HttpMethod.Delete, requestUrl);
// Authenticate HttpRequestMessage
await client.AuthenticationProvider.AuthenticateRequestAsync(hrm);
// Send the request and get the response.
var response = await client.HttpProvider.SendAsync(hrm);
// Get the status code.
if (!response.IsSuccessStatusCode)
{
throw new ServiceException(
new Error
{
Code = response.StatusCode.ToString(),
Message = await response.Content.ReadAsStringAsync()
});
}
else
{
var statusCode = (int)response.StatusCode;
}
...

"Response status code does not indicate success: 500 (Internal Server Error)" while creating Test Suite through TFS Rest API

While trying to create a Test Suite using TFS 2017 REST API, I am getting the error:
System.Net.Http.HttpRequestException - Response status code does not
indicate success: 500 (Internal Server Error)
Code I tried:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string base64StringPat = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", Configs.Pat)));
AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Basic", base64StringPat);
client.DefaultRequestHeaders.Authorization = authHeader;
string url = "http://vmctp-tl-mtm:8080/tfs/DefaultCollection/SgkProject/_apis/test/Plans/7/Suites/8?api-version=1.0";
var content = new StringContent("{\"suiteType\":\"StaticTestSuite\",\"name\":\"Module1\"}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
I have used this documentation from Microsoft to call the API: Create a test suite
Please guide me in fixing the issue.
HTTP code 500 means that this is an error on your server. The server threw an exception when trying to process this POST request.
So, this error has nothing to do with HttpClient. Just check your server first and see what causes the exception.
A possibility is that the specified content type is not expected by the server. POST a StringContent will set the content type to text/plain. You might find the server doesn't like that. In this case just try to find out what media type the server is expecting and set the Headers.ContentType of the StringContent instance.
Whatever, I can create the suite by below sample, you can have a try for that:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace CreateTestSuite
{
class Program
{
public static void Main()
{
Task t = CreateTestSuite();
Task.WaitAll(new Task[] { t });
}
private static async Task CreateTestSuite()
{
try
{
var username = "username";
var password = "password";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
string url = "http://server:8080/tfs/DefaultCollection/LCScrum/_apis/test/plans/212/suites/408?api-version=1.0";
var content = new StringContent("{\"suiteType\":\"StaticTestSuite\",\"name\":\"Module3\"}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

Spring not allowing RequestMethod.DELETE

I have this endpoint that invoke my service method which in turn call my repo class to Delete a user, but when i call this endpoint through postman i get a request Method not supported" printed in the console,any help would be greatly appreciated
#RequestMapping(value = "/{useId}/delete-user", method = RequestMethod.DELETE)
public ResponseEntity<String> deleteUser(#PathVariable("userId") String userId){
ResponseEntity<String> response = null;
try {
validate(userId);
userService.deleteUser(Long.parseLong(userId));
response = new ResponseEntity<String>(HttpStatus.NO_CONTENT);
}catch (InputMismatchException e){
response = new ResponseEntity<String>(HttpStatus.BAD_REQUEST);
} catch (UserNotFoundException e) {
response = new ResponseEntity<String>(HttpStatus.NOT_FOUND);
} catch (AccessDeniedException e) {
response = new ResponseEntity<String>(HttpStatus.FORBIDDEN);
}
return response;
}
The message received is Request method 'DELETE' not supported
There is a typo in the #RequestMapping. userid is misspelled. That is why Spring is not mapping the DELETE to deleteUser method

How to use a MVC action for downloading Google Drive streams

I am trying to make a download link for Google Drive documents through my MVC Google Drive API application using the DownloadFile method suggested by Google Drive documentation:
public static System.IO.Stream DownloadFile(
IAuthenticator authenticator, File file) {
if (!String.IsNullOrEmpty(file.DownloadUrl)) {
try {
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
new Uri(file.DownloadUrl));
authenticator.ApplyAuthenticationToRequest(request);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) {
return response.GetResponseStream();
} else {
Console.WriteLine(
"An error occurred: " + response.StatusDescription);
return null;
}
} catch (Exception e) {
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
} else {
// The file doesn't have any content stored on Drive.
return null;
}
}
In the View I build the controller call by the following line:
Download
which correctly sends data to my controller's action:
public FileStreamResult DownloadFile(string downloadUrl, string mimeType, string fileName){
System.IO.Stream stream = new GDriveRepository(Utils.ReturnIAuth((GoogleAuthenticator)Session["Gauthenticator"])).DownloadFile(downloadUrl);
return new FileStreamResult(stream, mimeType);
}
But the download fails and I cannot figure out where I am wrong!
The request to download the file must include authorization information, specifically your OAuth2 access token. See the Download Files guide in the developer documentation for more information and sample code.
I do not had to seek the file cause I was just trying to download the file. What I did is just read the stream i.e. through the DownloadFile API method and pass it to the browser. I enabled it through the following code:
public FileResult DownloadFile(string fileId)
{
DriveService service = Session["service"] as DriveService;
Google.Apis.Drive.v2.Data.File file = service.Files.Get(fileId).Fetch();
System.IO.Stream data = new GDriveRepository(Utils.ReturnIAuth((GoogleAuthenticator)Session["Gauthenticator"])).DownloadFile(file.DownloadUrl);
return File(data, System.Net.Mime.MediaTypeNames.Application.Octet, file.Title);
}

Resources