The view 'Search' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Search.aspx
~/Views/Home/Search.ascx
~/Views/Shared/Search.aspx
~/Views/Shared/Search.ascx
~/Views/Home/Search.cshtml
~/Views/Home/Search.vbhtml
~/Views/Shared/Search.cshtml
~/Views/Shared/Search.vbhtml
I am working on a basic web application that reads data from an api. When I run the solution and try to access the view referenced by this controller from the code below, I get this error. I have narrowed it down to being the GetAsync line of code. This works on windows however does not work on my Mac.
From what I can find, the cross platform .net framework Mono, used by visual studio on OSX, does not support GetAsync. What are my options if I want to develop/test this on my Mac but also deploy on a azure server?
public async Task<ActionResult> Search(string ticker)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(demoapiurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage res = await client.GetAsync(string.Format("{0}&symbol={1}&apikey={2}", apiurl, ticker, apikey));
if (res.IsSuccessStatusCode)
{
var accResponse = res.Content.ReadAsStringAsync().Result;
var quotes = GettingStarted.FromJson(accResponse);
GettingStarted allquotes = JsonConvert.DeserializeObject<GettingStarted>(accResponse);
return View(allquotes);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception Message: " + ex.Message);
}
}
return View();
}
Related
I have a WebApi that is running on Azure and fully tested via Postman
This API takes 2 headers
Content-Type: application/json
AppToken: {{AppToken}}
I want to call this API from a console application and I thought it is a pretty straight forward process. Here is my Main program
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("BASE_ADDRESS/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("AppToken", "MY_APP_TOKEN_VALUE");
// Call API to create the registration
CreateRegistration(client).Wait();
}
public static async Task CreateRegistration(HttpClient client)
{
using (client)
{
try
{
Registration reg1 = new Registration { email = "test#ssdafsds.com", clientId = 2342342, registrationId = 23423, ProgramId = 13 };
HttpResponseMessage responseMessage = await client.PostAsJsonAsync("api/auth/register", reg1);
responseMessage.EnsureSuccessStatusCode();
// Handle success
}
catch (Exception ex)
{
// Handle failure
Console.WriteLine(ex.StackTrace);
}
}
}
I am getting an internal server error as the "Reason Phrase" with status code 500. I am not sure why I am getting this error. I should be getting 201 Created like postman
Any idea how to solve this issue?
I made a mistake by passing a program id that I don't actually have in my database which failed the FK_Reference and caused this issue. Thank you all for your help.
I want to deploy and install an .appxbundle with c# on a UWP(IoT) - Device.
The REST-API documentation is on this site.
My code is
public async static Task<bool> UploadApp(string ip, Stream upload, string fileName)
{
try
{
if (http == null)
GetHttp();
HttpContent content = new StreamContent(upload);
var param = new Dictionary<string, string> {
{ "package", fileName}
};
var urlparam = new FormUrlEncodedContent(param);
var urlVar = await urlparam.ReadAsStringAsync();
var response = await http.PostAsync(String.Format("http://{0}:8080/api/app/packagemanager/package?{1}", ip, urlVar), content);
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
The code is not working. I get an "Bad request" Error after I send it and I don't know what to change. Could someone help me?
EDIT: The message I get is "Missing .appx (or .eappx) or .appinstaller file in uploaded files". I can deploy and install the package with ARC as "multipart/form-data".
I have seen a few questions posted with this same problem. I think I have all the pieces, but I am still getting the "Empty Payload" error. Does anyone see what is missing?
I want to update the category of some mail messages. I am using the beta endpoint because of this post: Microsoft Graph Client SDK vs. Requesting JSONs
Here is my code:
public async void UpdateMailCategory(GraphServiceClient graphClient, string messageId, string inbox)
{
string newCategory = #"{'categories': ['Processed']}";
try
{
// Get the request URL for adding a page.
string requestUrl = graphClient
.Users[inbox]
.Messages[messageId]
.Request()
.RequestUrl;
HttpRequestMessage hrm =
new HttpRequestMessage(new HttpMethod("PATCH"), requestUrl);
hrm.Content =
new StringContent(newCategory, Encoding.UTF8, "application/json");
// Authenticate (add access token) our HttpRequestMessage
await graphClient.AuthenticationProvider
.AuthenticateRequestAsync(hrm);
// Send the request and get the response.
HttpResponseMessage response =
await graphClient.HttpProvider.SendAsync(hrm);
}
catch (ServiceException Servex)
{
throw Servex;
}
}
When I look at the hrm.content, it shows this:
{ System.Net.Http.StringContent }
Headers:
{
Content - Type : application / json;charset = utf - 8
Content - Length : 35
}
You're using the Graph Client SDK is a rather roundabout way which is more likely going to cause you headaches than anything else. It also leads to more complicated code than necessary.
The SDK includes everything you need for the entire request. With the exception of an edge case, you should never need to deal with the HttpProvider or manage HttpRequestMessage and HttpResponseMessage instances.
The following will accomplish the same thing (setting the Categories property of a message) with a lot less complexity:
public async void UpdateMailCategory(GraphServiceClient graphClient, string messageId, string inbox)
{
try
{
await graphClient
.Users[inbox]
.Messages[messageId]
.Request()
.UpdateAsync(new Message()
{
Categories = new List<string>() { "Processed" }
});
}
catch (ServiceException Servex)
{
throw Servex;
}
}
You also shouldn't use the /beta version for this operation as it is supported by the /v1.0 version. You should only need to leverage the /beta version to manage the user's Categories since this isn't generally available yet.
I'm making Xamarin.Forms app which should get JSON from api and then allow to display it. My code so far:
public async void jsonDownload()
{
connect();
await downloadData();
}
public void connect()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
}
public async Task<List<Jsonclass>> downloadData()
{
String url = "https://my-json-server.typicode.com/kgbzoma/TestJsonFile/all";
var uri = new Uri(string.Format(url, string.Empty));
try
{
var response = await client.GetAsync(uri).ConfigureAwait(false);
response.EnsureSuccessStatusCode(); //NEVER GET HERE
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
List = JsonConvert.DeserializeObject<List<Jsonclass>>(content);
}catch (Exception ex)
{
Debug.WriteLine(#" Error {0}", ex.Message);
}
return List;
}
Problem is that code don't even go to response.EnsureSuccessStatusCode(); so my list of objects is empty. On UWP version it's working without any problems.
Here i'm gettin exception: System.Net.Http.HttpRequestException with message An error occurred while sending the request.
SecureChannelFailure (The authentication or decryption has failed.)
or
System.Net.WebException: Error: TrustFailure
or
Mono.Security.Protocol.Tls.TlsException: Invalid certificate received from server.
By default, Xamarin.Android uses the older Mono Managed HttpClient handler that does not support TLS 1.2.
Open your Xamarin.Android project settings, goto Build / Android Build / General and use the AndroidClientHandler.
This will add the following MSBuild properties directly to your .csproj
<AndroidHttpClientHandlerType>Xamarin.Android.Net.AndroidClientHandler</AndroidHttpClientHandlerType>
<AndroidTlsProvider>btls</AndroidTlsProvider>
Note: If doing this manually in the .csproj, you need to add them to the debug AND release PropertyGroup.
Or programmatically set the HttpClient to use it:
client = new HttpClient(new AndroidClientHandler());
Note: You should be looking at the InnerException for these types of errors
catch (Exception ex)
{
Console.WriteLine(#" Error {0}", ex.Message);
Console.WriteLine(#" Error {0}", ex.InnerException?.Message);
}
Using VS 2017 Community. Azure.
I have Azure setup, I have a blank webapp created just for test purpose.
My actual site is an Angular2 MVC5 site, currently run locally.
The following is the code that should... Contact azure providing secret key(the site is registered in azure Active directory).
From this i get a token i then can use to contact azure api and get list of sites.
WARNING: code is all Sausage code/prototype.
Controller
public ActionResult Index()
{
try
{
MainAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e.GetBaseException().Message);
}
return View();
}
static async System.Threading.Tasks.Task MainAsync()
{
string tenantId = ConfigurationManager.AppSettings["AzureTenantId"];
string clientId = ConfigurationManager.AppSettings["AzureClientId"];
string clientSecret = ConfigurationManager.AppSettings["AzureClientSecret"];
string token = await AuthenticationHelpers.AcquireTokenBySPN(tenantId, clientId, clientSecret).ConfigureAwait(false);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.BaseAddress = new Uri("https://management.azure.com/");
await MakeARMRequests(client);
}
}
static async System.Threading.Tasks.Task MakeARMRequests(HttpClient client)
{
const string ResourceGroup = "ProtoTSresGrp1";
// Create the resource group
// List the Web Apps and their host names
using (var response = await client.GetAsync(
$"/subscriptions/{Subscription}/resourceGroups/{ResourceGroup}/providers/Microsoft.Web/sites?api-version=2015-08-01"))
{
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsAsync<dynamic>().ConfigureAwait(false);
foreach (var app in json.value)
{
Console.WriteLine(app.name);
foreach (var hostname in app.properties.enabledHostNames)
{
Console.WriteLine(" " + hostname);
}
}
}
}
Controller class uses a static helper class that gets the token from Azure...
public static class AuthenticationHelpers
{
const string ARMResource = "https://management.core.windows.net/";
const string TokenEndpoint = "https://login.windows.net/{0}/oauth2/token";
const string SPNPayload = "resource={0}&client_id={1}&grant_type=client_credentials&client_secret={2}";
public static async Task<string> AcquireTokenBySPN(string tenantId, string clientId, string clientSecret)
{
var payload = String.Format(SPNPayload,
WebUtility.UrlEncode(ARMResource),
WebUtility.UrlEncode(clientId),
WebUtility.UrlEncode(clientSecret));
var body = await HttpPost(tenantId, payload).ConfigureAwait(false);
return body.access_token;
}
static async Task<dynamic> HttpPost(string tenantId, string payload)
{
using (var client = new HttpClient())
{
var address = String.Format(TokenEndpoint, tenantId);
var content = new StringContent(payload, Encoding.UTF8, "application/x-www-form-urlencoded");
using (var response = await client.PostAsync(address, content).ConfigureAwait(false))
{
if (!response.IsSuccessStatusCode)
{
Console.WriteLine("Status: {0}", response.StatusCode);
Console.WriteLine("Content: {0}", await response.Content.ReadAsStringAsync());
}
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<dynamic>().ConfigureAwait(false);
}
}
}
}
ISSUE:
Ok so the issue I was faced with was Async Deadlocks in my code. So i looked at this stack post stack post here
I fixed the issues by putting in .ConfigureAwait(false) on most of the await declarations.
Code runs and gets all the way back to the controller with a token etc and runs through the MakeARMRequests(HttpClient client) method, however the json only returns 1 result "{[]}" when i debug and as such ignores the loops.
My question is, is my code the culprit here? or would this point to a configuration setting in azure?
Not sure if this is the issue you are facing now BUT you never wait for a result from your async action in the first method Index in your code. MainAsync().ConfigureAwait(false); will immediately return and continue to the next block while the task MainAsync() will start in the background. The catch handler also does nothing because you dont wait f or a result.
Option 1 (recommended)
public async Task<ActionResult> Index()
{
try
{
await MainAsync().ConfigureAwait(false);
}
catch (Exception e)
{
Console.WriteLine(e.GetBaseException().Message);
}
return View();
}
Option 2 if you can't use async/await for some reason
public ActionResult Index()
{
try
{
MainAsync().GetAwaiter().GetResult();
}
catch (Exception e)
{
Console.WriteLine(e.GetBaseException().Message);
}
return View();
}
The Code looks OK and runs fine, Anyone who could help verify would be good, but one can assume this is OK.
The issue for this was configuration in azure, When you register an app you must set a certain number of Access controls via the subscription.
In this case I set some more specific things for the web api , for now set the app as owner and made reference to service management api.
Probably don't need half the "IAM" added in the subscription to the registered app, I simply went through adding the relevant ones and debugging each time until finally i got the results expected.