Json.net reading serialized array - c#

I am trying to read JSON data from web, and i am using Json.net library for this task, the problem is if there is only one json object
{"id":"2340","time":"2014-10-29 16:26:49"}
everything works fine, but if there is an array of them
[{"id":"2340","time":"2014-10-29 16:26:49"}, {"id":"2341","time":"2014-10-29 16:27:21"}]
Program isn't working.
using System;
using System.Net;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Collections.Specialized;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace Localhostnet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
using (WebClient client = new WebClient())
{
string htmlCode = client.DownloadString('http://localhost/json.php');
LocalhostTiming jsonResponse = JsonConvert.DeserializeObject<LocalhostTiming>(htmlCode);
string timeId = jsonResponse.id;
MessageBox.Show(timeId);
}
}
}
public class LocalhostTiming
{
public string id { get; set; }
public string time { get; set; }
}
}
I've tried to add
public class DataContainer
{
public List<LocalhostTiming> LocalhostTiming{ get; set; }
}
But i dont know how to work with this code.

You are trying to deserialize an array of LocalhostTiming into one instance of it.
You need to deserialize the object to an array.
List<LocalhostTiming> jsonResponse = JsonConvert.DeserializeObject<List<LocalhostTiming>>(htmlCode);

Related

Create an instance of a class from another package

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace assign_5.model
{
class Person
{
public void t()
{
Console.WriteLine("try");
}
public string h()
{
return "ll";
}
}
}
using assign_5.model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace assign_5.Controller
{
class FirstNameController
{
Person p = new Person();
p.t();
string o = p.h();
}}
Why there is an error in p.t(); and string o = p.h();
"Error CS0236 A field initializer cannot reference the non-static field, method, or property 'FirstNameController.p' assign_5 "
You need move your code to a method in class, also make class Person as public to accessable from another namespace as
public class Person{}
class FirstNameController
{
void test(){
Person p = new Person();
p.t();
string o = p.h();
}
}

Change button background image using method in Winforms

My code for Form
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace YAHTZEE
{
public partial class GameMainWindow : Form
{
public GameMainWindow()
{
InitializeComponent();
}
private void buttonRollDice_Click(object sender, EventArgs e)
{
DiceManager dm = new DiceManager();
dm.intDice_1_Roll();
dm.intDice_2_Roll();
dm.intDice_3_Roll();
dm.intDice_4_Roll();
dm.intDice_5_Roll();
Class1 c1 = new Class1();
c1.buttonDice_1Manager();
}
}
}
My class for generating random number for all the dice.
This works perfectly fine.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace YAHTZEE
{
public class DiceManager
{
Random rnd = new Random();
public int intDice_1_Roll()
{
int intDice_1 = rnd.Next(1, 7);
return intDice_1;
}
public int intDice_2_Roll()
{
int intDice_2 = rnd.Next(1, 7);
return intDice_2;
}
public int intDice_3_Roll()
{
int intDice_3 = rnd.Next(1, 7);
return intDice_3;
}
public int intDice_4_Roll()
{
int intDice_4 = rnd.Next(1, 7);
return intDice_4;
}
public int intDice_5_Roll()
{
int intDice_5 = rnd.Next(1, 7);
return intDice_5;
}
}
}
Class to change button background image.
This is where my problem is, the code works if I put it on my form but it does nothing when I make it a method on another class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YAHTZEE.Properties;
namespace YAHTZEE
{
class Class1 : GameMainWindow
{
public void buttonDice_1Manager()
{
DiceManager dm = new DiceManager();
if (dm.intDice_1_Roll() == 1)
{
buttonDice_1.BackgroundImage = Properties.Resources.Dice1;
}
}
}
}
Am I missing something?
P.S. I want them to be separated because there are a lot of things to consider making my code very long.
In class1, try changing your method to:
public System.Drawing.Bitmap dice1Manager(int diceRoll)
{
if(diceRoll == 1)
return Properties.Resources.Dice1;
}
In your main class, change what you have to:
private void buttonRollDice_Click(object sender, EventArgs e)
{
DiceManager dm = new DiceManager();
Class1 c1 = new Class1();
button_dice1.BackgroundImage = c1.dice1Manager(dm.intDice_1_Roll());
dm.intDice_2_Roll();
dm.intDice_3_Roll();
dm.intDice_4_Roll();
dm.intDice_5_Roll();
}

Writing form state to xml C#

