Why do non-null XElements cause an NRE? [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Why is my extension method GetVendorForXMLElement() erupting in an NRE when I pass it XElements with data?
The same code (except for the custom class used, which here is "Vendor") works with other classes/data, but not here. I get an NRE in the GetVendorForXMLElement() method.
private void buttonVendors_Click(object sender, EventArgs e)
{
IEnumerable<Vendor> vendors = GetCollectionOfVendors();
}
private IEnumerable<Vendor> GetCollectionOfVendors()
{
ArrayList arrList = FetchDataFromServer("http://localhost:21608/api/vendor/getall/dbill/ppus/42");
String contents = "<Vendors>";
foreach (String s in arrList)
{
contents += s;
}
contents += "</Vendors>";
String unwantedPreamble = "<ArrayOfVendor xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/CStore.DomainModels.HHS\">";
contents = contents.Replace(unwantedPreamble, String.Empty);
contents = contents.Replace("</ArrayOfVendor>", String.Empty);
MessageBox.Show(contents);
XDocument xmlDoc = XDocument.Parse(contents);
// The result (NRE) is the same with any one of these three "styles" of calling Select()
//IEnumerable<Vendor> vendors = xmlDoc.Descendants("Vendor").Select(GetVendorForXMLElement).ToList();
//IEnumerable<Vendor> vendors = xmlDoc.Descendants("Vendor").Select(x => GetVendorForXMLElement(x));
IEnumerable<Vendor> vendors = xmlDoc.Descendants("Vendor").Select<XElement, Vendor>(GetVendorForXMLElement);
return vendors;
}
private static Vendor GetVendorForXMLElement(XElement vendor)
{
return new Vendor
{
CompanyName = vendor.Element("CompanyName").Value,
VendorID = vendor.Element("VendorID").Value
};
}
public class Vendor
{
public String CompanyName { get; set; }
public String VendorID { get; set; }
public String siteNum { get; set; }
}
There is data; this is what I see with the MessageBox.Show() call prior to the XDocument.Parse() call:
Regardless of which of the three types of calls to "Select(GetVendorForXMLElement)" I use, the NRE occurs. Is it the angle brackets in the CompanyName element ("[blank]")? Or...???

Your element has a VendorId element, not a VendorID element (notice the casing), Element("VendorID") therefore returns null, and calling Value on that throws an NRE.

Related

c# new object(data) always creates empty objects [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I'm fairly new to c# and I'm trying to create a custom object, but they always seem to be empty.
public class Item
{
public string itemName {get;set;}
public int itemAmount {get;set;}
public Item (string name, int amount)
{
name = itemName;
amount = itemAmount;
}
}
public class Backpack : MonoBehaviour
{
void Start()
{
Item gold = new Item ("gold", 5)
}
}
When I try to get gold parameters I get null, 0. Should it work like that? I wanted to use it to quickly add items to a list, and right now I would have to change all of them manually with something like
gold.itemName = "gold"; gold.itemAmount = 5.
Can I do it in another way?
Your assignment in the constructor is the wrong way around, instead it should be:
public Item (string name, int amount)
{
itemName = name;
itemAmount = amount;
}

global array won't read in to console window c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
Schedule.cs
public static class SchArray
{
public static string[] clientName = new string[20];
public static DateTime[] startDate = new DateTime[20];
public static DateTime[] endDate = new DateTime[20];
public static string[] allocatedDriver = new string[20];
public static string[] depot = new string[20];
public static int count = 3;
}
public void schedule()
{
SchArray.clientName[0] = "eric cartman";
SchArray.clientName[1] = "peter griffin";
SchArray.clientName[2] = "homer simpson";
SchArray.startDate[0] = Convert.ToDateTime("2016,3,2");
SchArray.startDate[1] = Convert.ToDateTime("2016,3,4");
SchArray.startDate[2] = Convert.ToDateTime("2016,3,5");
SchArray.endDate[0] = Convert.ToDateTime("2016,3,3");
SchArray.endDate[1] = Convert.ToDateTime("2016,3,5");
SchArray.endDate[2] = Convert.ToDateTime("2016,3,6");
SchArray.allocatedDriver[0] = "owen";
SchArray.allocatedDriver[1] = "daniel";
SchArray.allocatedDriver[2] = "owen";
SchArray.depot[0] = "depot1";
SchArray.depot[1] = "depot2";
SchArray.depot[2] = "depot3";
}
Work_Schedule.cs
public void schedule()
{
Console.Clear();
Console.WriteLine(" Create Work Schedule ");
Console.WriteLine(Schedule.SchArray.clientName[0]);
Console.ReadKey();
}
Console.WriteLine(Schedule.SchArray.clientName[0]);
^^^^^ this line should display the name the eric cartman, i've debugged it and it says there are no objects in the array, they're are all null.
You need to create an object of Schedule since the array elements ware initialized inside the constructor:
Schedule scheduleObject = new Schedule();
Console.WriteLine(SchArray.clientName[0]);
For this particular scenario, i would like to suggest a different approach of creating a static list/array of objects. Let me modify the class as like the following:
public class SchArray
{
public string clientName;
public DateTime startDate;
public DateTime endDate;
public string allocatedDriver;
public string depot;
public int count = 3;
}
And i have a List<SchArray> defined as static;
public static List<SchArray> StaticSchArray = new List<SchArray>();
Then i can populate the list as like the following:
StaticSchArray.Add(new SchArray() {clientName="eric cartman",
startDate=Convert.ToDateTime("2016,3,2"),
endDate= Convert.ToDateTime("2016,3,2"),
depot="depot1",allocatedDriver ="owen" });
Similarly other elements can also be added to the array. this will be a better option for this scenario.

Getting "Member names cannot be the same as their enclosing type" [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I knew constructors from Java and have now a C# project. Syntax in both languages is very similar, so I thought this shouldn't be a problem:
class ShapeItems
{
public String masterName = "";
public String stencilName = "";
public Double coordY = 0.0;
public Double coordX = 0.0;
public String shapeText = "";
public void ShapeItems(String mN, String sN, Double X, Double Y, String sT)
{
this.masterName = mN;
this.stencilName = sN;
this.coordX = X;
this.coordY = Y;
this.shapeText = sT;
}
}
But as I wrote the constructor, I received the error:
Member Names cannot be the same as their enclosing type
I've seen some others with this problems here, but the answers won't fix my problem.
Maybe someone here has a hint for me to solve this issue?
You don't have a constructor but a method: void. Remove the word void and it should work.
So
public ShapeItems(params) { }
instead of
public void ShapeItems(params) { }
Remove "void" from constructor signature:
public ShapeItems(...) { }

Framework for handling serialization in "key:value;key:value;key:value;key:value;" format [closed]

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
Of course it's easy to write the code to deserialize from this format. I've already done it, but I don't like.
The single responsibility principle states that I should have a generic class that worries only about this kind of serialization. And the task is generic enough to be coped by a framework.
If you converted it to a JSON string like (which should be easy)
var jsonArray = “[{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}]”;
then you could easily deserialize it with Json.NET into whatever you want and Json.NET takes care of converting the values to the right types for you:
MyType1[] result = JsonConvert.Deserialize<MyType1[]>(jsonArray);
MyType2[] result = JsonConvert.Deserialize<MyType2[]>(jsonArray);
public class MyType1
{
public string key { get; set; }
public string value { get; set; }
}
public class MyType2
{
public string key { get; set; }
public double value { get; set; }
}
or even just as a dictionary (I hope I have the syntax correct, I didn't test it):
var jsonDic = “{{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}}”;
var result = JsonConvert.Deserialize<Dictionary<string, string>>(jsonDic);
The single responsibility class (just as an example):
public class KeyValueParser
{
public static TResult ParseKeyValueString<TResult>(string keyValueString)
{
keyValueString = ConvertToJson(keyValueString);
TResul result = JsonConvert.DeserializeObject<TResult>(keyValueString);
return result;
}
private static string ConvertToJson(string keyValueString)
{
// convert keyValueString to json
}
}
usage
var jsonDic = “{{'key':'value'}, {'key':'value'}, {'key':'value'}, {'key':'value'}}”;
var result = KeyValueParser.ParseKeyValueString<Dictionary<string, string>>(jsonDic);
I don't really understand the question.
If it is something your program does a lot then move the function to some area that it is easy to get too (or a nuget package if a lot of your systems need it). If it happens in one place in your code put it quite close to that place.

array of pointers to objects in another class [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have to create class like DataBase that will contain menu, adding users, editing them, deleting etc.
Users are from class User.
It looks like:
class base
{
protected int mAccounts=0;
protected const int mMaxAccs=10;
osoba[] list = new osoba[mMaxAccs];
public void menu(){...}
public void add()
{
user user1("Jurand","ze Spychowa",15231512,"1410-10-26","hue#x.com");
mAccounts++;
}
... useless code there
}
then there is User class
class user
{
private string mName;
private string mSurname;
private int mPesel;
private DateTime mBDate;
private string mEmail;
osoba(string mName2, string mSurname2, string mPesel2, string mBDate2, string mEmail2)
{
mName = mName2;
mSurname = mSurname2;
mPesel = Convert.ToInt32(mPesel2);
mBDate = Convert.ToDateTime(mBDate2);
mEmail = mEmail2;
}
The problem is adding new accounts. I totally don't know how to make it working
So the users will be stored in base class and you will have access to edit and add them etc.
Anyone know how to make it working (Creating objects properly)?
I suggest adding properties to User class:
class User
{
public string mName { get; private set; }
public string mSurname { get; private set; }
public int mPesel { get; private set; }
public DateTime mBDate { get; private set; }
public string mEmail { get; private set; }
//constructor for User class
public User(string mName2, string mSurname2, string mPesel2, string mBDate2, string mEmail2)
{
mName = mName2;
mSurname = mSurname2;
mPesel = Convert.ToInt32(mPesel2);
mBDate = Convert.ToDateTime(mBDate2);
mEmail = mEmail2;
}
}
and modify your add method (also changed object where you store data from array to List):
class MyDB
{
List<User> list = new List<User>();
public void add()
{
//use constructor to create new object
User person = new User("Jurand", "ze Spychowa","15231512","1410-10-26","hue#dupa.com");
//add object to list
list.Add(person);
}
}
Its not good idea to mix different languages in code so try avoiding naming objects/methods like "osoba".
You will probably benefit from reading following articles (in Polish):
C# Constructors
C# Properties
I belive that only thing that is missing in your add() method is:
osoba[mAccounts] = user1;
before mAccounts++ line.
Make fields public only if your User class is going to be stupid data object which only store data and contain no methods (maybe except formatting, converting etc.).

Categories