Parsing json to c# windows phone 8 - c#

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.

Related

"does not contain a definition and no accessible extension metho..."

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();
}
}

Mvc creating route attribute

I want to create a route attribute in the Porosi controller, in the detaje method that takes as a DatePorosie (DatePorosie is the date) on parameter. The method must display from Porosi.cs class EmriPorosise, DatePorosie, TotaliPorosise according to the date that comes as a parameter in url. (sending date value either by form or by link). I hope I explained it well. Can you help me please???
This is Porosi.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcProjektDb.Models
{
public class Porosi
{
public int PorosiId { get; set; }
public string EmriPorosise { get; set; }
public DateTime DatePorosie { get; set; }
public int TotaliPorosise { get; set; }
public int? KlienteId { get; set; }
public virtual Kliente Kliente { get; set; }
}
}
This is PorosiController.cs but I don't know what to do here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcProjektDb.Migrations;
using MvcProjektDb.Models;
namespace MvcProjektDb.Controllers
{
public class PorosiController : Controller
{
private ApplicationDbContext _db;
public PorosiController()
{
_db = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_db.Dispose();
}
// GET: Porosi
public ActionResult Index()
{
return View();
}
[Route("Porosi/detaje/{dateporosie?}")]
public ActionResult detaje(DateTime? dateporosie)
{
var x = _db.porosi.Where(p => p.DatePorosie == dateporosie).ToList();
return View(x);
}
}
}

I can't figure out how to extract variables from api

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.

GetSnapshotAsync() never returning and I don't get any errors. How can I debug this issue?

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.

How to delete item from SQLite PCL database on Xamarin.Forms?

I am using one of the Xamarin.Forms tutorials on SQLite database deployment to learn how to add, get and delete items from a mobile database. At the moment, I am not quite sure how to retrieve a the Id attribute from a database item in my table to pass it through the deleteData method. Basically, after I add in a certain amount of items, I would like to delete some of the data. I have implemented a button in my XAML binding pages but I need to know how to retrieve the Id attribute of certain items and pass them into the deleteData method I have created. Can anyone help me with this?
Here are the codes:
StudentDB.cs (database class)
using System;
using System.Linq;
using SQLite.Net;
using Xamarin.Forms;
using System.Collections.Generic;
namespace XamarinSqliteSample
{
public class StudentDB
{
private SQLiteConnection _sqlconnection;
public StudentDB ()
{
_sqlconnection = DependencyService.Get<ISQLite> ().GetConnection ();
_sqlconnection.CreateTable<Student> ();
}
public IEnumerable<Student> GetStudents()
{
return (from t in _sqlconnection.Table<Student> ()
select t).ToList ();
}
public Student GetStudent (int id)
{
return _sqlconnection.Table<Student> ().FirstOrDefault (t => t.Id == id);
}
public void DeleteStudent(int id)
{
_sqlconnection.Delete<Student>(id);
}
public void AddStudent(Student student)
{
_sqlconnection.Insert(student);
}
}
}
Student.cs (item attributes for database table)
using System;
using SQLite.Net.Attributes;
namespace XamarinSqliteSample
{
public class Student
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public Student ()
{
}
}
}
Register.xaml.cs (C# page to create methods to that manipulate data)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace XamarinSqliteSample
{
public partial class Register : ContentPage
{
public StudentDB _studentdb;
public Student student;
public Register()
{
InitializeComponent();
}
public void adddata(object s, EventArgs args)
{
student = new Student();
_studentdb = new StudentDB();
student.Name = name.Text;
student.Address = address.Text;
student.Phone = phone.Text;
student.Id++;
_studentdb.AddStudent(student);
}
public void Showdata(object sender, EventArgs args)
{
Navigation.PushModalAsync(new StudentList());
}
}
}
StudentList.xaml.cs (C# page to populate list view with database items)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace XamarinSqliteSample
{
public partial class StudentList : ContentPage
{
public StudentDB _database;
public Student student;
public StudentList()
{
InitializeComponent();
_database = new StudentDB();
var students = _database.GetStudents();
StudentListView.ItemsSource = students;
}
public void deleteData(object s, EventArgs args)
{
_database = new StudentDB ();
_database.DeleteStudent (//Id attribute is passed in here);
}
}
It depends on how you trigger deleteData, but you'll probably want to use StudentListView.ItemSelected, which should be one of your Student objects.

Categories

Resources