I have tried to fix this problem with my project for a while the getjokes returns null values and even though I don't have any errors. I am trying to make a app where there is just a simple joke shown. The api link is here APIlink.
This is the first time I have ever put anything on here so I'm probably doing it wrong but if anyone can help I will appreciate it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace JokeApp.Classes
{
public class Main
{
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("setup")]
public string Setup { get; set; }
[JsonProperty("delivery")]
public string Delivery { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
}
public class catagories
{
[JsonProperty("categories")]
public List<String> Categories { get; set; }
}
public class main
{
[JsonProperty("Main")]
public Main Main { get; set; }
[JsonProperty("categories")]
public string catogories { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Windows.UI.Popups;
namespace JokeApp.Classes
{
class CardWrapper
{
public static async Task<Main> Getjokes()
{
Uri request = new Uri(#"https://sv443.net/jokeapi/category/any");
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("User_Agent" ,"JokeApp");
HttpResponseMessage respons = await client.GetAsync(request);
if (respons.IsSuccessStatusCode == false)
{
MessageDialog md = new MessageDialog("Cant find jokes!!");
await md.ShowAsync();
}
respons.EnsureSuccessStatusCode();
main mc = await respons.Content.ReadAsAsync<main>();
return mc.Main;
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using JokeApp.Classes;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using static JokeApp.Classes.Main;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace JokeApp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page,INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public MainPage()
{
this.InitializeComponent();
Getjokes();
}
private Main _joke = new Main();
public Main Jokes
{
get { return _joke; }
set { _joke = value; NotifyPropertyChanged(); }
}
private async void Getjokes()
{
Jokes = await CardWrapper.Getjokes();
}
}
}
The response from sv443 looks like it would deserialize to an object of class Main, not of class main. So you probably want:
Main mc = await respons.Content.ReadAsAsync();
instead of
main mc = await respons.Content.ReadAsAsync();
In general, it's a bad idea to have two class definitions that differ only in capitalization, precisely because this type of problem can occur.
If that's not it, try logging your respons.Content as a string and see what's actually in there.
Related
I'm currently builiding an ASP .NET MVC application but I'm getting this error in my program. Not really sure what I did wrong.
This is my model: ProfileCreationContext
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using System.IO;
using Microsoft.Data.SqlClient;
using System.Data;
namespace CRUD_Profile_Creation.Models
{
public class ProfileCreationContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
optionsBuilder.UseSqlServer(configuration["ConnectionStrings:UserProfile"]);
}
SqlConnection con = new SqlConnection("Data Source=DESKTOP-HDBEK6R;Initial Catalog=Bottleneckv1;Integrated Security=True");
public DbSet<ProcessUnit> ProcessUnit { get; set; }
}
}
This is my other model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD_Profile_Creation.Models
{
public class ProcessUnit
{
public string ProcessUnitID { get; set; }
public string ProcessUnitName { get; set;}
public int ProcessTypeID { get; set;}
public string InventoryName { get; set;}
public string CumM { get; set;}
public string PerdayM { get; set;}
public string TotalM { get; set; }
}
}
And this is my controller:
using CRUD_Profile_Creation.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace CRUD_Profile_Creation.Controllers
{
public class ProcessUnitController : Controller
{
private ProfileCreationContext db = new ProfileCreationContext();
public IActionResult Index()
{
ViewBag.processUnitID = db.ProcessUnitID.ToList();
ViewBag.processUnitID = db.ProcessUnitName.ToList();
ViewBag.processUnitID = db.ProcessTypeID.ToList();
ViewBag.processUnitID = db.InventoryName.ToList();
ViewBag.processUnitID = db.CumM.ToList();
ViewBag.processUnitID = db.PerdayM.ToList();
ViewBag.processUnitID = db.TotalM.ToList();
return View();
}
}
}
This is the error I'm getting.
I'm still new in this framework. Im doing this based off my past personal projects
THE SOLUTION I DID
so basically, what I wanted was to list out all the items in the table. this is how I fixed it. I needed just to call that. Not sure why I started by listing all the variables. Hope this helps!
My controller:
public class DenoProfileController : Controller
{
private ProfileCreationContext db = new ProfileCreationContext();
public IActionResult Index()
{
ViewBag.denoprofile = db.DenoProfile.ToList();
return View();
}
}
hello im trying to build a rest api with many to one relationship using code first. here is my two entities :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace RestApiAndForm.Models
{
public class Categorie
{
[Key]
public int id { get; set; }
[Required,MaxLength(60)]
public string nom { get; set; }
public ICollection<Produit> produits { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace RestApiAndForm.Models
{
public class Produit
{
[Key]
public int id { get; set; }
[Required,Index,MaxLength(60)]
public string libelle { get; set; }
public uint stock;
[Required]
public Categorie categorie { get; set; }
}
}
here is the context :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace RestApiAndForm.Models
{
public class bdTestContext : DbContext
{
public bdTestContext() : base("connTest") { }
public DbSet<Categorie> categories { get; set; }
public DbSet<Produit> produits { get; set; }
}
}
in my controller im using this code :
using RestApiAndForm.Models;
using RestApiAndForm.Models.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace RestApiAndForm.Controllers
{
public class ProduitController : ApiController
{
private bdTestContext bd = new bdTestContext();
[HttpGet]
public List<Produit> GetProduits()
{
try
{
List<ProduitResponse> produitResponses = new List<ProduitResponse>();
List<Produit> produits = bd.produits.ToList();
return produits;
}
catch (Exception e)
{
return null;
}
}
i want to get the product and there categorie but the entity does not come with the categorie information even when im using produit.Find(id) , i cant have access to the categorie entity.
this is the result on postman (as you can see all categorie are set to null )
Postman result of the getProduits method
does anyone have the solution for that thank you
You should include them like the following :
List<Produit> produits = bd.produits.Include(p=> p.categorie).ToList();
Refer to : Eager loading
And don't forget to add
using System.Data.Entity; to your usings.
I am a starter in Azure Functions and durable Entities. I want to do the following things:
Create a durable entity and it has a state called systemList;
Create a queue trigger function to consume messages in my queue and store them in the entity state I just created.
create a http trigger function to get the current state of the entity;
And I met some problems in the 3rd step.
The code is as follows:
//HttpTriggerFunction.cs:
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json.Linq;
namespace **.Function
{
public static class HttpTriggerQueryEntity
{
[FunctionName("QueryEntity")]
public static async Task<HttpResponseMessage> Run(
[HttpTrigger(AuthorizationLevel.Function)] HttpRequestMessage req,
[DurableClient] IDurableEntityClient client)
{
var entityId = new EntityId(nameof(ProcessingListEntity), "processing_message_total");
EntityStateResponse<JObject> stateResponse = await client.ReadEntityStateAsync<JObject>(entityId);
//await client.SignalEntityAsync(entityId, "Empty");
return req.CreateResponse(HttpStatusCode.OK,stateResponse.EntityState);
}
}
}
//blockData.cs
#nullable enable
using System;
namespace **.Function
{
public class BlockData
{
public string? id { get; set; }
public string? SessionId { get; set; }
public string? MachineId { get; set; }
public DateTime? Start { get; set; }
public DateTime? End { get; set; }
public string? Activity {get; set;}
public string? BlobId { get; set; }
}
}
//Entity.cs
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Newtonsoft.Json;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
using System.Collections.Generic;
namespace **.Function
{
[JsonObject(MemberSerialization.OptIn)]
public class ProcessingListEntity
{
public ProcessingListEntity(){
systemList = new Dictionary<string, BlockData>();
}
[JsonProperty("systemList")]
public Dictionary<string, BlockData> systemList {get; set;}
public void Add(BlockData blockData) {
if (!this.systemList.ContainsKey(blockData.MachineId)) {
this.systemList.Add(blockData.MachineId, blockData);
return;
}
else {
this.systemList[blockData.MachineId].Start = blockData.Start;
this.systemList[blockData.MachineId].End = blockData.End;
}
}
public void Empty() => this.systemList = new Dictionary<string, BlockData>();
public Dictionary<string, BlockData> Get() => this.systemList;
[FunctionName(nameof(ProcessingListEntity))]
public static Task Run([EntityTrigger] IDurableEntityContext ctx)
=> ctx.DispatchAsync<ProcessingListEntity>();
}
}
But when I run it in my local environment and send Http query to it, the program stop. But when I changed the following line in HttpTriggerFunction.cs:
return req.CreateResponse(HttpStatusCode.OK,stateResponse.EntityState);
to
return req.CreateResponse(HttpStatusCode.OK,stateResponse.EntityState + "");
It can run and return the required string. But what I want to return is Json string.
So what can I do to fix my code? Thank you!
You can do is serialize the object and encode it and then send it.
So instead of createResponse return a HttpResponseMessage.
First you need to add packages such as:
using system.text;
using NewtonSoft.Json;
Then you can return :
return new HttpResponseMessage(HttpStatusCode.OK){Content = new StringContent(JsonConvert.SerializeOject(stateResponse.EntityState , Formating.Indented),Encoding.UTF8,"Response.json")}:
Refer the following article by Callon Campbell
Refer the following documentation.
I'm trying Firestore with the nugget package Google.Cloud.Firestore
I followed this intro CRUD with firestore
Using the debugger I can see that the execution of the program stops when trying to call the method Query.GetSnapshotAsync()
I want to get just a list of documents from a collection.
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Results;
using FirestoreAPI.Domain.Restaurants;
using FirestoreAPI.Repository.Restaurants;
using System.Threading.Tasks;
namespace FirestoreAPI.Controllers
{
[RoutePrefix("api")]
public class RestaurantsController : ApiController
{
public RestaurantsController() { }
[HttpGet]
[Route("restaurants")]
public IHttpActionResult GetAllRestaurants()
{
//var restAggregate = new RestaurantsAggregate();
var restaurantsRepo = new RestaurantsRepo();
return new NegotiatedContentResult<Task<List<Restaurant>>>(
HttpStatusCode.OK,
restaurantsRepo.GetAllRestaurants(),
this
); ;
}
}
}
DataLayer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Google.Cloud.Firestore;
namespace FirestoreAPI.Repository.Restaurants
{
public class RestaurantsRepo
{
//public FirestoreConn dbConn;
string projectId;
FirestoreDb firestoreDb;
public RestaurantsRepo()
{
//dbConn = new FirestoreConn();
string credentials = "C:\\Users\\ezequiel.lopez\\projects\\firestoredotnet\\FirestoreAPI\\firestoreapi-dca55-0be2f7d57f41.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credentials);
projectId = "firestoreapi-dca55";
firestoreDb = FirestoreDb.Create(projectId);
}
public async Task<List<Restaurant>> GetAllRestaurants()
{
//FirestoreDb fsDB = dbConn.GetFSConnection();
//Query query = fsDB.Collection("restaurants").OrderByDescending("avgRating").Limit(50);
Query query = firestoreDb.Collection("restaurants").OrderByDescending("avgRating").Limit(50);
QuerySnapshot restSnaps = await query.GetSnapshotAsync();
List<Restaurant> restaurants = new List<Restaurant>();
return restSnaps.Documents
.Where<DocumentSnapshot>(ds => ds.Exists)
.Select(ds => ds.ConvertTo<Restaurant>()).ToList();
}
}
}
Restaurant
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Google.Cloud.Firestore;
namespace FirestoreAPI.Repository.Restaurants
{
[FirestoreData]
public class Restaurant
{
[FirestoreProperty]
public decimal avgRating { get; set; }
[FirestoreProperty]
public string category { get; set; }
[FirestoreProperty]
public string city { get; set; }
[FirestoreProperty]
public string name { get; set; }
[FirestoreProperty]
public int numRatings { get; set; }
[FirestoreProperty]
public int price { get; set; }
}
}
I was having the same issue. Thing is, I was calling an async method from a synchronous one. It didn't work until I've made my caller method async and awaited for it.
Am getting this exception:
An exception of type 'System.Reflection.TargetInvocationException'
occurred in System.ni.dll but was not handled in user code
My Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using trialss.Resources;
using System.IO;
using Newtonsoft.Json;
namespace trialss
{
public class Token
{
public string Token_No { get; set; }
public string Transaction_Date { get; set; }
public string Transaction_Amount { get; set; }
public string Purchased_Units { get; set; }
}
public class RootObject
{
public List<Token> Token { get; set; }
public int success { get; set; }
}
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void clikeed(object sender, RoutedEventArgs e)
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri("my link"));
}
void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);
foreach (var book in rootObject.Token)
{
}
}
}
}
How can I solve the problem?
Why don't you try using Windows.Data.Json? I use HttpClient to download a Stream. Then I parse it using some classes (depending on the requirements) that has the namespace mentioned above.