Xamarin picker not showing the date from the list - c#

I have the following code:
<ContentPage.BindingContext>
<local:PisterosViewModel/>
</ContentPage.BindingContext>
<Picker x:Name="pck_Pisteros"
ItemDisplayBinding="{Binding PisteroN}"
ItemsSource="{Binding PisterosLista}"
SelectedItem="{Binding PisterosLista}"
Title="Seleccione el usuario..."/>
Then my Model:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.Contracts;
using System.Text;
namespace ServLottery.Models
{
public class Pisteros
{
public string PisteroID { get; set; }
public string PisteroN { get; set; }
}
}
and the view model:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
namespace ServLottery.Models
{
public class PisterosViewModel
{
public IList<Pisteros> PisterosLista { get; set; }
public PisterosViewModel()
{
try
{
PisterosLista = new ObservableCollection<Pisteros>();
GetPisteros();
}
catch (Exception ex)
{
throw ex;
}
}
private async void GetPisteros()
{
try
{
RestClient client = new RestClient();
var pist = await client.Get<Models.Pisteros>("https://servicentroapi.azurewebsites.net/api/Pisteros");
if (pist != null)
{
PisterosLista = pist;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
I set an breakpoint in var pist and it does have the values, then Pisteros list seems to get the values too, and this is executed when the page load, so I don't understand what's the problem, but the picker never shows the options.

Welcome to SO !
It seems like BindingContext in Xaml can not deal with the dynamical data ,such API data from web server .
There is a workaround binding ItemSource dynamically by using coding in ContentPage , also can refer to this officail sample .
Therefore , adding code in Page.Xaml.cs as follow :
protected override async void OnAppearing()
{
pck_Pisteros.ItemsSource = await GetTasksAsync();
base.OnAppearing();
}
private async Task<List<Pisteros>> GetTasksAsync()
{
List<Pisteros> PisterosLista = new List<Pisteros>();
HttpClient client = new HttpClient();
Uri uri = new Uri(string.Format("https://servicentroapi.azurewebsites.net/api/Pisteros", string.Empty));
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
string content = await response.Content.ReadAsStringAsync();
PisterosLista = JsonConvert.DeserializeObject<List<Pisteros>>(content);
Console.WriteLine("content :: " + content);
Console.WriteLine("Data :: " + PisterosLista);
}
return PisterosLista;
}
Now it will show:

Related

HTTP status code 500 when querying an API from a C# program, except the API works

I need to use another company's API to query data using POST requests.
The API works (= I receive all the data with no errors) when I query it from the swagger website using the UI, but when I do it from my C# program I get a 500 Internal Server Error.
Where should I be looking for the problem ? Is there a way to get a more detailed error message ?
Edit (added code) :
using System;
using System.Data.Entity;
using System.Data.Entity.Core.Mapping;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Infrastructure.Interception;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Text;
namespace credex_distribution_offers_to_interfaces
{
class Program
{
private const string jsonMediaType = "application/json";
static void Main()
{
FetchJSONAndInsertToDB();
}
private static bool FetchJSONAndInsertToDB()
{
var baseServiceUrl = new Uri("a valid url");
Root rootObject;
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(jsonMediaType));
try
{
string token = FetchToken(httpClient, baseServiceUrl);
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(token);
}
catch (Exception e)
{
return false;
}
try
{
rootObject = FetchDistributionLookupOffers(httpClient, baseServiceUrl, 29612, 29613, 29614, 29617, 29621);
}
catch (Exception e)
{
return false;
}
}
// database related stuff...
// ...
return true;
}
[DataContract]
public class MortgageForDistributionLookupInputDto
{
public int[] OfferNumbers { get; set; }
}
private static Root FetchDistributionLookupOffers(HttpClient aHttpClient, Uri aBaseServiceUrl, params int[] aOfferNumbers)
{
var input = new MortgageForDistributionLookupInputDto()
{
OfferNumbers = aOfferNumbers
};
var lookup = aHttpClient.PostAsync(new Uri(aBaseServiceUrl, "v1/MortgageDetails/InvestorLookupOffers"), PayloadFor(input)).Result;
if (lookup.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Fetching investor lookup offers failed with HTTP status code '" + lookup.StatusCode + "' : " + lookup.ReasonPhrase + "}");
}
var obj = ValueFor<Root>(lookup.Content);
return obj;
}
private static HttpContent PayloadFor<T>(T aObject)
{
return new StringContent(aObject.SerializeJson(), Encoding.UTF8, jsonMediaType);
}
private static T ValueFor<T>(HttpContent aHttpContent)
{
//var content = aHttpContent.ReadAsStringAsync();
return aHttpContent.ReadAsStreamAsync().Result.DeSerializeJson<T>();
}
private static string FetchToken(HttpClient aHttpClient, Uri aBaseServiceUrl)
{
var login = new LoginRequest()
{
UserName = "some user name",
Password = "some password"
};
var authResult = aHttpClient.PostAsync(new Uri(aBaseServiceUrl, "api/Login"), PayloadFor(login)).Result;
if (authResult.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Fetching authentication token failed. Reason : " + authResult.StatusCode + " -> " + authResult.ReasonPhrase);
}
return authResult.Content.ReadAsStringAsync().Result.Trim('"');
}
}
}

Unity.WebApi - Make sure that the controller has a parameterless public constructor

I am currently working on an asp.net Web API project. The project consists of the following files: "S3BucketController", "IS3Service", "S3Service". Basically, I am trying to call the AmazonS3 web service to create and retrieve data. To make my code cleaner, I reference on the following article on dependency injection
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection
I am using the Unity.WebApi NuGet package (Unity 5.2.0 and Unity.WebApi 5.3.0) The issue I am facing is that when attempting to run the code, I get the error: Make sure that the controller has a parameterless public constructor. I've research similar issues in StackOverflow but still could not solve my issue.
Update I am still trying to solve this issue, any help is greatly appreciated
Below is my code:
S3BucketController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Task_7.Services;
namespace Task_7.Controllers
{
public class S3BucketController : ApiController
{
private readonly IS3Service _service;
// Initialize at constructor
// injected the IS3Service,
public S3BucketController(IS3Service service)
{
_service = service;
}
[HttpPost]
[Route("api/S3Bucket/CreateBucket")]
public async Task<IHttpActionResult> CreateBucket([FromBody] string bucketName)
{
var response = await _service.createBucketAsync(bucketName);
return Ok(response);
}
[HttpPost]
public async Task<IHttpActionResult> AddFile([FromBody] string bucketName)
{
await _service.createFileAsync(bucketName);
return Ok();
}
}
}
IS3Service
using System.Threading.Tasks;
using Task_7.Models;
namespace Task_7.Services
{
public interface IS3Service
{
Task<S3Response> createBucketAsync(string bucketName);
Task createFileAsync(string bucketName);
}
S3Service
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Transfer;
using Amazon.S3.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using Task_7.Models;
namespace Task_7.Services
{
public class S3Service : IS3Service
{
private readonly IAmazonS3 _client;
public S3Service(IAmazonS3 client)
{
_client = client;
}
public async Task<S3Response> createBucketAsync(string bucketName)
{
try
{
if (await AmazonS3Util.DoesS3BucketExistAsync(_client, bucketName) == false)
{
var putBucketRequest = new PutBucketRequest
{
BucketName = bucketName,
UseClientRegion = true
};
var response = await _client.PutBucketAsync(putBucketRequest);
return new S3Response
{
Message = response.ResponseMetadata.RequestId,
Status = response.HttpStatusCode
};
}
}
catch (AmazonS3Exception e)
{
return new S3Response
{
Status = e.StatusCode,
Message = e.Message
};
}
catch (Exception e)
{
return new S3Response
{
Status = HttpStatusCode.InternalServerError,
Message = e.Message
};
}
return new S3Response
{
Status = HttpStatusCode.InternalServerError,
Message = "Something Went Wrong"
};
}
private const string filePath = "C:\\Users\\ randomguy1\\Desktop\\Project\\Background_Images";
public async Task createFileAsync(string bucketName)
{
try
{
var fileTransferUtility = new TransferUtility(_client);
await fileTransferUtility.UploadAsync(filePath, bucketName);
}
catch (AmazonS3Exception e)
{
Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
}
catch (Exception e)
{
Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
}
//https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/net-dg-install-assemblies.html#net-dg-nuget
}
}
}
UnityResolver.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Dependencies;
using Unity;
using Unity.Exceptions;
namespace Task_7.Resolver
{
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
container.Dispose();
}
}
}
WebApiConfig.cs
using Amazon.S3;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using Task_7.Resolver;
using Task_7.Services;
using Unity;
using Unity.Lifetime;
namespace Task_7
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var container = new UnityContainer();
container.RegisterType<IS3Service, S3Service>(new HierarchicalLifetimeManager());
container.RegisterType<IAmazonS3>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}

