Error when trying to retrieve from database - c#

I have generated three classes from XSD schema:
public partial class PathDetailsMessage {
private MessageHeader messageHeaderField;
public MessageHeader MessageHeader {
get {
return this.messageHeaderField;
}
set {
this.messageHeaderField = value;
}
}
}
public partial class MessageHeader {
private Recipient recipientField;
public Recipient Recipient {
get {
return this.recipientField;
}
set {
this.recipientField = value;
}
}
}
public partial class Recipient {
private string valueField;
public string Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
When I try to put the value of id (which is a char in database) to medusa.MessageHeader.Recipient.Value, I get an error (see below):
if (dr.HasRows)
{
dr.Read();
medusa.MessageHeader.Recipient.Value = Convert.ToString(dr["id"]);
dr.Close();
}
I get the following error:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
PathDetailsMessage.MessageHeader.get returned null.
I use the following SQL string:
string sqlString = "SELECT id FROM view_otf WHERE id LIKE '%079%'";
id column is CHAR in database.
I can't figure out a solution for this issue.
Can you help me?
Thank you.
LE: Those 3 classes are in the same .cs file.
LE2: medusa is an object initialized from the PathDetailsMessage.cs file, class that was created from XSD schema
PathDetailsMessage medusa = new PathDetailsMessage();

We are missing the medusa initialization code, but you should do something like this:
medusa.MessageHeader = new MessageHeader {
Recipient = new Recipient()
};
medusa.MessageHeader.Recipient.Value = Convert.ToString(dr["id"]);
That is because the initialization of a class like PathDetailsMessage will set no value to the MessageHeader property which will be null. The same applies to the Recipient property. So with the above initialization, you'll have some object to store the value.

Related

Unable Deserialize the JSON List into List of Objects in C#

I am currently working on a solution that Deserializes the list of email from json array, Once I get the list of email objects, I am validating using another class then set into another list.
Below is the code for Deserialize:
static void Main(string[] args)
{
string jsonTest = "{\"Emails\":[\"testUser#gmail.com\",\"testUser2#gmail.com\"]}";
Class1 contact = JsonConvert.DeserializeObject<Class1>(jsonTest);
Console.WriteLine(contact.Emails[0]);
Console.WriteLine(contact.Emails[1]);
}
And, below is the class definition for Class1 for deserialize:
public class Class1
{
private readonly List<ValidateEmail> emailsobj;
public List<string> Emails
{
get
{
return emailsobj.Select(o => o.EmailAdd).ToList();
}
set
{
foreach (string email in value)
{
emailsobj.Add(new ValidateEmail(email));
}
}
}
}
And, below is the validate class:
public class ValidateEmail
{
public string EmailAdd { get; set; }
private bool Valid;
public ValidateEmail(string value)
{
try
{
MailAddress mail = new MailAddress(EmailAdd);
EmailAdd = value;
Valid = true;
}
catch (FormatException)
{
Valid = false;
}
}
}
Whenever I deserialize I am getting exception on line :
Console.WriteLine(contact.Emails[0]);
Newtonsoft.Json.JsonSerializationException: Error getting value from
'Emails' on 'JsonGenerator.Class1'. ---> System.ArgumentNullException:
Value cannot be null. (Parameter 'source')
It looks like the List<Email> never set. Any help on this, it would be much appreciated.
You have to set the below setting(Replace) if you are using Lists - ObjectCreationHandling.
Replace Always create new objects and enables the setter property for the Lists!
So after you initialize the new list in Class1 like below:
private readonly List<ValidateEmail> emailsobj = new List<ValidateEmail>();
Change the code to have setting:
var settings = new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
};
Class1 contact = JsonConvert.DeserializeObject<Class1>(jsonTest, settings);
See the detailed explanation here !

Pass properties from array to a new class

i am working with a .net application where i have a web service that returns values in array form and now this array values i want to pass to a class and also as a reference to a private object. But since i am fresh new in programming i do not know how where an with what logic to start.
This is the private obj i created and i want to pass those references where CT is the array type and clsIn is the info that comes from another class but i have no idea how to pass neither of them.
private object TotInfo(clsIn In, CT ct)
{
TotInfo objFromCD = new TotInfo();
return objFromCD;
}
And here is the new class i have created that where i want to pass all the values from clsIn and CT:
public class TotInfo
{
// Object properties
private string LAST_OFFER;
private string LAST_OFFER_DATE;
private string CLOSING_REASON;
private string _NO;
private string _STATUS;
#region "GET/SET Property"
public string NO
{
get { return _NO; }
set { _NO = value; }
}
public string LAST_OFFER
{
get { return _LAST_OFFER; }
set { _LAST_OFFER = value; }
}
public string LAST_OFFER_DATE
{
get { return _LAST_OFFER_DATE; }
set { _LAST_OFFER_DATE = value; }
}
public string CLOSING_REASON
{
get { return _CLOSING_REASON; }
set { _CLOSING_REASON = value; }
}
public string STATUS
{
get { return _STATUS; }
set { _STATUS = value; }
}
#endregion
#region "Costruttori"
public CardsTotInfo() { }
public CardsTotInfo(string No, string lastOffer, string lastOfferDate, string closingReason, string status)
{
this.NO = No;
this.LAST_OFFER = lastOffer.ToUpper();
this.LAST_OFFER_DATE = lastOfferDate.ToUpper();
this.CLOSING_REASON = closingReason.ToUpper();
this.STATUS = status.ToUpper();
}
}
I have passed, or better say i think i have passed in the correct way the values of clsIn but i do not know how to pass the properties of the array type CT[].
I really need help.
Thank you in advance.
If CT is an object array and the data you get from the web service always comes in the same order, for instance using an arbitrary example:
object[] CT = { 1, DateTime.Now, "foo", true }
If you know that each property data inside the array will always be at the same index (you will always have a int in index 0 representing an Id, and a DateTime on index 1 representing the last offer day and so on)
I would say you need to set each property "manually":
private object TotInfo(clsIn In, CT ct)
{
TotInfo objFromCD = new TotInfo();
//get data from DB
//set the data from the array into the class properties
objFromCD.Id = (int)ct[0];
objFromCD.LastOfferDate = (DateTime)ct[1];
objFromCD.ClosingReason = (string)ct[2];
objFromCD.Available = (bool)ct[3];
return objFromCD;
}

