Parsing API response in Xamarin form - xamarin

I am new to xamarin. I am trying to get data from php api but it doesn't give me any data or error kindly check. URL is
http://mehdibalti.000webhostapp.com/xamrin/getall.php
response is .. [{"Id":"1","Name":"Mehdi","Department":"Balti"},{"Id":"2","Name":"Mehdi","Department":"Syntecx"}]
and i did like this
public class EmployeeServices
{
public EmployeeServices()
{
}
public async Task<List<EmployeeModel>> getEmployeeAsyn(){
RestClient<EmployeeModel> resclient = new RestClient<EmployeeModel>();
var list =await resclient.GetTodoItemsAsync();
return list;
}
}
}
this is my resClient Class
public async Task<List<EmployeeModel>> GetTodoItemsAsync()
{
var httpClient = new HttpClient();
var response = await httpClient.GetStringAsync(getAllUrl);
response = response.Replace("\"", "");
var todoItems = JsonConvert.DeserializeObject<List<EmployeeModel>>(response);
return todoItems;
}
this is Model class
public class EmployeeModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
}
but it did not return any list

The result API is giving you is not a list. Use stuff like http://json2csharp.com/
to investigate json you are getting.

Related

Blazor Session Storage

At my current project(blazor server side) I want to start using the session storage for user data like roles and names.
I've tried Blazored.SessionStorage and AspNetCore.Components.Server.ProtectedBrowserStorage.
The problem I'm facing is, that I just can't get the value(it's always null) and I don't know why.
Code I'm using:
public void GetUserInfo()
{
var x = sessionStorage.GetAsync<string>("Name");
var y = sessionStorage.GetAsync<string>("Email");
string Name = x.ToString();
string Email = y.ToString();
}
And
[Inject] public ProtectedSessionStorage sessionStorage { get; set; }
protected override async Task OnAfterRenderAsync(bool firstRender)
{
string Name = Helper.Name;
string Email = Helper.Email;
await sessionStorage.SetAsync("Name", Name);
await sessionStorage.SetAsync("Email", Email);
var x = sessionStorage.GetAsync<string>("Name");
var y = sessionStorage.GetAsync<string>("Email");
Name = x.Result.Value;
Email = y.Result.Value;
}
Thanks to everyone in advance and have a great day! :)
DO NOT USE THIS SOLUTION AS IS. WHEN I GET THE TIME I WILL UPDATE IT TO A WORKING SOLUTION
I suggest adding this as an injected object using Dependency Injection.
Create a class to hold this information and add is as a Scoped service.
Class:
public class UserInfo : IUserInfo //Create an interface
{
public static Name { get; set; }
public static Email { get; set; }
}
Injection (Program.cs on .NET 6):
public static async Task Main(string[] args)
{
//For WSAM
var builder = WebAssemblyHostBuilder.CreateDefault(args);
//For Server
var builder = WebApplication.CreateBuilder(args);
...
builder.Services.AddScoped<IUserInfo, UserInfo>(); //Scoped Service injection
}
Add data to injected service:
[Inject]
public IUserInfo UserInfo { get; set; }
protected override void OnInitialized() //Use whatever Life Cycle methods works for your implementation
{
UserInfo.Name = Helper.Name;
UserInfo.Email = Helper.Email;
}
Usage example:
#inject IUserInfo UserInfo
#page "/"
<div>#UserInfo.Name</div>
<div>#UserInfo.Email</div>

Fetching data from an API in ASP.NET Core MVC

I'm facing problem while fetching data from an API in ASP.NET Core MVC controller (imdb api).
The problem is I cannot deserialize the current JSON object into type
this is my code
List<Movie> movieList = new List<Movie>();
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://imdb-api.com/en/API/Title/****/tt0110413"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
var Movie = JsonConvert.DeserializeObject<Movie>(apiResponse);
//movieList = JsonConvert.DeserializeObject<List<Movie>>(apiResponse);
}
}
return View();
My api data looks like this
{
"items": [
{
"id": "tt0111161",
"rank": "1",
},...
]
}
I have an issue with deserialize - any help?
You need to make sure the structure of Movie is corresponding to your json data:
public class Movie {
public List<Item> items { get; set; }
}
public class Item {
public string id { get; set; }
public string rank { get; set; }
}
Use IMDbApiLib.
GitHub:
https://github.com/IMDb-API/IMDbApiLib
Nuget:
https://nuget.org/packages/IMDbApiLib
Movie's TitleData:
https://github.com/IMDb-API/IMDbApiLib/blob/master/IMDbApiLib/Models/TitleData.cs

Mediator Api call failing

