I'm trying to use Azure Mobile Services and Xamarin. I follow all instuctions of official tutorial, created Azure backend for application and downloaded sample quick-start app for Xamarin.Forms from Azure.
There is code in TodoItemManager.cs:
public async Task<ObservableCollection<TodoItem>> GetTodoItemsAsync(bool syncItems = false)
{
try
{
IEnumerable<TodoItem> items = await todoTable
.Where(todoItem => !todoItem.Done)
.ToEnumerableAsync();
return new ObservableCollection<TodoItem>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
}
return null;
}
And I got MobileServiceInvalidOperationException with message "Invalid sync operation: The request could not be completed. (Not Found)".
I have tested Azure Backend on UWP App and it works fine. So looks like there is problem in WP8.1 project. Can anybody help with this exception?
So.. I forgot to enable internet connection on my Windows Phone
Related
THIS IS MY CODE
This code is a Device controller that is one of the controllers I have created..
// GET: api/Devices
[HttpGet]
public async Task<ActionResult<IEnumerable<Device>>> GetDevice()
{
return await _context.Device.ToListAsync();
}
// GET: api/Devices/5
[HttpGet("{id}")]
public async Task<ActionResult<Device>> GetDevice(Guid id)
{
var device = await _context.Device.FindAsync(id);
if (device == null)
{
return NotFound();
}
return device;
}
I have deployed ASP.NET Core Web API and able to access the Get request, follow the below steps
Create an ASP.NET Core API in Visual studio
Below is the file structure
ProductsController.cs
Use post method in ProductController.cs use the below
[HttpGet]
public ActionResult<IEnumerable<Product>> GetAll() => Ok(_productService.GetAll());
[HttpGet("{id}")]
public ActionResult<Product> Get(Guid id) => Ok(_productService.Get(id));
Deployed the Web-app to Azure app service from visual studio
I have tried the Get request and got the below output
Now Goto Get ID and use the copied id there as click on send
After that you will get the value with the help of ID as below
We have a .NET Core Web API deployed as an Azure Web App. All endpoint work locally, however, once deployed, we have one controller that is gives us a 404 for all endpoint we hit within it.
We have checked and triple checked that the url we are calling is correct & from what we can tell, there is nothing different about this controller relative to the others in our application.
This is our BinController that is giving us 404's:
namespace API.Controllers
{
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class BinController : ControllerBase
{
private readonly IBinRepository _binRepo;
private readonly ILogger _logger;
public BinController(IBinRepository binRepo, ILogger<BinController> logger)
{
_binRepo = binRepo;
_logger = logger;
}
[HttpGet("{locationId}/{binId}")]
public async Task<IActionResult> CheckBinExists(int locationId, string binId)
{
try
{
bool result = await _binRepo.CheckBinExists(locationId, binId);
return Ok(result);
}
catch (Exception e)
{
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
[HttpGet("findAll/{locationId}/{itemId}")]
public async Task<IActionResult> FindAllBinsWithItem(int locationId, string itemId)
{
try
{
var result = await _binRepo.FindAllBinsWithItem(locationId, itemId);
return Ok(result);
}
catch (Exception e)
{
_logger.LogError(e.Message);
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
[HttpGet("contents/{locationId}/{bin}")]
public async Task<IActionResult> GetBinContents(int locationId, string bin)
{
try
{
List<BatchLine> contents = await _binRepo.GetBinContents(locationId, bin);
return Ok(contents);
}
catch (Exception e)
{
_logger.LogError(e.Message);
return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
}
}
}
}
We are calling https://ourapiname.azurewebsites.net/api/Bin/1234/TestBin.
To Summarize:
All endpoints work locally
All controllers work when deployed except for one
We have multiple other controllers in our application with similar if not the same setup, but this one is returning a 404 when deployed
We saw these similar posts, but they did not resolve this issue:
Web API interface works locally but gets 404 after deployed to Azure Website
Web api call works locally but not on Azure
I wish I could provide more insight, but we are really at a loss for what could be going on here. Any ideas would be greatly appreciated.
You can deploy your web project with Self-Contained mode, then find the project_name.exe and double-click it. Test it in your local, and your test url should be https://localhost:5001/api/Bin/1234/TestBin.
If you can run it works well in your local, the second step you should to create a new webapp, then deploy it as usual. We just rult out the some specifical reason in your original webapp.(like: deploy failed)
If it still not work, my suggestion is you can manually drag and drop the publish file to the kudu site of the azure webapp.
The steps above should be useful to you, but I think the easiest way is to go to the kudu site to get the dll file, and then decompile it, so that the root cause of the problem can be found.
This does not make any sense, but I simply changed the name of the Controller from "BinController" to "BinsController" and now it works...
Must not be able to name a controller "Bin".
I had a Microsoft Bot Framework project that connect to Web API(that not hosted in azure).
in local host everything was work fine. but when i was deployed the Bot to an Azure app service. it's seem that the call is failed(and the Bot not return any response).
this is my post request:
public static string Post(List<ActionInputParams> data, string url)
{
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/json;charset=utf-8";
try
{
var res = wc.UploadString(url, "POST", JsonConvert.SerializeObject(data));
return res;
}
catch (Exception ex)
{
return "error " + ex.Message;
}
}
}
my question: there is a problem to call to external Web API from Azure app service? or i just missing something?
in the "log stream" i getting a 500 error:
HTTP Error 500.0 - Internal Server Error
The page cannot be displayed because an internal server error has occurred.
I am currently implementing Azure AD B2C into my Xamarin.ios native app. However, the only examples I can find are for Xamarin.Forms, this means ive had to try and convert it to Xamarin.ios. The example given is Xamarin.Forms Azure AD B2C Example
The problem Im having is at the point I try to request the Access Token from Azure. It always returns System.NullReferenceException. When I tested the actual example in Forms it worked fine and all I have done is copy the code from that project into the Ios one whilst changing the things that need to be changed to Xamarin.Ios rather than Forms. This is the code below that return the Null Exception:
async partial void LoginButton(NSObject sender)
{
try
{
AuthenticationResult result = await App.AuthenticationClient.AcquireTokenAsync(
Constants.Scopes,
string.Empty,
UIBehavior.SelectAccount,
string.Empty,
null,
Constants.Authority);
//Constants.SignUpSignInPolicy);
//await Navigation.PushAsync(new LogoutPage(result));
}
catch (MsalException ex)
{
if (ex.Message != null && ex.Message.Contains("AADB2C90118"))
{
//await OnForgotPassword();
}
if (ex.ErrorCode != "authentication_canceled")
{
//await DisplayAlert("An error has occurred", "Exception message: " + ex.Message, "Dismiss");
}
}
}
I managed to get it to work by using this example which is an updated version and taking the code from this to Xamarein.ios native. Sample I used for Azure AD B2C
I'm using IMobileServiceSyncTable from Azure Mobile App. In InsertAsync operation, on the backend server side, I had some validations for the data and, if that validations failure, I want throw Exception from the server side. I tried return InternalServerError(), throw HttpResponseException, but never worked on the client side. I debbuged the Post method in server side, the server throws the exception or return InternalServerError, but in the mobile client, don't occurs error.
Can anyone help me?
Here is my code on the client side:
public async Task<bool> AddPaciente(Paciente novoPaciente)
{
//other things
try
{
await _pacienteTable.InsertAsync(novoPaciente);
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
throw new WebException(AppResources.MensagemFalhaConexaoServidorAzure);
}
await SyncPaciente();
return true;
}
Here is my post method on the backend server side
// POST tables/Paciente
public async Task<IHttpActionResult> PostPaciente(Paciente novoPaciente)
{
//other things
if (paciente != null)
{
var responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Já existe um paciente com esse token cadastrado.")
};
//throw new HttpResponseException(responseMessage);
return InternalServerError(new Exception("Já existe um paciente com esse token cadastrado."));
}
}
You should listen to the response status code.
var response = await _pacienteTable.InsertAsync(novoPaciente);
if (response.IsSuccessStatusCode) {
var content = await response.Content.ReadAsStringAsync ();
}
else
{
//Here handle the error code
throw new WebException(AppResources.MensagemFalhaConexaoServidorAzure);
}
I'm using IMobileServiceSyncTable from Azure Mobile App. In InsertAsync operation, on the backend server side, I had some validations for the data and, if that validations failure, I want throw Exception from the server side.
For IMobileServiceSyncTable, you are dealing with An Offline Client which means that IMobileServiceSyncTable<T>.InsertAsync would directly insert data into the local SQLite store on your mobile client-side. Until you manually call MobileServiceClient.SyncContext.PushAsync(), then your local data store would be pushed to your mobile backend. For this approach, I would recommend you make sure that you need to validate the inputs before you saving them into the local data store, otherwise your push operations would fail, then you need to force your client user to adjust the existing inputs even after it has been successfully added before.
If you use An Online Client as follows, then both your approaches for throwing the exception would be immediately returned to your client.
var mobileClient= new MobileServiceClient("https://{your-mobile-app-name}.azurewebsites.net");
var _pacienteTable= mobileClient.GetTable<Paciente>();
await _pacienteTable.InsertAsync(novoPaciente);
Moreover, I used the following code line for catching the exception:
try
{
await table.InsertAsync(item);
}
catch (MobileServiceInvalidOperationException ex)
{
//TODO:
//await ex.Response.Content.ReadAsStringAsync(); //get detailed response content
}
catch (Exception e)
{
//TODO: other uncaught exception
}
Also, for the similar issue, you could leverage Fiddler to capture the network traces to narrow down this issue, make sure your client-side could correctly receive the relevant response.