I have a Blazor-project (ServerApp). And I want to import data from Excel-files and a start week and an end week by using an API.
And the data I send is all 0. MinWeek, MaxWeek and the number of FormFiles.
Please can anybody help me?
public class ImportSelectModel
{
public int MinWeek { get; set; }
public int MaxWeek { get; set; }
[Required] public List<IFormFile> FormFiles { get; set; } = new();
}
}
... from the ImportService:
public async Task<string> ImportList(ImportSelectModel model)
{
try
{
var data = JsonConvert.SerializeObject(model);
HttpContent content = new StringContent(data, Encoding.UTF8, "application/json");
var httpResponseMessage = await _httpClient.PostAsync($"api/Import/SubmitFiles", content);
if (httpResponseMessage.IsSuccessStatusCode)
... from the API:
[HttpPost("SubmitFiles")]
[RequestSizeLimit(long.MaxValue)]
//public async Task<IActionResult> SubmitFiles([FromBody] int minWeek, int maxWeek, [FromForm] List<FormFile> formFiles)
public async Task<ActionResult<ImportSelectModel>> SubmitFiles([FromForm] ImportSelectModel model)
{
if (model.FormFiles.Count() > 0)
{
There added 2 files
And minWeek = 1 and maxWeek = 53.
And in the API everything is gone:
Related
i have a currently working embed post when a channel given in the config is live on twitch.
I want to make a loop that the function gets checked every 5 Minutes if the channel is live or not (live-alert for dc).
I use a classic timer and its looping and spamming the channel cuz i dont know which function i could use for it. MessageCaching is in the DiscordSocketClient config active.
I want: that its not spamming the embed. A little check needed to check if the streamer is live and embed already posted.. when not live check if the streamer was 5 minutes not live then check till hes live again (when streamers internet is reconnecting the stream embed dont need to get spammed)
Here is the full code of my twitch"handler"
using Microsoft.Extensions.DependencyInjection;
using Discord;
using Discord.WebSocket;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace CentricXBot.Services
{
public class TwitchHandler
{
// setup fields to be set later in the constructor
private readonly IConfiguration _config;
private readonly DiscordSocketClient _client;
private readonly IServiceProvider _services;
private readonly Microsoft.Extensions.Logging.ILogger _logger;
public TwitchHandler(IServiceProvider services)
{
//Timer Infinite Loop need to check if not Live still Loop if live and posted dont post any new but still checks
System.Timers.Timer timer = new System.Timers.Timer(10000); //10 seconds
timer.Elapsed += async ( sender, e ) => TwitchTest();
timer.Start();
// juice up the fields with these services
// since we passed the services in, we can use GetRequiredService to pass them into the fields set earlier
_config = services.GetRequiredService<IConfiguration>();
_client = services.GetRequiredService<DiscordSocketClient>();
_logger = services.GetRequiredService<ILogger<CommandHandler>>();
_services = services;
// hook into these events with the methods provided below
_client.Ready += TwitchTest;
}
public class Datum
{
[JsonProperty("id")] public string ID { get; set; }
[JsonProperty("userId")] public string user_id { get; set; }
[JsonProperty("user_name")] public string user_name { get; set; }
[JsonProperty("game_id")] public string game_id { get; set; }
[JsonProperty("game_name")] public string game_name { get; set; }
[JsonProperty("type")] public string type { get; set; }
[JsonProperty("title")] public string title { get; set; }
[JsonProperty("viewer_count")] public int viewer_count { get; set; }
[JsonProperty("thumbnail_url")] public string thumbnail_url { get; set; }
}
public class StreamObject
{
public List<Datum> data { get; set; }
}
public class ProfileTwitch
{
[JsonProperty("profile_image_url")] public string profile_image_url { get; set; }
}
public class ProfileObject
{
public List<ProfileTwitch> data { get; set; }
}
public async Task TwitchTest()
{
//Create new HttpClient
var client = new HttpClient();
//Send client-id and oauth token to Twitch API
client.DefaultRequestHeaders.Add("Client-ID", $"{_config["clientid"]}");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", $"{_config["oauth"]}");
//Get Stream Info
HttpResponseMessage response = await client.GetAsync($"https://api.twitch.tv/helix/streams?user_login={_config["live-alert-streamer"]}");
HttpContent responseContent = response.Content;
string jsonString = await response.Content.ReadAsStringAsync();
var stream = JsonConvert.DeserializeObject<StreamObject>(jsonString);
//Get Profile Info just for the profile picture
HttpResponseMessage responseUser = await client.GetAsync($"https://api.twitch.tv/helix/users?login={_config["live-alert-streamer"]}");
HttpContent responseUserContent = responseUser.Content;
string jsonProfileString = await responseUser.Content.ReadAsStringAsync();
var profile = JsonConvert.DeserializeObject<ProfileObject>(jsonProfileString);
//Check if the channel is not offline
if (!(stream == default(StreamObject) || stream.data.Count == 0))
{
Console.WriteLine($"Live: {stream.data[0].type}");
Console.WriteLine($"Streamer: {stream.data[0].user_name}");
Console.WriteLine($"Title: {stream.data[0].title}");
Console.WriteLine($"Game: {stream.data[0].game_name}");
Console.WriteLine($"ThumbnailURL: {stream.data[0].thumbnail_url.Replace("{width}x{height}","1920x1080")}");
Console.WriteLine($"Viewer Count: {stream.data[0].viewer_count}");
//Create Embed
var embed = new EmbedBuilder{};
embed.WithFooter(footer => footer.Text = "CentricX")
.WithTitle($"{stream.data[0].title}")
.WithAuthor($"{stream.data[0].user_name} is now live on Twitch!", $"{profile.data[0].profile_image_url}")
.WithImageUrl($"{stream.data[0].thumbnail_url.Replace("{width}x{height}","1920x1080")}")
.WithDescription($"Playing {stream.data[0].game_name} for {stream.data[0].viewer_count} viewers \n [Watch Stream](https://twitch.tv/{stream.data[0].user_name})")
.WithColor(Color.Blue)
.WithUrl($"https://twitch.tv/{stream.data[0].user_name}")
.WithCurrentTimestamp();
//Send Embed to channel
ulong ChannelID = Convert.ToUInt64(_config["live-alert-channel"]);
var sendchannel = _client.GetChannel(ChannelID) as IMessageChannel;
var msg = await sendchannel.SendMessageAsync(embed: embed.Build());
}
//If channel is offline do
else
{
Console.WriteLine("Not Live");
};
_logger.LogInformation("Twitch Handler loaded");
}
}
}```
I'm having issues retrieving the response with the populated result within the Dispatch method, I'm not sure what I'm missing :(
The issue seems to be when it's deserializing as the responseBody is correct until that point.
Can anyone help?
public async Task<Response> Dispatch(DispatchItem dispatchRequest)
{
var url = string.Format("dispatch/dispatchitem.json");
var response = PostAsJsonAsyncResponse<DispatchItem , DispatchResponse>(url, dispatchRequest);
response.Wait();
return new Response();
}
protected async Task<Response<TResponse>> PostAsJsonAsyncResponse<TModel, TResponse>(string url, TModel model)
{
using (var client = new HttpClient())
{
var authCredential = Encoding.UTF8.GetBytes($"{Username}:{Password}");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authCredential));
client.BaseAddress = new Uri(APIUrl);
var response = client.PostAsJsonAsync(url, model);
response.Wait();
var responseBody = await response.Result.Content.ReadAsStringAsync();
if (!response.Result.IsSuccessStatusCode)
throw new ApiException(response.Result.StatusCode, responseBody);
return JsonConvert.DeserializeObject<Response<TResponse>>(responseBody);
}
}
public class Response : Response<string>
{
}
public class Response<T>
{
public T Result { get; set; }
public bool IsSuccessful { get; set; }
}
}
public class DispatchResponse
{
public int Id { get; set; }
public guid Reference { get; set; }
}
Can someone help me?
I'm try to consume api in my apps (I'm still learning). I can successfully call the api and get the data, but debug ended in DeserializeObject.
Can someone help me, and tell what must I do? or reference how to fix this?
This is my code:
My ViewModels
from ViewModels I call GetHeroes(), which calls my class in services.
public class DotaViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public DotaViewModel()
{
GetHeroes(); // Start From Here
}
IDotaApi _rest = DependencyService.Get<IDotaApi>();
private ObservableCollection<Hero> heroes;
public ObservableCollection<Hero> Heroes
{
get { return heroes; }
set
{
heroes = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Heroes"));
}
}
public async void GetHeroes()
{
var result = await _rest.getheroes(); // Go Inside Here
if (result != null)
{
}
}
}
My Services
I got the data and stored it to var result, but my debug just when I DeserializeObject.
public class DotaApi : IDotaApi
{
string Base_url = "https://api.opendota.com/api/heroes";
public async Task<ObservableCollection<Hero>> getheroes()
{
string url = Base_url;
HttpClient client = new HttpClient();
HttpResponseMessage responseMessage = await client.GetAsync(url);
if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK)
{
var result = await responseMessage.Content.ReadAsStringAsync(); // I Got Data Here
var json = JsonConvert.DeserializeObject<ObservableCollection<Hero>>(result); // But Stuck Here
return json;
}
return null;
}
}
This is My Model
public class Hero
{
public int id { get; set; }
public string name { get; set; }
public string localized_name { get; set; }
public string primary_attr { get; set; }
public string attack_type { get; set; }
public List<string> roles { get; set; }
public int legs { get; set; }
//[
//{"id":1,
//"name":"npc_dota_hero_antimage",
//"localized_name":"Anti-Mage",
//"primary_attr":"agi",
//"attack_type":"Melee",
//"roles":["Carry","Escape","Nuker"],
//"legs":2}
//}
//]
}
Try to implement the API calling method like below and add a debug point to the exception and check the issue
public async Task<ObservableCollection<Hero>> getheroes()
{
string Base_url = "https://api.opendota.com/api/heroes";
using (var httpClient = new HttpClient())
{
var data = new ObservableCollection<Hero>();
try
{
var content = new StringContent(requestBody, Encoding.UTF8, "application/json");
var result = await httpClient.GetAsync(Base_url);
var response = await result.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<ObservableCollection<Hero>>(response);
if (result.IsSuccessStatusCode && result.StatusCode == HttpStatusCode.OK)
{
return data;
}
return null;
}
catch (Exception exp)
{
return null;
}
}
}
Thanks For all,
I finally solved the problem,
this is purely my fault cause I didn't really understand how it worked before,
so i try to understand more deeply about ObservableCollection and how to debug
now i know, there is nothing wrong with DeserializeObject like i said in my question (sorry for that), the problem is in GetHeroes() function
public async void GetHeroes()
{
var result = await _rest.getheroes();
if (result != null)
{
Heroes = result; // i missed this code, so. I haven't entered my data before
}
}
By posting a request to my database, I only get string values .For some reason, the floating values don't get to the DB.
Model
public DateTime ? Date {get;set; }
public double latitud { get; set; }
public double longitud { get; set; }
public string Name { get; set; }
Model Request = Model;
Request.latitud=location.Latitude;
Request.longitud=location.Longitude;
Request.Date=DateTime.Now;
Request.Name=Name;
Service:
public async Task<string> Post(Model Request)
{
var response = new ServiceResponse<string>();
using (var httpClient = new HttpClient())
{
InitClient(httpClient);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation(
"Content-Type", "application/json");
var result = await httpClient.PostAsync(API_URL,
new
StringContent(JsonConvert.SerializeObject(Request),
System.Text.Encoding.UTF8, "application/json"));
Debug.WriteLine("post results : " + result.Content);
}
}
return response;
}
Date, Name is successfully posted anytime I called the service,
However, none of the doubles values does. NOTE- I am 100% sure that all the values are been sent in the object Request.
I am trying to learn xamarin forms. I have this existing database that I wanted to be accessed by an App. Here I want to update something using web api/REST, I followed this guide for consuming REST. Unfortunately it's not working and I don't even know why.
How do I properly use PUT for updating something and what is wrong here?
WEB API class:
class GuestAcc
{
public string RefCode { get; set; }
public double Price { get; set; }
}
Xamarin Model:
public class GuestAcc
{
public string RefCode { get; set; }
public double Price { get; set; }
}
GuestAccountsController:
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> UpdateBalance(GuestAcc guestAcc)
{
var guestAccounts = db.GuestAccounts.First(x => x.ReferenceCode == guestAcc.RefCode);
guestAccounts.Balance = guestAccounts.Balance - guestAcc.Price;
db.Entry(guestAccounts).State = EntityState.Modified;
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
Xamarin form:
private async void btn_proceed_clicked(object sender, EventArgs e)
{
GuestAcc guestAcc = new GuestAcc();
guestAcc.Price = 125;
guestAcc.RefCode = "user123";
var guestAccountURL = "http://192.168.8.100:56750/api/UpdateBalance/";
var uri_guestAccount = new Uri(string.Format(guestAccountURL, string.Empty));
var json = JsonConvert.SerializeObject(guestAcc);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PutAsync(uri_guestAccount, content);
if (response.IsSuccessStatusCode)
{
await DisplayAlert("Notice", "Success", "Ok");
}
}
You need to use the correct HTTP verb either in the action name or as an attribute to the method. like
[ResponseType(typeof(void))]
[HttpPut]
public async Task<IHttpActionResult> UpdateBalance(GuestAcc guestAcc)
{
var guestAccounts = db.GuestAccounts.First(x => x.ReferenceCode == guestAcc.RefCode);
guestAccounts.Balance = guestAccounts.Balance - guestAcc.Price;
db.Entry(guestAccounts).State = EntityState.Modified;
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
or in the name like
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutBalanceAsync(GuestAcc guestAcc)
{
var guestAccounts = db.GuestAccounts.First(x => x.ReferenceCode == guestAcc.RefCode);
guestAccounts.Balance = guestAccounts.Balance - guestAcc.Price;
db.Entry(guestAccounts).State = EntityState.Modified;
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}