My aim is to save the all form data via button click (as opposed to upon closing). To that end, I've used the example given in the following thread. Saving the form state then opening it back up in the same state
I've tried to adapt my code to the best of my ability, but nothing happens, and there are no errors shown. What am I doing wrong?
Here's the relevant parts of my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace WindowsFormsApplication1
{
public partial class frmPayroll : Form
{
SaveData sd = new SaveData();
public frmPayroll()
{
InitializeComponent();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
writeConfig();
}
private void writeConfig()
{
using (StreamWriter sw = new StreamWriter("config.xml"))
{
sd.Married = rdoMarr.Checked;
sd.PayPd = cbPayPd.Text;
sd.Allow = cbAllow.Text;
sd.Gross = txtGross.Text;
sd.Fit = txtFit.Text;
sd.Soc = txtSoc.Text;
sd.Med = txtMed.Text;
sd.NetPay = txtNet.Text;
sd.PayPd = cbPayPd.Text;
XmlSerializer ser = new XmlSerializer(typeof(SaveData));
ser.Serialize(sw, sd);
}
}
private void frmPayroll_Load(object sender, EventArgs e)
{
if (File.Exists("config.xml"))
{
loadConfig();
}
sd.Married = rdoMarr.Checked;
sd.PayPd = cbPayPd.Text;
sd.Allow = cbAllow.Text;
sd.Gross = txtGross.Text;
sd.Fit = txtFit.Text;
sd.Soc = txtSoc.Text;
sd.Med = txtMed.Text;
sd.NetPay = txtNet.Text;
}
private void loadConfig()
{
XmlSerializer ser = new XmlSerializer(typeof(SaveData));
using (FileStream fs = File.OpenRead("config.xml"))
{
sd = (SaveData)ser.Deserialize(fs);
}
}
}
public struct SaveData
{
public bool Married;
public string PayPd;
public string Allow;
public string Gross;
public string Fit;
public string Soc;
public string Med;
public string NetPay;
}
}
You are loading your object by deserializing.
But Where are you assigning the states back to your controls?
look at frmPayroll_Load function.
You are trying to assign the data back to the object again.
You have to assign data back to form controls.
Should be something like this (you may need to apply data conversions if required):
rdoMarr.Checked = sd.Married;
.
.
.
.
txtFit.Text = sd.Fit;
.
.
.
.

want to access data from text box in the form which is in another solution in visual studio 2013?

I have two solutions TranferService and Sender. TranferService has WCF service and IISHost to host that service. In Sender solution i have windows forms application. In that form i used button to browse and select file, text box to display selected file path, and another button(Send) to transfer that file through WCF service. But i am unable to access textbox value in the transfer solution. it shows"the name does not exist in the current context".
Code for TransferService
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace TransferService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "TransferService" in both code and config file together.
public class TransferService : ITransferService
{
public File DownloadDocument()
{
File file = new File();
String path = txtSelectFilePath.Text;
file.Content = System.IO.File.ReadAllBytes(#path);
//file.Name = "ImagingDevices.exe";
return file;
}
}
}
I am getting error on this line
String path = txtSelectFilePath.Text;
code for form.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sender
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Browse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
txtSelectFilePath.Text = openFileDialog1.FileName;
}
}
private void Send_Click(object sender, EventArgs e)
{
TransferService.TransferServiceClient client = new TransferService.TransferServiceClient();
TransferService.File file = client.DownloadDocument();
System.IO.File.WriteAllBytes(#"C:\DownloadedFiles\" + file.Name, file.Content);
MessageBox.Show(file.Name + " is downloaded");
}
}
}
Code for ITransferService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace TransferService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ITransferService" in both code and config file together.
[ServiceContract]
public interface ITransferService
{
[OperationContract]
File DownloadDocument();
}
[DataContract]
public class File
{
[DataMember]
public string Name { get; set; }
[DataMember]
public byte[] Content { get; set; }
}
}
Thanx a lot in advance..........
Then create a constructor to your class that receives a path as string something like this:
public class TransferService : ITransferService
{
private string _path;
public TransferService(string path) {
_path = path
}
public File DownloadDocument()
{
File file = new File();
//String path = txtSelectFilePath.Text;
file.Content = System.IO.File.ReadAllBytes(_path);
//file.Name = "ImagingDevices.exe";
return file;
}
}
and then on form.cs
TransferService.TransferServiceClient client = new TransferService.TransferServiceClient(txtSelectFilePath.Text);

using variables from another file .cs

I have a project in c# winforms, with a file called: PublicSettings.cs (this file is within a folder called: Class) where I have a variable.
Now, I want to use that variable from another file within the same project.
PublicSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LVSetup.Class
{
class PublicSettings
{
private string _ConnStr = "Connection";
public string ConnStr
{
get
{
return this._ConnStr;
}
set
{
this._ConnStr = value;
}
}
}
}
I want to use the variable ConnStr in the file: frmLogin.cs
frmLogin.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LVSetup.Class;
namespace LVSetup
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}
private void btnEnter_Click(object sender, EventArgs e)
{
string a = PublicSettings.ConnStr;
}
}
}
But there is no ConnStr within PublicSettings, just (Equals and ReferenceEquals)
What could be wrong here?
You need to make this field static in order to access it without creating a class instance. Or create and instance. What suites the best depends on the logic that you want to apply for this class and how it will be used later.
Instance approach
private void btnEnter_Click(object sender, EventArgs e)
{
var settings = new PublicSettings();
string a = settings.ConnStr;
}
Static field approach
class PublicSettings
{
private static string _ConnStr = "Connection";
public static string ConnStr
{
get
{
return _ConnStr;
}
set
{
_ConnStr = value;
}
}
}
For a connection string, I would either use a Configuration file (app.config) or make the property a static read-only property (since there's often no reason to change a connection string at run-time):
class PublicSettings
{
public static string ConnStr
{
get
{
return "Connection";
}
}
}

Categories

Resources