Async/Await deadlock

I can't seem to get my code work, although I tried several different approaches. Here is my preferred code snippet:
var client = await ApiClientProvider.GetApiClient();
var freeToPlayChampions = await client.GetChampionsAsync(true, Region);
var championsData = freeToPlayChampions.Select(x =>
client.GetStaticChampionByIdAsync(
(int)x.Id,
platformId: Region));
ConsoleTable.From(await Task.WhenAll(championsData)).Write();
When debugging I see that the code hangs on await Task.WhenAll(championsData). So i tried to make the code more easy:
var client = await ApiClientProvider.GetApiClient();
var freeToPlayChampions = await client.GetChampionsAsync(true, Region);
var table = new ConsoleTable();
foreach(var freeToPlayChampion in freeToPlayChampions)
{
var championsData = client.GetStaticChampionByIdAsync(
(int)freeToPlayChampion.Id,
platformId: Region);
table.AddRow(await championsData);
}
table.Write();
Unfortunately this hangs, as well. Again on the same code part, e.g. await championsData.
How can this 'easy' usage of async/await lead to an deadlock? Thanks in advance for help!
EDIT:
Here is the whole class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ConsoleTables;
using Mono.Options;
using RiotNet.Models;
using RiotShell.Properties;
namespace RiotShell
{
public class FreeToPlay : IShellCommand
{
public IEnumerable<string> Names { get; }
public OptionSet Options { get; }
public bool ShowHelp { get; private set; }
public string Region { get; private set; }
public FreeToPlay()
{
Names = new List<string>
{
"freetoplay",
"ftp"
};
Options = new OptionSet
{
{ "r|region=" , "The region to execute against", x => Region = x},
{ "h|help|?" , "Show help", x => ShowHelp = true }
};
}
public async Task Execute(IEnumerable<string> args)
{
if (ShowHelp)
{
Options.WriteOptionDescriptions(Console.Out);
return;
}
if (args.Any())
{
throw new Exception(Resources.TooManyArgumentsProvided);
}
if (Region == null)
{
throw new Exception(string.Format(Resources.RequiredOptionNotFound, "region"));
}
if (!PlatformId.All.Contains(Region))
{
throw new Exception(string.Format(Resources.InvalidRegion, Region));
}
var client = await ApiClientProvider.GetApiClient();
var freeToPlayChampions = await client.GetChampionsAsync(true, Region);
var championsData = freeToPlayChampions.Select(x =>
client.GetStaticChampionByIdAsync(
(int)x.Id,
platformId: Region));
ConsoleTable.From(await Task.WhenAll(championsData)).Write();
}
}
}
And here is the caller code, my main method:
using System;
using System.Threading.Tasks;
using RiotShell.Properties;
namespace RiotShell
{
public class Program
{
public static async Task Main()
{
while (true)
{
Console.Write(Resources.RiotShellLineString);
var input = Console.ReadLine();
try
{
var parsedArgs = InputParser.Parse(input);
(var command, var commandArgs) = ArgsToIShellCommandCaster.GetCommand(parsedArgs);
await command.Execute(commandArgs);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
Since it was wished, here the code for the ApiProvider:
using RiotNet;
using System.Threading.Tasks;
namespace RiotShell
{
public class ApiClientProvider
{
private static IRiotClient _client;
public static async Task<IRiotClient> GetApiClient()
{
if (_client != null)
{
_client.Settings.ApiKey = await KeyService.GetKey();
return _client;
}
_client = new RiotClient(new RiotClientSettings
{
ApiKey = await KeyService.GetKey()
});
return _client;
}
}
}

C# Throwing unable to resolve controller error

I'm fairly new to .NET and c# and I'm working on a POC where I've run into an issue when a controller throws the error
System.InvalidOperation Exception {"Unable to resolve controller: TenantController"}
The Inner exception details are
No default Instance is registered and cannot be automatically determined for type 'GICS.Web.Managers.Interfaces.ITenantManager'
There is no configuration specified for GICS.Web.Managers.Interfaces.ITenantManager
1.) new TenantController(Default of ITenantManager, Default of IRemedyService)
2.) GICS.Web.Controllers.Api.TenantController
3.) Instance of GICS.Web.Controllers.Api.TenantController
4.) Container.GetInstance(GICS.Web.Controllers.Api.TenantController)
The TenantController looks as follows:
using System.Web.Mvc;
using GICS.Web.Controllers.Api.Abstracts;
using GICS.Web.Managers.Interfaces;
using GICS.Web.Services.Interfaces;
using System.Collections.Generic;
using GICS.Web.ViewModels.Tenant;
using GICS.Web.Models.Tenant;
namespace GICS.Web.Controllers.Api
{
[RoutePrefix("api/tenant")]
public class TenantController : BaseApiController
{
private readonly ITenantManager _tenantsManager;
private readonly IRemedyService _remedyService;
private string token;
public TenantController(ITenantManager tenantsManager, IRemedyService remedyService)
{
_tenantsManager = tenantsManager;
_remedyService = remedyService;
token = null;
}
[HttpGet, Route("{groupId}/{userName}")]
public JsonResult getTenants(string groupId, string UserName)
{
getToken(UserName);
JsonResult result = Json(null);
if (token != null)
{
var tenants = _tenantsManager.GetTenants(token, groupId);
List<TenantViewModel> tenantViewModelList = new List<TenantViewModel>();
foreach (Values x in tenants)
{
TenantViewModel model = new TenantViewModel(x, groupId);
tenantViewModelList.Add(model);
}
result = Json(tenantViewModelList);
}
return result;
}
}
The TenantManager interface is as follows:
using System.Collections.Generic;
using GICS.Web.Models.Tenant;
namespace GICS.Web.Managers.Interfaces
{
public interface ITenantManager
{
IEnumerable<Values> GetTenants(string token, string groupId);
}
}
And the Manager implementation is:
using GICS.Web.Managers.Abstracts;
using GICS.Web.Managers.Interfaces;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using GICS.Web.Models.Tenant;
namespace GICS.Web.Managers
{
public class TentantManager : ManagerBase, ITenantManager
{
public IEnumerable<Models.Tenant.Values> GetTenants(string token, string groupId)
{
Tenant restEntries = null;
List<Models.Tenant.Values> tenantList = new List<Models.Tenant.Values>();
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.Authorization] = token;
var baseURL = ConfigurationManager.AppSettings["RemedyBaseUrl"];
var apiPath = ConfigurationManager.AppSettings["RemedyAPIPath"];
string getURL = baseURL + apiPath + "ESN%3AAST%3ALogSysComp%5FASTPeople" + "?q=?q=%27PeopleGroup%20Form%20Entry%20ID%27%20%3D%20%22" + groupId + "%22&fields=values(Name)";
string getResponse = client.DownloadString(getURL);
restEntries = JsonConvert.DeserializeObject<Tenant>(getResponse);
foreach (Models.Tenant.Entry x in restEntries.entries)
{
tenantList.Add(x.values);
}
}
return tenantList;
}
}
}
I have other controllers in the project that follow the same approach and all are working except for this one. Anyone spot where I am going wrong here?
Thanks in advance.