Get Nvarchar length in Database From Class

I have Class use as Table in SQL server
Then properties below
[Column(Storage = "_new_name", DbType = "nvarchar (2000)")]
public string new_name { get { return _new_name; } set { _new_name = value; } }
So. Can I get Length From my Class using C#
In this case It's 2000
Thank
You can't easily, without resorting to Reflection. Attributes are meta-data, so they only decorate code with additional information required for various processes. In your case, for your ORM to identify which property maps to which column.
Assuming you have a class like this:
public class TestTable
{
private string _new_name;
private string _address;
[Column(Storage = "_new_name", DbType = "nvarchar (2000)")]
public string new_name {
get
{
return _new_name;
}
set
{
_new_name = value;
}
}
[Column(Storage = "_address", DbType = "nvarchar (5000)")]
public string address {
get
{
return _address;
}
set
{
_address = value;
}
}
}
You can read the attribute values from the properties like this:
var properties = typeof(TestTable).GetProperties();
var attributesPerProperty = new Dictionary<string, string>();
foreach (var propertyInfo in properties)
{
var attribute = System.Attribute.GetCustomAttributes(propertyInfo).FirstOrDefault();
if(attribute is ColumnAttribute)
{
var columnAttribute = (ColumnAttribute)attribute;
attributesPerProperty.Add(propertyInfo.Name, columnAttribute.DbType);
}
}
It's not an ideal way of doing things, and I've just given a rough example but if you really, really need to read this kind of information from your classes, the above will get you there.

Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''

I've been searching for the past 4 hours for ways on how to tackle this problem, and I've not yet found a solution.
I'm building an API with .NET and wish to parse JSON information that is sent back from API calls.
My current approach does the following:
private void PostNewPlayer(HttpContext context)
{
// Create the serializer
context.Request.InputStream.Position = 0;
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(ASPlayer));
ASPlayer p = (ASPlayer)json.ReadObject(context.Request.InputStream); <-- Exception here
Int32 playerId = ASPlayerManager.InsertNewPlayer(p);
}
But I currently get an Exception at the indicated line. I have made sure my class implements the correct serialization namespaces:
using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;
The class I am trying to serialize has had its DataContract and Member fields set accordingly:
[DataContract]
public class ASPlayer
{
[DataMember]
private string _name;
public string player_name
{
get { return _name; }
set { _name = value; }
}
[DataMember]
private string _location;
public string player_location
{
get { return _location; }
set { _location = value; }
}
// Other vars
...
public ASPlayer(string name, string location)
{
_name = name;
_location = location;
}
}
However, when I use a HTTP client such as Postman to make a request I get the error stated in the question title
I think you marked the wrong variables, this:
[DataMember]
private string _name;
public string player_name
should be this:
private string _name;
[DataMember]
public string player_name
The answer was a very bad mistake on my behalf, but for those who encounter this in future make sure you send your JSON object in Postman through the Raw field. In my case I simply did:
{
"player_name": "Test",
"player_location": "EUW",
"player_wins":10,
"player_draws":10,
"player_losses":15,
"player_points":20
}
This fixed it

C# get, set properties

I have the following code:
private void button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1("ttt");
myClass.Name = "xxx";
MessageBox.Show(myClass.Name);
}
and
class Class1
{
string str = "";
public Class1(string name)
{
str = name;
}
public string Name
{
get { return str; }
set;
}
}
Initially I set:
myClass.Name = "ccc";
but later changed it to:
myClass.Name = "xxx";
and also changed:
set {str = value;}
to:
set;
Why when I run it do I get "ccc" instead of "xxx" ?
In my current code there is "ccc".
public string Name
{
get { return str; }
set;
}
should be
public string Name
{
get { return str; }
set { str = value; }
}
Change your Name property as follows:
public string Name
{
get { return str; }
set { str = value; }
}
To answer your question, the reason why you get "ccc" instead of "xxx" is that you have compile errors. When you run your application it will ask you if you want to run the latest known working configuration. The last time your program did compile, you used "ccc" as literal, and that is what is still running.
Fix the compile errors and run it again, and then it will be "xxx"
The pattern
public string Name {get;set;}
is what is called "Auto-Implemented Properties".
The compilier creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
What you original code seems to be doing is get on a field you defined but a set on the anonymous backing field. Therefore build error ...

Categories

Resources