why do I have this Rest Api uri error? - c#

My problem
I have my Universal Windows Application and i want work with rest api.
I always get error CS 4032 in this :
httpResponseBody = await httpClient.GetStringAsync(requestUri);
Like you can't call that method when it is not async.
Whole code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Net;
using Windows.Web.Http;
namespace UniversalCA
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Send();
}
public string Send()
{
HttpClient httpClient = new HttpClient();
Uri requestUri = new Uri("http://restapic.azurewebsites.net/WebForm1.aspx?func=dd&hodn=WW");
HttpResponseMessage httpResponse = new HttpResponseMessage();
string httpResponseBody = "";
try
{
httpResponseBody = await httpClient.GetStringAsync(requestUri);
}
catch (Exception ex)
{
httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
}
string tt = httpResponseBody.Split('>')[1].Split('<')[0];
return httpResponseBody;
}
}
}

The problem is that you cannot use await keyword inside a not async function. Your Send function does not have async keyword in declaration. Adding async keyword will solve the problem
public async Task<string> Send()

Just To add to #Ruben Vardanyans answer.
simply:
add using System.Threading.Tasks;
add Wait() keyword on your Send(); call
public MainPage()
{
this.InitializeComponent();
Send().Wait();
}
and finally on your Send() method
add async Task<T>
public async Task<string> Send()
Please check out this answer for calling an asynchronous method inside a constructor. Call asynchronous method in constructor?
do not use await Send(); for calling the method you will have a compiler error.

Related

How to return the name of a file I sent via POST request from an Azure function in .AspNetCore

Hi I am new to C# programming and azure functions.I want to send a file via POST request to an azure function and I want it to return the file name. This is my code:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace Demo1
{
public static class initialTrigger
{
[FunctionName("Function2")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get","post", Route = null)] HttpRequest req,
ILogger log)
{
try
{
var formdata = await req.ReadFormAsync();
var file = req.Form.Files["file"];
return new OkObjectResult(file.FileName + " - " + file.Length.ToString());
}
catch (Exception ex)
{
return new BadRequestObjectResult(ex);
}
}
}
}
I am sending the file using postman to this function which I have hosted locally using Visual Studio.But it is showing System.NullReferenceException at the return instance of OkObjectResult. Can someone help me with this? Thanks in advance!

GET, POST to a rest api