Redirect to a webpage using an attribute in Asp.net webforms with web.api

I created this attribute class to redirect to a web page url:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using UtilityLibrary;
namespace xxxxxxx.Web.Attributes
{
public class SessionExpireWebApiFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public string UrlPortal { get { return System.Configuration.ConfigurationManager.AppSettings["Portal"].ToString(); } }
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
{
try
{
if (StateManager.Instance.Get(Key.Autenticacao, State.Session) == null)
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
filterContext.Response.Headers.Location = new Uri(http://www.examplepage.com);
}
base.OnActionExecuting(filterContext);
}
catch (Exception ex)
{
throw;
}
}
}
}
but nothing happens, the method that i used the attribute didn't excecute, but the page completed the post as status 200! Could someone help me?
Looks you are using OnActionExecuting, it is called before action method. Use OnResultExecuting or OnResultExecuted.
https://msdn.microsoft.com/en-us/library/system.web.mvc.actionfilterattribute.onresultexecuting(v=vs.118).aspx
Sorry, i'm did mistake.
I think you can do:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Result = new RedirectResult(url);
return;
}
i think this fix in your code will be help your.
public class SessionExpireWebApiFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public string UrlPortal { get { return System.Configuration.ConfigurationManager.AppSettings["Portal"].ToString(); } }
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
{
try
{
if (StateManager.Instance.Get(Key.Autenticacao, State.Session) == null)
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
filterContext.Response.Headers.Location = new Uri(http://www.examplepage.com);
/*add this return*/return;
}
base.OnActionExecuting(filterContext);
}
catch (Exception ex)
{
throw;
}
}
}

Categories