I'm trying to make a simple request using mediator and .net core. I'm getting an error that I am not understanding. All I'm trying to do is a simple call to get back a guid.
BaseController:
[Route("api/[controller]/[action]")]
[ApiController]
public class BaseController : Controller
{
private IMediator _mediator;
protected IMediator Mediator => _mediator ?? (_mediator = HttpContext.RequestServices.GetService<IMediator>());
}
Controller:
// GET: api/Customer/username/password
[HttpGet("{username}/{password}", Name = "Get")]
public async Task<ActionResult<CustomerViewModel>> Login(string username, string password)
{
return Ok(await Mediator.Send(new LoginCustomerQuery { Username = username,Password = password }));
}
Query:
public class LoginCustomerQuery : IRequest<CustomerViewModel>
{
public string Username { get; set; }
public string Password { get; set; }
}
View Model:
public class CustomerViewModel
{
public Guid ExternalId { get; set; }
}
Handler:
public async Task<CustomerViewModel> Handle(LoginCustomerQuery request, CancellationToken cancellationToken)
{
var entity = await _context.Customers
.Where(e =>
e.Username == request.Username
&& e.Password == Encypt.EncryptString(request.Password))
.FirstOrDefaultAsync(cancellationToken);
if (entity.Equals(null))
{
throw new NotFoundException(nameof(entity), request.Username);
}
return new CustomerViewModel
{
ExternalId = entity.ExternalId
};
}
This is the exception I am getting:
Please let me know what else you need to determine what could be the issue. Also, be kind I have been away from c# for a while.
Thanks for the info it was the missing DI. I added this
// Add MediatR
services.AddTransient(typeof(IPipelineBehavior<,>), typeof(RequestPreProcessorBehavior<,>));
services.AddMediatR(typeof(LoginCustomerQueryHandler).GetTypeInfo().Assembly);
and we are good to go.

Web API controller returning boolean

I have a Web API where one of the methods in a controller return true or false when validating user id which is a string of numbers. I do no have an actual database yet, so I sort of mocked up the set of values in the repository.
Below is my code:
My repository class:
public class myRepository
{
public myClasses.Employee[] GetAllEmployees()
{
return new myClasses.Employee[]
{
new myClasses.Employee
{
empId="111111",
empFName = "Jane",
empLName="Doe"
},
new myClasses.Employee
{
empId="222222",
empFName = "John",
empLName="Doe"
}
};
}
public bool VerifyEmployeeId(string id)
{
myClasses.Employee[] emp = new myClasses.Employee[]
{
new myClasses.Employee
{
empId="111111",
empFName = "Jane",
empLName="Doe"
},
new myClasses.Employee
{
empId="222222",
empFName = "John",
empLName="Doe"
}
};
for (var i = 0; i <= emp.Length - 1; i++)
{
if (emp[i].empId == id)
return true;
}
return false;
}
}
and my model class:
public class myClasses
{
public class Employee
{
public string empId { get; set; }
public string empFName { get; set; }
public string empLName { get; set; }
}
}
and here is my controller:
public class myClassesController : ApiController
{
private myRepository empRepository;
public myClassesController()
{
this.empRepository = new myRepository();
}
public myClasses.Employee[] GetEmployees()
{
return empRepository.GetAllEmployees();
}
public bool VerifyEmployee(string id)
{
return empRepository.VerifyEmployeeId(string id);
}
}
Now when i compile it I get an error:
} expected
Type or namespace definition, or end-of-file expected
; expected
in line
return empRepository.VerifyEmployeeId(string id);
of my controller.
My question is using boolean the best way to return Success or Failure from Web API method or is there a better way? and also why am I getting this error. I am new to Web API
The compile error is caused by this;
return empRepository.VerifyEmployeeId(string id);
You should rewrite to:
return empRepository.VerifyEmployeeId(id);
You don't have you specify the type of the argument when calling a function.
About returning true or false; if you intend to only check whether the employee is valid or not, I should leave it this way. If you plan to use that employee data more you could rewrite that function so it returns the actual employee itself, and return 404: Not Found when the Employee is not found for instance.

WebAPI call brings in the xml namespace that causes the deserialization to fail

I have a WebAPI method like so:
[HttpPost, Route("api/student/studentstatus")]
public UpdatedStudent StudentStatus(HttpRequestMessage request)
{
string requestData = request.Content.ReadAsStringAsync().Result;
GetStudentStatus scp = null;
XmlSerializer serializer = new XmlSerializer(typeof(GetStudentStatus), new XmlRootAttribute("GetStudentStatus"));
using (Stream stream = request.Content.ReadAsStreamAsync().Result)
{
scp = (GetStudentStatus)serializer.Deserialize(stream);
}
}
This is the string in requestData
<GetStudentStatus xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/StudentStatusConsole">
<StudentID></StudentID><Batch></Batch>
</GetStudentStatus>
When StudentStatus is hit it dies at the Deserialize part with this error:
"<GetStudentStatus xmlns='http://schemas.datacontract.org/2004/07/StudentStatusConsole'> was not expected."}
This is the GetStudentStatus class:
public class GetStudentStatus
{
public string StudentID { get; set; }
public string Batch { get; set; }
}
Tried annotating the class with DataContract(NameSpace="") and adding DataMember attributes to the properties.
No go.
This is the method which calls the WebAPI:
using (var client = new HttpClient())
{
GetStudentStatus studentToPost = new GetStudentStatus() { StudentID = "", Batch = "" };
client.BaseAddress = new Uri("http://localhost:53247/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
HttpResponseMessage response = await client.PostAsXmlAsync("api/student/studentstatus", studentToPost);
}
Any help is greatly appreciated.
Try annotating your GetStudentStatus class with the DataContract attribute but specify the Namespace property so that it includes the namespace where the class is located.
[DataContract(Name = "GetStudentStatus", Namespace = "http://schemas.datacontract.org/2004/07/[NameSpace]")]
public class GetStudentStatus
{
public string StudentID { get; set; }
public string Batch { get; set; }
}

Resources