Hi i have a Api that i want to use to collect data from a backend that spits out json i need to get this via C# Application and it's http functionalities. My question is should i use a rest api and setup an async thread that downloads the data and then use the data as i want to from there or should i somehow use something close to a Web Api i have an authentication that is required to exist in a header. This has given me some hedaches because i keep on being split by what to use for what. I mean i need to do a Httprequest with a header. this i later on need to use for posting to another database. but the user of the program should not have to see the data itself. i have two examples that i have done but i don't know with what i should continue? this is my two examples in code...
Example 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
namespace Plugin
{
public enum HttpVerb
{
GET,
POST,
PUT,
DELETE
}
class Api
{
private HttpVerb HttpMethod { get; set; }
public Api()
{}
public string startDownload()
{
return (Download("sending token"));
}
private string Download(string token)
{
string strResponseValue = string.Empty;
string finnishedOutput = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("Url");
request.Headers.Add("Authorization", "Bearer " + token);
request.Method = HttpMethod.ToString();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
strResponseValue = reader.ReadToEnd();
}
return strResponseValue;
}
catch (WebException e)
{
HttpWebResponse httpResponse = (HttpWebResponse)e.Response;
if ((int)httpResponse.StatusCode == 401)
{}
int errorCodeInt;
string errorCode;
errorCodeInt = (int)httpResponse.StatusCode;
errorCode = errorCodeInt.ToString();
return errorCode;
}
}
}
}
Example 2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace TestAPi
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Api.InitializeClient("");
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
namespace TestAPi
{
public class Api
{
private static HttpClient ApiClient { get; set;}
private string url { get; set;}
public static void InitializeClient(string token)
{
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri("your url");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Bearer Authentication"));
}
public async Task<Data> LoadData()
{
url = ApiClient.BaseAddress.ToString();
using (HttpResponseMessage response = await ApiClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
Data data = await response.Content.ReadAsAsync<data>();
return data;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
}

Xamarin forms with firebase user registration error

i am developing an app using xamarin forms and firebase authentication
with xamarin.firebase.auth and xamarin.firebase.core
when i want to create a new user the code works fine but it gives me the exception
Java.Lang.IllegalStateException: 'Task is not yet complete'
when i trace the code line by line every thing works just fine and i get no errors but when running the app after creating user it gives me the exception.
this is my code:
inerface in pcl:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace XamarinFirebaseAuth
{
public interface IAuth
{
Task<string> LoginWithEmailPassword(string email, string password);
bool SignUpWithEmailPassword(string email, string password);
}
}
android implementation:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Foundation;
using UIKit;
using XamarinFirebaseAuth;
using XamarinFirebaseAuth.iOS;
using Firebase.Auth;
using System.Threading.Tasks;
using Xamarin.Forms;
[assembly: Dependency(typeof(AuthIOS))]
namespace XamarinFirebaseAuth.iOS
{
public class AuthIOS : IAuth
{
public async Task<string> LoginWithEmailPassword(string email, string password)
{
try
{
var user = await Auth.DefaultInstance.SignInWithPasswordAsync(email, password);
var token = user.User.GetIdTokenAsync();
return token.ToString();
}
catch(Exception e)
{
return "";
}
}
public bool SignUpWithEmailPassword(string email, string password)
{
try
{
var signUpTask = Auth.DefaultInstance.CreateUserAsync(email, password);
return true;
}
catch (Exception e)
{
throw;
//return false;
}
}
}
}
and this is my sign up page :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace XamarinFirebaseAuth
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SignUpPage : ContentPage
{
IAuth auth;
public SignUpPage()
{
InitializeComponent();
auth = DependencyService.Get<IAuth>();
}
private async void btnRegister_Clicked(object sender, EventArgs e)
{
try
{
bool created = auth.SignUpWithEmailPassword(EmailInput.Text, PasswordInput.Text);
if (created)
{
await DisplayAlert("Success", "Your account created successfully", "OK");
await Navigation.PopAsync();
}
else
{
await DisplayAlert("Error", "Something went wrong. Try again later!", "OK");
}
}
catch
{
throw;
}
}
}
}
I think you should await the CreateUserAsync method to know whether the account is created successfully or not:
AuthDataResult signUpTask = await Auth.DefaultInstance.CreateUserAsync(email, password);
Then you can get the user info:
await signUpTask.User.GetIdTokenAsync();

Mono Invalid IL code in System.Net.Http.HttpClient:.ctor (System.Net.Http.HttpClient): method body is empty

I am trying to get my C# application to run on Mono. Its purpose is to consume as REST WebApi using System.Net.Http.HttpClient. However, when I run it, the Mono .Net runtime throws the following exception:
Unhandled Exception:System.InvalidProgramException: Invalid IL code in System.Net.Http.HttpClient:.ctor (): method body is empty.
Here is the source code:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace MyProject.Data
{
public class DataAccess
{
public string Uri;
public int DeviceId;
static HttpClient client;
public DataAccess(string uri)
{
Uri = uri;
client = new HttpClient();
client.BaseAddress = new Uri(uri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<List<Event>> GetEvents(int deviceId)
{
List<Event> events = new List<Event>();
HttpResponseMessage response = await client.GetAsync(string.Format("devices/{0}/events", deviceId));
if (response.IsSuccessStatusCode)
{
events = await response.Content.ReadAsAsync<List<Event>>();
}
return events;
}
//... other data access methods
I am running on Mono JIT compiler version 4.6.2 (Debian 4.6.2.7+dfsg-1) on Raspbian distro.
Has anyone come across this ?
Thanks in advance.
Damien.

Stripe Webhook Controller Not Found

I have the following:
public class StripeController : Controller
{
private readonly UserService _userService;
public StripeController(UserService userService)
{
_userService = userService;
}
[HttpPost]
public ActionResult StripeWebook()
{
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
[HttpPost]
[Route("api/stripewebhook")]
public async Task<ActionResult> Index(CancellationToken ct)
{
var json = new StreamReader(Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
switch (stripeEvent.Type)
{
case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents
var stripeCharge = Stripe.Mapper<StripeCharge>.MapFromJson(stripeEvent.Data.Object.ToString());
break;
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
}
}
And requests from stripe generate an error:
The controller for path '/api/stripewebhook' was not found or does not implement IController
Any idea why this is happening when I test from the stripe portal?
Using WebApi 2 it works with no problem.
Here is the smallest WebApi controller to begin with:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class StripeController : ApiController
{
[HttpPost]
[Route("api/stripewebhook")]
public IHttpActionResult Index()
{
var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
return Ok();
}
}
}
if you execute this from VS you can access it from http://localhost:(port)/api/stripewebhook
Now you only need to extend this to include the stripe code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace WebApplication1.Controllers
{
public class StripeController : ApiController
{
[HttpPost]
[Route("api/stripewebhook")]
public IHttpActionResult Index()
{
var json = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();
var stripeEvent = StripeEventUtility.ParseEvent(json);
switch (stripeEvent.Type)
{
case StripeEvents.ChargeRefunded: // all of the types available are listed in StripeEvents
var stripeCharge = Stripe.Mapper<StripeCharge>.MapFromJson(stripeEvent.Data.Object.ToString());
break;
}
return Ok();
}
}
}

Categories