I want to load json data to my wpf datagrid.
I have followed this tutorial: http://wpf-4-0.blogspot.com/2012/12/how-to-bind-json-data-to-datagrid-in.html
But something is going wrong and I am not sure where is the problem.
my xaml code:
<Button Click="btnLoad_Click" Content="Load" Width="50" Grid.Row="0"></Button>
<DataGrid Grid.Row="1" x:Name="albuminfo" AutoGenerateColumns="True"></DataGrid>
C# code:
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
WebRequest req = WebRequest.Create("http://coderomusic.com/beta/SecuredAdministrator/mobile/getInfo.php?_mod=album");
req.ContentType = "application/json";
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader re = new StreamReader(stream);
string json = re.ReadToEnd();
json = "{\"AlbumDetail\":" + json + "}";
Wrapper w = (Wrapper)new JavaScriptSerializer().Deserialize(json, typeof(Wrapper));
albuminfo.ItemsSource = w.albumdetail;
}
AlbumDetail class:
public class AlbumDetail
{
#region//private property
private int albumId;
private string albumName;
private DateTime releasedate;
private int productionId;
private string duration;
private string category;
private string themes;
private ImageBrush coverImage;
private ImageBrush profileImage;
private string description;
private double albumPrice;
private double specialPrice;
private int[] artistIds;
#endregion
#region//public property
public int[] ArtistIds
{
get { return artistIds; }
set { artistIds = value; }
}
public double SpecialPrice
{
get { return specialPrice; }
set { specialPrice = value; }
}
public double AlbumPrice
{
get { return albumPrice; }
set { albumPrice = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}
public ImageBrush ProfileImage
{
get { return profileImage; }
set { profileImage = value; }
}
public ImageBrush CoverImage
{
get { return coverImage; }
set { coverImage = value; }
}
public string Themes
{
get { return themes; }
set { themes = value; }
}
public string Category
{
get { return category; }
set { category = value; }
}
public string Duration
{
get { return duration; }
set { duration = value; }
}
public int ProductionId
{
get { return productionId; }
set { productionId = value; }
}
public DateTime Releasedate
{
get { return releasedate; }
set { releasedate = value; }
}
public string AlbumName
{
get { return albumName; }
set { albumName = value; }
}
public int AlbumId
{
get { return albumId; }
set { albumId = value; }
}
#endregion
}
and Wrapper class:
public class Wrapper
{
public List<AlbumDetail> albumdetail { get; set; }
}
The end result looks like below image:
https://dl.dropboxusercontent.com/u/59201118/json.JPG
(dropbox link because i'm not allowed to post image!)
You should make the web request on a background thread and then update the UI using the dispatcher object. I have modified your code to make it work. Here are the important bits,
private static readonly ManualResetEvent AllDone = new ManualResetEvent(false);
private void BtnLoadClick(object sender, RoutedEventArgs e)
{
var request =
(HttpWebRequest)
WebRequest.Create("http://coderomusic.com/beta/SecuredAdministrator/mobile/getInfo.php?_mod=album");
request.ContentType = "application/json";
request.BeginGetResponse(GetResponseCallback, request);
AllDone.WaitOne();
}
private void GetResponseCallback(IAsyncResult ar)
{
var request = (HttpWebRequest) ar.AsyncState;
var response = (HttpWebResponse) request.EndGetResponse(ar);
Stream stream = response.GetResponseStream();
Wrapper w = null;
if (stream != null)
{
var re = new StreamReader(stream);
string json = re.ReadToEnd();
w = (Wrapper) new JavaScriptSerializer().Deserialize(json, typeof (Wrapper));
}
Dispatcher.BeginInvoke(
new Action(() => {
if (w != null)
albuminfo.ItemsSource = new ObservableCollection<AlbumDetail>(w.AlbumDetail);
}));
response.Close();
AllDone.Set();
}
Change it to suit your needs. I hope it works.
Simple and easy way use jsonorm from nuget and create a data layer from received json by (http://json2csharp.com/)
Related
I have some Properties and i want to save some specific property value in json format.Here is my code and i want to save two properties value like SelectedScalesModel and SelectedScales port Can anyone help me with this.
public class SetUpViewModel : ViewModelBase
{
public List<string> ScalesModel { get; set; } = new List<string> { "None", "METTLER-TOLEDO", "DINI ARGEO DFW-DFWK", "ESSAE SI-810" };
private string _selectedScalesModel;
public string SelectedScalesModel
{
get { return _selectedScalesModel; }
set
{
_selectedScalesModel = value;
RaisePropertyChanged("SelectedScalesModel");
}
}
public List<string> ScalesPort { get; set; } = new List<string> { "None", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM10", "COM11", "COM12", "COM13", "COM14", "COM15" };
private string _selectedScalesPort;
public string SelectedScalesPort
{
get { return _selectedScalesPort; }
set
{
_selectedScalesPort = value;
RaisePropertyChanged("SelectedScalesPort");
}
}
string _text1;
public string BlackLineText
{
get { return _text1; }
set
{
_text1 = value;
RaisePropertyChanged(nameof(BlackLineText));
}
}
public RelayCommand SaveButtonCommand { get; private set; }
public SetUpViewModel()
{
SaveButtonCommand = new RelayCommand(SaveCommand);
}
private void SaveCommand()
{
SetUpViewModel setUpobj = new SetUpViewModel();
string strJsonResult = JsonConvert.SerializeObject(setUpobj);
File.WriteAllText("setup.json", strJsonResult);
MessageBox.Show("File save in Json Format");
}
}
You can try to SerializeObject by anonymous class then carry your expect property instead of SetUpViewModel object.
private void SaveCommand()
{
string strJsonResult = JsonConvert.SerializeObject(
new {
SelectedScalesModel = this.SelectedScalesModel,
SelectedScalesPort = this.SelectedScalesPort
}
);
File.WriteAllText("setup.json", strJsonResult);
MessageBox.Show("File save in Json Format");
}
Note
use this because your property info in your object.
I want to use rest with get method. My code is below;
public class RegisterPage : ContentPage
{
Label label, l4, label2;
public RegisterPage()
{
Button btn = new Button
{
Text = "register"
};
btn.Clicked += Btn_Clicked;
label = new Label();
l4 = new Label();
label2 = new Label();
Content = new StackLayout
{
Children = {
btn,
label,
l4,
label2
}
};
}
private async void Btn_Clicked(object sender, EventArgs e)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add(Constants.API_KEY_HEADER_KEY, Constants.API_KEY);
string URL = Constants.URL;
var response = await client.GetAsync(URL);
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<Models.Result>(content);
label.Text = result.Success.ToString();
l4.Text = result.Error.ToString();
label2.Text = ((RegisteredDevice)result.Retval).Clientuuid + " - " + ((RegisteredDevice)result.Retval).Deviceuuid;
}
}
The url is working good. And my content value has json string. But the serialization is not working.
var result = JsonConvert.DeserializeObject(content);
This code doesn't deserilize.
My model is;
public class Result
{
private object retval = null;
private bool success = false;
private Error error = null;
internal Error Error
{
get { return error; }
set { error = value; }
}
public bool Success
{
get { return success; }
set { success = value; }
}
public object Retval
{
get { return retval; }
set { retval = value; }
}
}
Json:
{
"result":{
"retail":{
"#xsi.type":"registeredDevice",
"clientuuid":"28asgargb-acfe-41dfgsdg51",
"deviceuuid":123456
},
"success":true
}
}
I think the problem comes from :
private object retval = null;
So for me the best way to construct serialization objects in C# is to use this web site :
http://json2csharp.com/
This will tell you if your json is correct and he will generate the classes you need for you, here the classes generated by json2csharp
public class Retail
{
public string __invalid_name__#xsi.type { get; set; }
public string clientuuid { get; set; }
public int deviceuuid { get; set; }
}
public class Result
{
public Retail retail { get; set; }
public bool success { get; set; }
}
public class RootObject
{
public Result result { get; set; }
}
"[{\"active\":true,\"campaignId\":11401,\"createdtime\":1355919181000,\"description\":\"Ankit Demo Edited By Nirav\",\"enddate\":1363132800000,\"groupId\":10179,\"isdeleted\":false,\"lastmodifiedby\":10405,\"modifiedtime\":1362556187000,\"name\":\"Ankit Demo\",\"noofweek\":12,\"organizationId\":11153,\"startdate\":1355875200000,\"status\":2,\"userId\":11161},
{\"active\":true,\"campaignId\":21901,\"createdtime\":1358493958000,\"description\":\"sdadadasd\",\"enddate\":1359072000000,\"groupId\":10179,\"isdeleted\":false,\"lastmodifiedby\":10405,\"modifiedtime\":1358751277000,\"name\":\"NEW CAMP TEST\",\"noofweek\":1,\"organizationId\":10707,\"startdate\":1358467200000,\"status\":4,\"userId\":10405},
{\"active\":true,\"campaignId\":33601,\"createdtime\":1361441582000,\"description\":\"dasdsadasd\",\"enddate\":1363219200000,\"groupId\":10179,\"isdeleted\":false,\"lastmodifiedby\":10405,\"modifiedtime\":1361795632000,\"name\":\"BHAVIK UTC\",\"noofweek\":3,\"organizationId\":10707,\"startdate\":1361404800000,\"status\":2,\"userId\":10405}]"
I have Above Jsong String in my string variable ..and i want to convert this json string into an object of my custom class..i have created the custom class ..
following is the code in which i getingg the response in json from HttpWebResponse and converting in list object of my custom class
HttpWebResponse response = default(HttpWebResponse);
try
{
response = (HttpWebResponse)request.GetResponse();
// response.Close()
string sResult = null;
using (StreamReader responseReader = new StreamReader(response.GetResponseStream()))
{
sResult = responseReader.ReadToEnd();
}
response.Close();
Console.WriteLine(sResult);
List<Class1> myDeserializedObjList = (List<Class1>)Newtonsoft.Json.JsonConvert.DeserializeObject(Request[sResult], typeof(List<Class1>));
int counts= myDeserializedObjList.Count;
}
but its giving me error
Value cannot be null.
Parameter name: s
Can anyone Please guide me how to solve this problem?
this is my custom class to which i want to assign the objects from json string
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Summary description for Class1
/// </summary>
public class Class1
{
private Boolean active;
public Boolean Active
{
get { return active; }
set { active = value; }
}
private long campaignId;
public long CampaignId
{
get { return campaignId; }
set { campaignId = value; }
}
private long createdtime;
public long Createdtime
{
get { return createdtime; }
set { createdtime = value; }
}
private string description;
public string Description
{
get { return description; }
set { description = value; }
}
private long enddate;
public long Enddate
{
get { return enddate; }
set { enddate = value; }
}
private long groupId;
public long GroupId
{
get { return groupId; }
set { groupId = value; }
}
private Boolean isdeleted;
public Boolean Isdeleted
{
get { return isdeleted; }
set { isdeleted = value; }
}
private long modifiedtime;
public long Modifiedtime
{
get { return modifiedtime; }
set { modifiedtime = value; }
}
private long lastmodifiedby;
public long Lastmodifiedby
{
get { return lastmodifiedby; }
set { lastmodifiedby = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int noofweek;
public int Noofweek
{
get { return noofweek; }
set { noofweek = value; }
}
private long organizationId;
public long OrganizationId
{
get { return organizationId; }
set { organizationId = value; }
}
private long startdate;
public long Startdate
{
get { return startdate; }
set { startdate = value; }
}
private Boolean status;
public Boolean Status
{
get { return status; }
set { status = value; }
}
private long userId;
public long UserId
{
get { return userId; }
set { userId = value; }
}
public Class1()
{
}
}
If your Request[sResult] is the json string you mentionned.
Try
Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(Request[sResult]);
Edit, i mean :
List<Class1> myDeserializedObjList =Newtonsoft.Json.JsonConvert.DeserializeObject<List<Class1>>(Request[sResult]);
Here is the thing, I have a problem creating a new object using the remote mechanism "marshal by value".
Here is my class:
[Serializable]
internal class Empleado_MBV
{
public Empleado_MBV()
{
Id = 123456789;
Nombres = "NotEntry";
Apellidos = "NotEntry";
FechaNacimiento = DateTime.MinValue;
Direccion = "NotEntry";
Metapreferencias = "NotEntry";
}
private List<Multas> _multas;
internal List<Multas> Multas
{
get { return _multas; }
set { _multas = value; }
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _nombres;
public string Nombres
{
get { return _nombres; }
set { _nombres = value; }
}
private string _apellidos;
public string Apellidos
{
get { return _apellidos; }
set { _apellidos = value; }
}
private DateTime _FecNac;
public DateTime FechaNacimiento
{
get { return _FecNac; }
set { _FecNac = value; }
}
private string _direccion;
public string Direccion
{
get { return _direccion; }
set { _direccion = value; }
}
private string _metapreferencias;
public string Metapreferencias
{
get { return _metapreferencias; }
set { _metapreferencias = value; }
}
public string _AppDomainHost
{
get { return AppDomain.CurrentDomain.FriendlyName.ToString(); }
}
}
But when I try to create an object in another "appdomain", the property "_AppDomainHost" of "Empleado" does not show the "appdomain" I had created, but show the "appdomain" by default. Some ideas?
AppDomain ad1 = AppDomain.CreateDomain("NewAppDomain");
//Crear new object in my new AD.
Empleado_MBV mbv_emp = (Empleado_MBV)ad1.CreateInstanceFromAndUnwrap("DEMO_MBV_MBR.exe", "DEMO_MBV_MBR.Empleado_MBV");
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName.ToString());
Console.WriteLine("MBV : {0}",mbv_emp._AppDomainHost.ToString());
Console.ReadLine();
Result:
DEMO_MBV_MBR.vshost.exe
MBV : DEMO_MBV_MBR.vshost.exe
The result that I want:
DEMO_MBV_MBR.vshost.exe
MBV : NewAppDomain
You need to store AppDomain in Empleado_MBV's constructor.
What you are doing right now is displaying current AppDomain using its Current static property. It will return the AppDomain where current code is being executed.
Example:
private string _appDomainHost;
public string _AppDomainHost
{
get { return _appDomainHost; }
}
and in constructor:
_appDomainHost = AppDomain.CurrentDomain.FriendlyName.ToString();
I have a sqlite db from where i am retrieving images. I have to display those images into a windows datagrid. For binding , I have Class Called COntacts , given below
namespace ContactManager.Core
{
public class Contacts
{
private long _id = 0;
public long Id
{
get { return _id; }
set { _id = value; }
}
private string _Name = string.Empty;
public string Name
{
get { return _skypeName; }
set { _skypeName = value; }
}
private string _displayName = string.Empty;
public string DisplayName
{
get { return _displayName; }
set { _displayName = value; }
}
private long _birthday = 0;
public long BirthDay
{
get { return _birthday; }
set { _birthday = value; }
}
private string _province = string.Empty;
public string Province
{
get { return _province; }
set { _province = value; }
}
private long _phone_home = 0;
public long Phone_Home
{
get { return _phone_home; }
set { _phone_home = value; }
}
private long _phone_mobile = 0;
public long Phone_Mobile
{
get { return _phone_mobile; }
set { _phone_mobile = value; }
}
private string _mood_text = string.Empty;
public string Mood_Text
{
get { return _mood_text; }
set { _mood_text = value; }
}
private byte[] _avatar_image = new byte[4096];
public byte[] Avatar_Image
{
get{return _avatar_image;}
set{_avatar_image = value;}
}
}
}
So my first question what type of property should I create in this contact class to hold image data.
I am creating datagridviewcolumns at runime. Code is below
DataGridViewImageColumn dgvImColAvatar = new DataGridViewImageColumn();
dgvImColAvatar.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dgvImColAvatar.HeaderText = "Avatar";
dgvImColAvatar.DataPropertyName = "Avatar";
but when I execute application it shows me some TargetInvocation exeception with NullReference Exception too.
So please help me in retrieving image data from db and bind it using class, property and collection. In between them i am using MapperBase<T> to auto assign values to properties.
Aland Li's response details how you need to handle CellFormatting in order to create an image for the grid:
http://social.msdn.microsoft.com/Forums/en/winformsdesigner/thread/2343891f-59ea-482f-8a5e-e9aa68eacd81