This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I have a CibilResponse Class that has properties that are of class type (TUEF class). I am trying to assign value to CibilEnquiryEnq.Tuef.Version but i am getting null reference error. Before you mark this question as duplicate let me mention that I have read some of the similar questions and their answers on SO and post which I have initialized tuef in the constructor as you can see in my code. Can you please point out if you can what is it that I am doing wrong?
ICIBIL.cs
[ServiceContract]
public interface ICIBIL
{
[OperationContract]
string InsertCibil(CibilResponse cibilResponse);
[OperationContract]
string GenerateEnquiry(CibilEnquiry testObj);
}
[DataContract]
public class CibilResponse
{
[DataMember]
public string ResponseString { get; set; }
[DataMember]
public string Business { get; set; }
[DataMember]
public string MkrId { get; set; }
}
[DataContract]
public class CibilEnquiry
{
[DataMember]
public TUEF Tuef { get; set; }
public CibilEnquiry()
{
this.Tuef = new TUEF();
}
}
[DataContract]
public class TUEF
{
[DataMember]
public string SegmentTag { get; set; }
[DataMember]
public string Version { get; set; }
[DataMember]
public string MemberReferenceNumber { get; set; }
}
Appication :
CibilWcfService.CIBIL obj = new CibilWcfService.CIBIL();
CibilWcfService.CibilEnquiry CibilEnquiryEnq = new CibilWcfService.CibilEnquiry();
CibilEnquiryEnq.Tuef.Version = "123";// null reference error here
string res = obj.GenerateEnquiry(CibilEnquiryEnq);
Can you try the below. C# is case sensitive.
using CbilFileReader.CibilWcfService;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
CIBIL obj = new CIBIL();
CibilEnquiry CibilEnquiryEnq = new CibilEnquiry();
TUEF objtuef = new TUEF();
objtuef.Version = "123";
CibilEnquiryEnq.Tuef = objtuef;
string res = obj.GenerateEnquiry(CibilEnquiryEnq);
}
}
}
This might do the trick for you
CibilWcfService.CIBIL obj = new CibilWcfService.CIBIL();
CibilWcfService.CibilEnquiry CibilEnquiryEnq = new CibilWcfService.CibilEnquiry();
CibilWcfService.CibilEnquiry.Tuef ObjTUEF = new CibilWcfService.CibilEnquiry.Tuef();
ObjTUEF.Version="123";
CibilEnquiryEnq.Tuef = ObjTUEF;
string res = obj.GenerateEnquiry(CibilEnquiryEnq);
Related
C# and Newtonsoft.JSON
I've an object model class like this
class RolePerson
{
public NodeRolePerson[] Items { get; set; }
}
class NodeRolePerson
{
public bool active { get; set; }
public string dateUva { get; set; }
public bool delegated { get; set; }
public NodeentityOrg entityOrg { get; set; }
.....
public string userUva { get; set; }
}
.........
Now i get data with
RolePerson myP1 = JsonConvert.DeserializeObject<RolePerson>(data1,settings);
RolePerson myP2 = JsonConvert.DeserializeObject<RolePerson>(data2,settings);
How can i have only one object with both myP1 and myP2 ?
I've tried with
List<RolePerson> trace;
trace.Add(myP1);
trace.Add(myP2);
but receive a compilation error 'local variable not assigned'.
Thanks so much.
You never actually created a new list:
List<RolePerson> trace = new List<RolePerson>();
trace.Add(myP1);
trace.Add(myP2);
try this
var items = new List<NodeRolePerson>(myP1.Items);
items.AddRange(myP2.Items);
RolePerson trace = new RolePerson { Items = items.ToArray() };
This question already has answers here:
C# List<Interface>: why you cannot do `List<IFoo> foo = new List<Bar>();`
(9 answers)
Closed 4 years ago.
I'm having issues trying to use a list of interfaces. (I'm probably terrible at explaining this, I've only been coding for a year now, but here goes.)
I have an interface:
public interface IComboBoxItem
{
string Display { get; set; }
int? IntValue { get; set; }
string StringValue { get; set; }
}
And a class that implements that interface:
public class GenericComboBoxItem : IComboBoxItem
{
public virtual string Display { get; set; }
public virtual int? IntValue { get; set; }
public virtual string StringValue { get; set; }
public GenericComboBoxItem(string stringValue)
{
Display = stringValue;
StringValue = stringValue;
IntValue = null;
}
}
Then I take a list of these in my View Model's constructor:
public class TransactionModalVM
{
public TransactionModalVM(List<IComboBoxItem> categoryList)
{
CategoryList = categoryList;
}
public List<IComboBoxItem> CategoryList { get; set; }
}
Yet when I attempt to pass them in
public class TransactionsOM
{
internal TransactionModalVM GetTransactionModalVM()
{
return new TransactionModalVM(new List<GenericComboBoxItem>() { new GenericComboBoxItem("Not yet Implemented") });
}
}
I get an error that it can't convert from List<GenericComboBoxItem> to List<IComboBoxItem>.
I originally ran into this when I was using a class that inherited from GenericComboBoxItem and thought I just had to use and interface instead of inheritance but then found that both classes failed and figured there but be some trick I'm missing here.
This may possibly be a duplicate of something, but I've spent the morning searching with no luck and thought I'd post a new question.
Much appreciation in advance for any help!
It would be a good idea to research covariance and contravariance in C#.
However in your particular case,using an IReadOnlyList instead of a list in your view model would solve your problem.
public class TransactionModalVM
{
public TransactionModalVM(IReadOnlyList<IComboBoxItem> categoryList)
{
CategoryList = categoryList;
}
public IReadOnlyList<IComboBoxItem> CategoryList { get; set; }
}
A List<GenericComboBoxItem> is convertible to an IReadOnlyList<IComboBoxItem>, but not to a List<IComboBoxItem>
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I´m attempting to fill a POCO object but I get the NullReferenceException - Object reference not set to an instance of an object, at line "objectAreas.position.Add(objectPositions);" I think I'm not initializing well but I don't see my mistake, let's see the code:
POCO OBJECT
public class GenericQuery
{
public sealed class Areas
{
public int idarea { get; set; }
public string areaname { get; set; }
public List<Positions> positions { get; set; }
}
public sealed class Positions
{
public int idposition { get; set; }
public string positionname { get; set; }
}
public sealed class QueryAreasPositions
{
public int code { get; set; }
public string response { get; set; }
public List<Areas> areas { get; set; }
}
}
Filling It
GenericQuery.QueryAreasPositions objectAreasPositions = new GenericQuery.QueryAreasPositions();
var query = areaRepository.Get(); //Eager Loading EntityFramework List Object, see the AreaRepository at the end
objectAreasPositions.code = 123;
objectAreasPositions.response = "anything";
foreach (var area in query)
{
GenericQuery.Areas objectAreas = new GenericQuery.Areas();
objectAreas.idarea = area.IdArea;
objectAreas.areaname = area.Name;
foreach (var position in area.Position)
{
GenericQuery.Positions objectPositions = new GenericQuery.Positions();
objectPositions.idposition = position.IdPosition;
objectPositions.positionname = position.Name;
***objectAreas.position.Add(objectPositions);***//HERE
}
objectAreasPositions.areas.Add(objectAreas); //And maybe here
}
AreaRepository
public List<Area> Get()
{
using (var context = new Entities())
{
return context.Area.Include("Position").ToList();
}
}
I would appreciate any help/guide you can give me, Thanks.
You are never initializing objectAreas.position, hence the default value for a List<T> is null.
Since you are trying to call the Add method on a null reference, you are getting a NullReferenceException.
To fix this, you should initialize the property before using it:
objectAreas.position = new List<GenericQuery.Positions>();
Alternatively, you can add this logic on GenericQuery.Areas constructor, which would be more appropriate:
public sealed class Areas
{
public int idarea { get; set; }
public string areaname { get; set; }
public List<Positions> positions { get; set; }
public class Areas()
{
positions = new List<Positions>();
}
}
Shouldn't you rather be doing like below. Your position is null cause not yet initialized and thus the said exception.
objectAreas.position = new List<Position>();
objectAreas.position.Add(objectPositions);
In my common.cs class I have the below declarations for a list based on a class:
public static List<edbService> edb_service;
public class edbService
{
public string ServiceID { get; set; }
public string ServiceName { get; set; }
public string ServiceDescr { get; set; }
public string ServiceInterval { get; set; }
public string ServiceStatus { get; set; }
public string ServiceUrl { get; set; }
public string SourceApplication { get; set; }
public string DestinationApplication { get; set; }
public string Function { get; set; }
public string Version { get; set; }
public string userid { get; set; }
public string credentials { get; set; }
public string orgid { get; set; }
public string orgunit { get; set; }
public string customerid { get; set; }
public string channel { get; set; }
public string ip { get; set; }
}
I have a public method to populate the list from xml data files declared like this in the same class (common.cs):
#region PublicMethods
public List<edbService> populateEDBService(string xmlDataFile)
{
try
{
XElement x = XElement.Load(global::EvryCardManagement.Properties.Settings.Default.DataPath + xmlDataFile);
// Get global settings
IEnumerable<XElement> services = from el in x.Descendants("Service")
select el;
if (services != null)
{
edb_service = new List<edbService>();
foreach (XElement srv in services)
{
edbService edbSrv = new edbService();
edbSrv.ServiceID = srv.Element("ServiceID").Value;
edbSrv.ServiceName = srv.Element("ServiceName").Value;
edbSrv.ServiceDescr = srv.Element("ServiceDescr").Value;
edbSrv.ServiceInterval = srv.Element("ServiceInterval").Value;
edbSrv.ServiceStatus = srv.Element("ServiceStatus").Value;
edbSrv.ServiceUrl = srv.Element("ServiceUrl").Value;
foreach (XElement ServiceHeader in srv.Elements("ServiceHeader"))
{
edbSrv.SourceApplication = ServiceHeader.Element("SourceApplication").Value;
edbSrv.DestinationApplication = ServiceHeader.Element("DestinationApplication").Value;
edbSrv.Function = ServiceHeader.Element("Function").Value;
edbSrv.Version = ServiceHeader.Element("Version").Value;
foreach (XElement ClientContext in ServiceHeader.Elements("ClientContext"))
{
edbSrv.userid = ClientContext.Element("userid").Value;
edbSrv.credentials = ClientContext.Element("credentials").Value;
edbSrv.orgid = ClientContext.Element("orgid").Value;
edbSrv.orgunit = ClientContext.Element("orgunit").Value;
edbSrv.customerid = ClientContext.Element("customerid").Value;
edbSrv.channel = ClientContext.Element("channel").Value;
edbSrv.ip = ClientContext.Element("ip").Value;
}
}
edb_service.Add(edbSrv);
}
}
}
catch (Exception ex)
{
/* Write to log */
Common.logBuilder("CustomerCreate : Form --> CustomerCreate <--", "Exception", Common.ActiveMQ,
ex.Message, "Exception");
/* Send email to support */
emailer.exceptionEmail(ex);
}
return edb_service;
}
but the problem is, in my calling class when I try to have a list returned from this method, it is not found - I get a compile error that an object reference is required.
I am trying to call it like this:
Common.edbService edb_service = Common.populateEDBService("CardUpdate.xml");
and I get the below error:
An object reference is required for the non-static field, method, or property 'EvryCardManagement.Common.populateEDBService(string)'
What am I doing wrong?
I would like to have a generic method that can be called from several classes (which run async after being instantiated by background workers on my form)
You can try making your method as static.
public static List<edbService> populateEDBService(string xmlDataFile)
{
//Your code here
....
}
Now you can call this method from all the other classes by using common.populateEDBService();
You need either to create the class static, or to create an object to call it.
class edbService { }
public static void Main() {
//this is error
edbService.populateEDBService("");
//this is correct
edbService s = new edbService();
s.populateEDBService("");
}
The last line in my example shows the object reference required by the compiler. The s variable here is the object reference.
Are there any missing values in your XML? The.Value property won't work if the value is missing. So if ServiceID is missing then srv.Element("ServiceID").Value; will cause an error. You can get it to return an empty string for missing values, for example, by instead using (string)srv.Element("ServiceID");
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I want to serialize simple class as for example like below and write to XML file.
Sample Class file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SampleXMLSerializeDeserialize
{
public class SampleXML
{
public SampleXML()
{
}
public List<IndividualInfo> IndividualInfo { get; set; }
public List<CommunicationInfo> Communication { get; set; }
}
public class IndividualInfo
{
public String Name { get; set; }
public String Age { get; set; }
}
public class CommunicationInfo
{
public String presentAdd { get; set; }
public String permanentAdd { get; set; }
}
}
Serialization Method:
namespace SampleXMLSerializeDeserialize
{
class Program
{
static void Main(string[] args)
{
SampleXML s = new SampleXML();
s.IndividualInfo[0].Name="Jyoti";
s.IndividualInfo[0].Age = "25";
s.Communication[0].permanentAdd = "Dhaka";
s.Communication[0].presentAdd = "Dhaka";
XmlSerializer serializer = new XmlSerializer(typeof(SampleXML));
StreamWriter str = new StreamWriter(Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments) + #"\SAM.XML");
serializer.Serialize(str, s);
}
}
}
I am getting System.NullReferenceExeption at following line: s.IndividualInfo[0].Name="Jyoti";
Would you please help, what I am missing
You never instantiate the [0] object of the collection and the collection itself. Use this:
s.IndividualInfo = new List<IndividualInfo>();
s.IndividualInfo.Add(new IndividualInfo { Name = "Jyoti" });
Have your constructor as
public SampleXML()
{
IndividualInfo = new List<IndividualInfo>();
Communication = new List<CommunicationInfo>();
}
the list is not being initialized and is null.
do the same for the other list as well.
And then use the Add method instead of indexed access.
s.IndividualInfo.Add(new IndividualInfo { Name = "Jyoti", Age = 25 });