Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I need to access referenced classes inside a main class and insert values into the objects. The classes are of partial type.
my code:
public partial class Get_CountryInfo_Resp_object
{
public string ReturnCode { get; set; }
public string ErrorMsg { get; set; }
public string Alpha2_Code { get; set; }
public string Digit3_Code { get; set; }
public string CountryName { get; set; }
public string IBAN_Mandatory { get; set; }
public As_SenderCountry[] As_SenderCountry { get; set; }
public As_ReceiverCountry[] As_ReceiverCountry { get; set; }
}
public partial class As_SenderCountry
{
public string SenderCountry_IsSensitive { get; set; }
}
public partial class As_ReceiverCountry
{
public string ReceiverCtry_EFTNotAllowed { get; set; }
public ReceiverCtry_AllowedCCY_Item[] ReceiverCtry_AllowedCCY_List { get; set; }
}
public partial class ReceiverCtry_AllowedCCY_Item
{
public string ReceiverCtry_AllowedCCY { get; set; }
}
private static void Task2()
{
String xmlText = File.ReadAllText(#"../../XML/sample1.xml");
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(xmlText)));
DataTable dt = ds.Tables["column"];
Get_CountryInfo_Resp_object Get_CountryInfo_Resp = new Get_CountryInfo_Resp_object();
//Get_CountryInfo_Resp.As_SenderCountry;
Get_CountryInfo_Resp.ReturnCode = dt.Rows[0]["column_Text"].ToString();
Get_CountryInfo_Resp.ErrorMsg = dt.Rows[1]["column_Text"].ToString();
Get_CountryInfo_Resp.Alpha2_Code = dt.Rows[2]["column_Text"].ToString();
Get_CountryInfo_Resp.Digit3_Code = dt.Rows[3]["column_Text"].ToString();
Get_CountryInfo_Resp.CountryName = dt.Rows[4]["column_Text"].ToString();
Get_CountryInfo_Resp.IBAN_Mandatory = dt.Rows[5]["column_Text"].ToString();
//GetCountryInfo_Resp.As_SenderCountry.SenderCountry_IsSensitive
I need to Insert dt.Rows[6]["column_Text"].ToString(); into the GetCountryInfo_Resp.As_SenderCountry.SenderCountry_IsSensitive .
How shall i proceed?
Please help.
Since As_SenderCountry is an array, it can contain multiple items. You have to assign an array too, not just a single instance.
I would start to create an object, add that to a list and eventually create an array out of it (or change the type to be a list instead of an array). You can also fix-size the array if you know the length already.
As_SenderCountry asc = new As_SenderCountry();
asc.SenderCountry_IsSensitive = dt.Rows[6]["column_Text"].ToString();
And then:
GetCountryInfo_Resp.As_SenderCountry = new As_SenderCountry[] { asc };
Or create the list, loop over items and eventually assign it:
List<As_SenderCountry> list = new List<As_SenderCountry>();
// some sort of loop
As_SenderCountry asc = new As_SenderCountry();
...
list.Add(asc);
// end loop
GetCountryInfo_Resp.As_SenderCountry = list.ToArray();
I don't think I fully understand your code, but As_SenderCountry and As_ReceiverCountry in your public partial class Get_CountryInfo_Resp_object are arrays, if I am not reading it wrong.
Therefore, the messy solution, if you know there is only one sender country:
GetCountryInfo_Resp.As_SenderCountry[0].SenderCountry_IsSensitive = dt.Rows[6]["column_Text"].ToString();
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating. An example with your variables:
public partial class Get_CountryInfo_Resp_object
{
public string ReturnCode { get; set; }
...
public List<As_SenderCountry> As_SenderCountry { get; set; }
public List<As_ReceiverCountry> As_ReceiverCountry { get; set; }
}
private static void Task2()
{
String xmlText = File.ReadAllText(#"../../XML/sample1.xml");
DataSet ds = new DataSet();
ds.ReadXml(new XmlTextReader(new StringReader(xmlText)));
DataTable dt = ds.Tables["column"];
Get_CountryInfo_Resp_object Get_CountryInfo_Resp = new Get_CountryInfo_Resp_object();
...
GetCountryInfo_Resp.As_SenderCountry.SenderCountry_IsSensitive.Add(dt.Rows[6]["column_Text"].ToString());
p.s. Your variable and class naming is very messy. I would suggest you to clean that up so that you, as well as the people reading the question can understand it better.
You need to create a new instance of the inner class as you would do normally for any other class, and then assign whatever value to the field you need.
First you need to assign the length of the array, then each cell of the array will contain an instance of an object of type (As_SenderCountry ), then you should assign each object the value you need.
GetCountryInfo_Resp.As_SenderCountry = new GetCountryInfo_Resp.As_SenderCountry();
GetCountryInfo_Resp.As_SenderCountry[INDEX_HERE].SenderCountry_IsSensitive = dt.Rows[6]["column_Text"].ToString();
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
I have a class with this:
public class myDataType
{
public class GetInvoice
{
public string InvoiceID { get; set; }
public string InvoiceNumber { get; set; }
public decimal InvoiceAmount { get; set; }
public List<InvoiceRow> Rows { get; set; }
}
public class InvoiceRow
{
public decimal RowQty { get; set; }
public string RowCode { get; set; }
public string RowDescription { get; set; }
}
}
And when I want to add data has th
using static test.myDataType;
...
private void LoadData()
{
GetInvoice Invoice = new GetInvoice();
Invoice.InvoiceID = "0a8625e5-62f6-4ad7-a8bf-ab04b1158392";
Invoice.InvoiceNumber = "Inv-001";
Invoice.InvoiceAmount = 100;
Invoice.Rows.Add(new InvoiceRow { RowQty= 1, RowCode = "C100", RowDescription = "Item C100"});
}
When try to add the row:
Invoice.Rows.Add(new InvoiceRow { RowQty= 1, RowCode = "C100",
RowDescription = "Item C100"});
Show me this error "System.NullReferenceException: 'Object reference not set to an instance of an object'"
I think i have a sintax o wrong way to do it
Can someone help?
Thanks in advance
It's not a syntax error, you just haven't initialised the list.
With
public List<InvoiceRow> Rows { get; private set; }
you've declared a place to hold the list, but haven't created the list itself.
(If an analogy helps, imagine you've drawn a line on the wall of your house where you're going to put up a bookshelf, but you haven't actually screwed the shelf to the wall yet - that's the situation your code is in).
If you want the list to always be available you can either initialise it automatically through the property declaration, or in the constructor of the class. Alternatively of course you could leave the calling code to initialise it.
This version just makes it part of the property declaration:
public List<InvoiceRow> Rows { get; private set; } = new List<InvoiceRow>();
You need first to initialize list Rows before you add element to it.
For example in GetInvoice class you can add:
public List<InvoiceRow> Rows { get; set; } = new List<InvoiceRow>();
List is reference type in C# so it needs to be initialized before being used.
If you want to do that in LoadData() method you can do in this way:
private void LoadData()
{
GetInvoice Invoice = new GetInvoice();
Invoice.InvoiceID = "0a8625e5-62f6-4ad7-a8bf-ab04b1158392";
Invoice.InvoiceNumber = "Inv-001";
Invoice.InvoiceAmount = 100;
Invoice.Rows = new List<InvoiceRow>();
Invoice.Rows.Add(new InvoiceRow { RowQty = 1, RowCode = "C100", RowDescription = "Item C100" });
}
I need a clear example that shows me how to define a list that has n rows and 4 columns and how to use it. I need a list to save my data like the below image. as you see this could be a dictionary.
You need to create a class with all the above properties
public class Sample
{
public string vocabulary { get; set; }
public string meaning { get; set; }
public int number { get; set; }
public int group { get; set; }
}
and then you can create a List of type Sample,
List<Sample> yourList = new List<Sample>();
You can add items to the list as below
yourList.Add(new Sample { vocabulary = "massive", meaning = "very big", number = 5, group = 15 });
You can access them later like this, if you want the first element,
var result = yourList[0];
this is the easiest and best way of doing it. You need to create a new class and then create new instances of the class and then add it to the list and then use LINQ to get the data out
void Main()
{
var list = new List<myClass>()
list.Add(new myClass() {
Vocabluary = "Vocabluary ",
Meaning = "meaning",
Number = 1,
Group = 2})
}
public class myClass
{
public string Vocabluary { get; set; }
public string Meaning { get; set; }
public int Number { get; set; }
public int Group { get; set; }
}
yes... as Sajeetharan mentioned, with a custom class you can create an any dimensions List. but i don't think you need to think about dimension in C#... it is a bit more high level than that.
just simply create a class and put everything you need in it...
public class CustomClass{
public string d1;
public int d2;
public string d3;
public string d4;
...
//you can easily create a N dimension class
}
to access it and apply it
public void Main(){
List<CustomClass> list = new List<CustomClass>();
CustomClass cc = new CustomClass();
cc.d1 = "v1";
cc.d2 = 0; //v2
list.Add(cc);
//to access it
foreach(CustomClass tmpClass in list)
{
string d1Value = tmpClass.d1;
int d2Value = tmpClass.d2;
}
}
i have this code:
public List<CsvUserData> CsvUserList = new List<CsvUserData>();
public CsvUserData()
{
readCSV(#"C:\userdata.csv");
}
public string CSVEmailEditText { get; set; }
public string CSVNameEditText { get; set; }
public string CSVAddressEditText { get; set; }
public string CSVPostnumEditText { get; set; }
public string CSVCityEditText { get; set; }
public string CSVPhoneEditText { get; set; }
public string CSVCommentEditText { get; set; }
public string SelectPage { get; set; }
private void readCSV(string location)
{
var reader = new StreamReader(File.OpenRead(location));
string line;
string[] values;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
values = line.Split(',');
CsvUserList.Add
(
new CsvUserData
{
CSVEmailEditText = values[0],
CSVNameEditText = values[1],
CSVAddressEditText = values[2],
CSVPostnumEditText = values[3],
CSVCityEditText = values[4],
CSVPhoneEditText = values[5],
}
);
}
}
I am trying to read csv file into list that consists of objects named CsvUserData, the class definition is displayed above. Once the class is instantiated my program is getting into infinite loop eventually resulting in stackoverflow exception once the list memory is full, even though my csv file only has one row of data. Can someone help me and explain why is this happening?
Let’s see:
Create a new CsvUserData object, call the constructor.
readCSV(#"C:\userdata.csv");
Inside readCSV: Open file, and iterate over the lines.
For each line: new CsvUserData { … }
Go to 1.
So you end up creating new CsvUserData objects from within the constructor of the CsvUserData type. So this will repeat forever.
You probably meant to make the readCSV method static or something, and only call it once. There is really no reason why it should be called from the constructor. And the constructor shouldn’t really open a file and create stuff based on the file; that’s far too much work for a constructor.
I have obtained the list of data from database in the following way
List<MakerCheckerModel> mkckdata = new List<MakerCheckerModel>();
var dataContext = new PetaPoco.Database("MessageEntity");
mkckdata = dataContext.Query<MakerCheckerModel>(PetaPoco.Sql.Builder.Append("Select * from MakerChecker1")).ToList();
The data comes in mkckdata. My model is of the following way.
public class MakerCheckerModel
{
public int MakerCheckerId { get; set; }
public string OldJson { get; set; }
public string NewJson { get; set; }
public string ModelName { get; set; }
}
Now I want to put the value obtained in OldJson and NewJson of mkckdata in new List type of model variables so that I can manipulate it further.I want something like this.
List<MakerCheckerModel> oldDataList = new List<MakerCheckerModel>();
oldDataList.Add(mkckdata.OldJson));
But this is not allowed here. PLease help me how to do this.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I receive from client a raw string as this:
{ "\"wrapper\": {\"system\": { \"session\":\"ed6d1cc6-82f9-46e8-91bb-eae341a771cf\", \"ip\":\"\", \"station\":\"\"},{ \"personal_profile\": {\"suffix\":\"1096\",\"first_name\":\"Varvara\",\"middle_name\":\"\",\"last_name\":\"Terlouw\",\"street\":\"\",\"number\":\"\",\"add\":\"\",\"postal\":\"\",\"city\":\"\",\"state\":\"\",\"country\":\"\",\"birthday\":\"\",\"relation_type_id\":\"\"}},{ \"personal_contacts\": {\"contact_type_id_0\":\"409\",\"contact_0\":\"06-26096994\",\"contact_0\":\"on\"},{\"contact_type_id_0\":\"420\",\"contact_0\":\"jj#vv.com\",\"contact_0\":\"on\"},{\"contact_type_id_0\":\"\",\"contact_0\":\"\",\"contact_0\":\"on\"}},{ \"personal_work\": {}},{\"personal_connected\": {}},{\"personal_interests\": {}}}} "
I get the string in into my webservice and need to convert this to LIST<> so I can process the data to my database, preferable with my classes
here and old example of a class i used a while ago as another example for simple json serialize :
internal class CFingerPrint
{
public string WanIP;
public string MacAddress;
public string getClassEncrypted()
{
return new JavaScriptSerializer().Serialize(this);
}
public CFingerPrint getClassDecrypted(string sSerializedClass)
{
return new JavaScriptSerializer().Deserialize<CFingerPrint>(sSerializedClass);
}
}
I use the same way to communicate with other languages a lot and haven't had any issue yet except Dates that are problematic in JSON but that's another story.
Edit : example how to use :
// create new class
var originalClass = new CFingerPrint();
// fill some data
originalClass.WanIP = "test1";
originalClass.MacAddress= "test2";
// serialize to json string
var classSerialized = originalClass.getClassEncrypted();
// create new class from string only
var newClass = new CFingerPrint().getClassDecrypted(classSerialized);
Console.WriteLine(newClass.WanIP); // output "test1"
Console.WriteLine(newClass.MacAddress); // output "test2"
Example with childs :
public class Manufacturer
{
public string Name{ get; set; }
public List<Motor> AvailaibleMotors{ get; set; }
public string getClassSerialized()
{
return new JavaScriptSerializer().Serialize(this);
}
public ManufacturergetClassDeSerialized(string sSerializedClass)
{
return new JavaScriptSerializer().Deserialize<Manufacturer>(sSerializedClass);
}
}
public class Motor
{
public string Model { get; set; }
public List<Voltage> Voltages { get; set; }
}
public class Voltage
{
public int Volt { get; set; }
public int Phase { get; set; }
public int Frequency { get; set; }
}
so manufacturer can have one or many motors which can have one of many voltage and this works perfectly no matter what.
You can probably do something like this too.
public ActionResult jsonPull()
{
try
{
using (var webClient = new System.Net.WebClient())
{
webClient.Encoding = Encoding.UTF8;
var json = webClient.DownloadString("example.com/json");
var parsed = JsonConvert.DeserializeObject(json);
return Json(parsed);
}
}
catch (Exception e)
{
return Json(new { json = "error" });
}
}