Where can I initialize List to let other functions know that it exists so Visual Studio doesn't show any errors. For the time being it looks like this:
namespace ConsoleApplication1
{
public class BazaDanych
{
public class Album
{
public int IDNumber { get; set; }
public string AlbumName { get; set; }
public string Artist { get; set; }
public int ReleaseDate { get; set; }
public int TrackAmount { get; set; }
public string Location { get; set; }
public int Rating { get; set; }
public Album(int _id, string _name, string _artist, int _releasedate, int _trackamount, string _location, int _rating)
{
IDNumber = _id;
AlbumName = _name;
Artist = _artist;
ReleaseDate = _releasedate;
TrackAmount = _trackamount;
Location = _location;
Rating = _rating;
}
}
static int currid = 1;
public void addnew()
{
int ID = currid;
if (ID == 1);
List<Album> AlbumsList = new List<Album>();
//useless for this question
}
public void printlist()
{
foreach ( int i in AlbumsList)
{
Console.WriteLine(i);
}
}
static void Main(string[] args)
{
var db = new BazaDanych();
//useless
db.addnew();
db.addnew();
}
}
}
Visual Studio screams that AlbumsList doesn't exist in print function.
You are declaring AlbymsList inside the addnew() method. This means it is only visible within that method. You need to declare it outside any method.
It should be a class member/property:
public class BazaDanych
{
private List<Album> AlbumsList = new List<Album>();
....
}
First off, move the class definition of Album outside of the class BazaDanych, idealy make a separate class file for it but this would work too
namespace ConsoleApplication1
{
public class Album
{
//Album logic
}
public class BazaDanych
{
//Baza logic
}
}
Second, as Amiros states, move the definition out of the addNew method into the class (BazaDanych) and use this reference within AddNew
public class BazaDanych
{
private List<Album> AlbumsList = new List<Album>();
public void AddNew()
{
AlbumsList.Add(new Album(...));
}
}
Related
I am invoking a method in my constructor like below.Is this the right way to do to set properties based on some validations.Please suggest.
public class Asset
{
public Asset(string id)
{
SetStorageId(id);
}
public string AssetId { get; set; }
public string UtilId { get; set; }
public string MappingId { get; set; }
public bool IsActive { get; set; }
private void SetStorageId(string id)
{
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
AssetId = id;
}
else
{
UtilId = id;
}
}
}
In my opinion your design should be like below,
You should abstract common items to base class and create specific class inheriting this,
and decide from client(consumer) which instance do you need and construct it
public class AssetBase
{
public string MappingId { get; set; }
public bool IsActive { get; set; }
}
public class Asset : AssetBase
{
public string AssetId { get; set; }
}
public class Util : AssetBase
{
public string UtilId { get; set; }
}
static void Main(string[] args)
{
string id = Console.ReadLine();
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
Asset asset = new Asset();
asset.AssetId = id;
}
else
{
Util util = new Util();
util.UtilId = id;
}
}
simply try this
public class Asset
{
private string id;
public string AssetId { get; set; }
public string UtilId { get; set; }
public string Id
{
set
{
if (Regex.Match(value, "^[A-Z][a-zA-Z]*$").Success)
{
this.id = value;
}
else
{
UtilId = value;
}
}
get
{
return id;
}
}
}
When you create a property in c#, a private variable is created for that property on compile time. When you try to set the Id property in the code above the Id you pass goes into the value keyword and you can perform your validations on the value keyword and set your property accordingly.
No need to complicate your code with set methods, constructors or deriving classes
or you can even use data annotations which is a more elegant way https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx#Properties
using System.ComponentModel.DataAnnotations;
public class Asset
{
[RegularExpression("^[A-Z][a-zA-Z]*$")]
public string Id { get; set; }
}
It's not wrong. It can possibly grow to be a little confusing. Maybe you can make it clearer by moving the bod of SetStorageId to the constructor. Perhaps there is no need to complicate with subclassing, relative to other code within the project.
I wonder if there's any way to match the names in a list with the elements in a class:
I have a class:
public class exampleClass
{
public string name { get; set; }
public string value { get; set; }
}
and a List: List<exampleClass> EnfSist
So that's the way the list is made. Now I would like to know how to match or identify the string inside "name" from my list. To match this class:
tbl_sistematicas b = new tbl_sistematicas
{
ap_enf_id_enfermedad = Convert.ToInt32(EnfSist[0].value),
ap_pac_inicio = Convert.ToInt32(EnfSist[1].value),
ap_pac_inicio_periodo = Convert.ToInt32(2].value),
ap_pac_duracion = Convert.ToInt32(EnfSist[3].value),
ap_pac_duracion_periodo = Convert.ToInt32(EnfSist[4].value),
ap_pac_tratamiento = EnfSist[5].value
};
Once being able to match the same names I won't have to specify each index of every element in the list. The elements in the list have the same name as in the table. Not all elements of the class are being used.
I have something like this: tbl_sistematicas bh = EnfSist.FindAll(x => x.name == bh.?????? );
If I understand the question, you can do this using something like automapper or ValueInjector
An example using ValueInjector
void Main()
{
List<exampleClass> EnfSist = new List<exampleClass>();
EnfSist.Add(new exampleClass { name = "ap_enf_id_enfermedad", value = "12" });
EnfSist.Add(new exampleClass { name = "apap_pac_inicio" , value = "34" });
// etc
tbl_sistematicas b = new tbl_sistematicas();
b.InjectFrom<MyInjection>(EnfSist);
}
public class MyInjection : KnownSourceValueInjection<List<exampleClass>>
{
protected override void Inject(List<exampleClass> source, object target)
{
foreach(var entry in source)
{
var property = target.GetProps().GetByName(entry.name, true);
if (property != null)
property.SetValue(target, Convert.ChangeType(entry.value, property.PropertyType));
}
}
}
public class exampleClass
{
public string name { get; set; }
public string value { get; set; }
}
public class tbl_sistematicas
{
public int ap_enf_id_enfermedad { get; set; }
public int apap_pac_inicio { get; set; }
public int ap_pac_inicio_periodo { get; set; }
public int ap_pac_duracion { get; set; }
public int ap_pac_duracion_periodo { get; set; }
public string ap_pac_tratamiento { get; set; }
}
Note, this will throw an exception if the value can not be converted to an int
I've created classes from XSD Schema using xsd.exe (also tried with xsd2code which had better results in a way that they worked immediately, and with xsd.exe I have to debug some errors). XSD Schema I've used can be found at http://www.landxml.org/schema/LandXML-1.2/LandXML-1.2.xsd , and sample file can be found at http://landxml.org/schema/LandXML-1.1/samples/AASHTO%20SDMS/MntnRoad.xml .
My code for deserialization looks like:
var mySerializer = new XmlSerializer(typeof (LandXML), new XmlRootAttribute(""));
TextReader myFileStream = new StreamReader("myFile.xml");
var myObject = (LandXML) mySerializer.Deserialize(myFileStream);
My problem is that result of deserialization is list of items of type XmlElement, so if I try to access their properties, I can't easy do that. If I want to access, for example, some Alignment object attribute in myFile.xml, the code is similar to this:
var a = myObject.Items[5];
var b = (XmlElement) a;
var c = b.ChildNodes.Item(5).ChildNodes.Item(0).ChildNodes.Item(0).Attributes[0].Value;
It is obvious that this is not a way which is meant to be while deserializing XML to classes. My idea was like (for same element):
var c = LandXML.Alignments.Alignment.CoordGeometry.Curve.rot
I don't know what I'm doing wrong, I've tried with simpler schemas, and this code was working well. Please help and tnx in advance!
EDIT 1
this is at top of my class and I think that this List type generating troubles. And there is a more similar code in my generated classes
public class LandXML
{
private List<object> _items;
private System.DateTime _date;
private System.DateTime _time;
private string _version;
private string _language;
private bool _readOnly;
private int _landXMLId;
private string _crc;
public LandXML()
{
this._items = new List<object>();
}
[System.Xml.Serialization.XmlAnyElementAttribute()]
[System.Xml.Serialization.XmlElementAttribute("Alignments", typeof(Alignments))]
[System.Xml.Serialization.XmlElementAttribute("Amendment", typeof(Amendment))]
[System.Xml.Serialization.XmlElementAttribute("Application", typeof(Application))]
[System.Xml.Serialization.XmlElementAttribute("CgPoints", typeof(CgPoints))]
[System.Xml.Serialization.XmlElementAttribute("CoordinateSystem", typeof(CoordinateSystem))]
[System.Xml.Serialization.XmlElementAttribute("FeatureDictionary", typeof(FeatureDictionary))]
[System.Xml.Serialization.XmlElementAttribute("GradeModel", typeof(GradeModel))]
[System.Xml.Serialization.XmlElementAttribute("Monuments", typeof(Monuments))]
[System.Xml.Serialization.XmlElementAttribute("Parcels", typeof(Parcels))]
[System.Xml.Serialization.XmlElementAttribute("PipeNetworks", typeof(PipeNetworks))]
[System.Xml.Serialization.XmlElementAttribute("PlanFeatures", typeof(PlanFeatures))]
[System.Xml.Serialization.XmlElementAttribute("Project", typeof(Project))]
[System.Xml.Serialization.XmlElementAttribute("Roadways", typeof(Roadways))]
[System.Xml.Serialization.XmlElementAttribute("Surfaces", typeof(Surfaces))]
[System.Xml.Serialization.XmlElementAttribute("Survey", typeof(Survey))]
[System.Xml.Serialization.XmlElementAttribute("Units", typeof(Units))]
public List<object> Items
{
get
{
return this._items;
}
set
{
this._items = value;
}
}
Try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlSerializer xs = new XmlSerializer(typeof(LandXML));
XmlTextReader reader = new XmlTextReader(FILENAME);
reader.Namespaces = false;
LandXML landXML = (LandXML)xs.Deserialize(reader);
}
}
[XmlRoot("LandXML")]
public class LandXML
{
[XmlAttribute("version")]
public double version { get;set; }
[XmlAttribute("date")]
public DateTime date { get;set; }
[XmlAttribute("time")]
public DateTime time { get; set; }
[XmlAttribute("readOnly")]
public Boolean readOnly { get;set; }
[XmlAttribute("language")]
public string language { get;set; }
[XmlElement("Project")]
public Project project { get; set; }
[XmlElement("Units")]
public Units units { get; set; }
[XmlElement("Application")]
public Application application { get; set; }
[XmlElement("Alignments")]
public Alignments alignments { get; set; }
}
[XmlRoot("Project")]
public class Project
{
[XmlAttribute("name")]
public string name;
}
[XmlRoot("Units")]
public class Units
{
[XmlElement("Imperial")]
public Imperial imperial { get; set; }
}
[XmlRoot("Application")]
public class Application
{
[XmlElement("Author")]
public Author author { get; set; }
}
[XmlRoot("Imperial")]
public class Imperial
{
[XmlAttribute("linearUnit")]
public string linearUnit;
[XmlAttribute("areaUnit")]
public string areaUnit;
[XmlAttribute("volumeUnit")]
public string volumeUnit;
[XmlAttribute("temperatureUnit")]
public string temperaturUnit;
[XmlAttribute("pressureUnit")]
public string pressureUnit;
[XmlAttribute("angularUnit")]
public string angularUnit;
[XmlAttribute("directionUnit")]
public string name;
}
[XmlRoot("Author")]
public class Author
{
[XmlAttribute("createdBy")]
public string createdBy;
[XmlAttribute("createdByEmail")]
public string createdByEmail;
[XmlAttribute("company")]
public string company;
[XmlAttribute("companyURL")]
public string companyURL;
}
[XmlRoot("Alignments")]
public class Alignments
{
[XmlAttribute("desc")]
public string desc;
[XmlElement("Alignment")]
public Alignment alignment { get; set; }
}
[XmlRoot("Alignment")]
public class Alignment
{
[XmlAttribute("name")]
public string name;
[XmlAttribute("desc")]
public string desc;
[XmlAttribute("length")]
public string length;
[XmlAttribute("staStart")]
public string staStart;
[XmlElement("AlignPIs")]
public AlignPIs alignPIs { get; set; }
}
[XmlRoot("AlignPIs")]
public class AlignPIs
{
[XmlElement("AlignPI")]
public List<AlignPI> alignPI { get; set; }
}
[XmlRoot("AlignPI")]
public class AlignPI
{
[XmlElement("PI")]
public PI pi { get; set; }
[XmlElement("InSpiral")]
public InSpiral inSpiral { get; set; }
[XmlElement("Curve1")]
public Curve1 cureve1 { get; set; }
[XmlElement("OutSpiral")]
public OutSpiral outSpiral { get; set; }
[XmlElement("Station")]
public Station station { get; set; }
}
[XmlRoot("Station")]
public class Station
{
[XmlText]
public string value { get; set; }
}
[XmlRoot("PI")]
public class PI
{
[XmlAttribute("code")]
public int code;
[XmlAttribute("name")]
public int name;
[XmlText]
public string value;
}
[XmlRoot("InSpiral")]
public class InSpiral
{
[XmlElement("Spiral")]
public Spiral spiral { get; set; }
}
[XmlRoot("Spiral")]
public class Spiral
{
[XmlAttribute("length")]
public double length;
[XmlAttribute("radiusEnd")]
public double radiusEnd;
[XmlAttribute("radiusStart")]
public double radiusStart;
[XmlAttribute("rot")]
public string rot;
[XmlAttribute("spiType")]
public string spiType;
}
[XmlRoot("Curve1")]
public class Curve1
{
[XmlElement("Curve")]
public Curve curve { get; set; }
}
[XmlRoot("Curve")]
public class Curve
{
[XmlAttribute("rot")]
public string rot;
[XmlAttribute("radius")]
public double radius;
}
[XmlRoot("OutSpiral")]
public class OutSpiral
{
[XmlElement("Spiral")]
public Spiral spiral { get; set; }
}
}
I have two classes with some similar fields, some different, and a form that utilizes two different objects depending on what mode it's in (insert/edit).
Instead of using two different objects and if statements checking the form mode, I'd like to have one struct to be hydrated with either of the two objects fields so I can manipulate one object through the page life-cycle. Then separated the struct back to its respective object for insert/updating the DB.
Example of classes:
public partial class SomeClass
{
public Int32 B {get;set;}
public String C {get;set;}
public Boolean D {get;set;}
}
public class SomeOtherClass
{
public Int32 A {get;set;}
public Int32 B {get;set;}
public String C {get;set;}
}
Update with Solution Example:
public interface IInsertable
{
string SharedName { get; set; }
string SharedID { get; set; }
string editedFieldValue { get; set; }
long GetSuperSecreteInfo();
}
internal class InsertableImplementation : IInsertable
{
public string SharedName { get; set; }
public string SharedID { get; set; }
public string editedFieldValue { get; set; }
public long GetSuperSecreteInfo()
{
return -1;
}
}
public interface IUpdateable
{
string SharedName { get; set; }
string SharedID { get; set; }
string updatedFieldValue { get; set; }
Guid GenerateStevesMagicGuid();
}
internal class UpdateableImplementation : IUpdateable
{
public string SharedName { get; set; }
public string SharedID { get; set; }
public string updatedFieldValue { get; set; }
public Guid GenerateStevesMagicGuid()
{
return new Guid();
}
}
public static class WonderTwinFactory
{
public static WonderTwins GenerateWonderTwin(IUpdateable updateable, IInsertable insertable)
{
var wt = new WonderTwins();
// who will win?
wt.SharedID = updateable.SharedID;
wt.SharedID = insertable.SharedID;
// you decide?
wt.SharedName = updateable.SharedName;
wt.editedFieldValue = "stuff";
return wt;
}
}
public class WonderTwins : IInsertable, IUpdateable
{
public string SharedName { get; set; }
public string SharedID { get; set; }
public string editedFieldValue { get; set; }
public long GetSuperSecreteInfo()
{
return 1;
}
public string updatedFieldValue { get; set; }
public Guid GenerateStevesMagicGuid()
{
return new Guid();
}
}
class Program
{
static void Main(string[] args)
{
IUpdateable updateable = new UpdateableImplementation();
IInsertable insertable = new InsertableImplementation();
WonderTwins dualImplementatin = WonderTwinFactory.GenerateWonderTwin(updateable, insertable);
IUpdateable newUpdateable = dualImplementatin as IUpdateable;
IInsertable newInsertable = dualImplementatin as IInsertable;
}
}
Have both classes implement an interface that defines the operations common to each, including both the fields that are shared (assuming the view needs to access them) and also a method to actually perform the operation that they represent (insert/edit).
Other way of doing such things is using C# dynamic object and assign properties directly. It may help to avoid any new type or interface and directly utilizing new dynamic object any time, as much as required.
var newObject = new {
objectOfClass1 = x.prop1,
objectOfClass2 = x.prop2
}
I'm new on java/android:
I'm using this list of objects on wp7 and I want pass to android, how I do this:
My big object c#:
public class ListCountries
{
public List<CountriesRepresented> _countriesRepresented { get; set; }
public List<CountriesOrigin > _countriesOrigin { get; set; }
}
My others two objects in c#:
public class CountriesRepresented
{
public int CountryID { get; set; }
public string Designation { get; set; }
public string Symbol { get; set; }
public string NomDesignationISO { get; set; }
}
public class CountriesOrigin
{
public int CountryID { get; set; }
public string Designation { get; set; }
public string Symbol { get; set; }
public string NomDesignationISO { get; set; }
}
My java Deserializer:
public Object[] getListCountries()
{
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(Config.WS_PATH);
post.setHeader("content-type", "application/json; charset=UTF-8");
post.addHeader("Client-Application","3601cfde-e440-4a84-a2cc-a402f4c7bd14");
HttpResponse resp = httpClient.execute(post);
String respStr = EntityUtils.toString(resp.getEntity());
ListCountries _listCountries = new JSONDeserializer().deserialize(ListCountries .class, respStr);
return _listCountries;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
My big object in java:
public class ListCountries {
public List<CountriesRepresented> _CountriesRepresented;
public List<CountriesOrigin > _CountriesOrigin ;
public List<CountriesRepresented> getCountriesRepresented() {
return this._CountriesRepresented;
}
public List<CountriesOrigin > getCountriesOrigin() {
return this._CountriesOrigin ;
}
public void setCountriesRepresented (List<CountriesRepresented> CountriesRepresented) {
this._CountriesRepresented = CountriesRepresented;
}
public void setCountriesOrigin (List<CountriesOrigin > CountriesOrigin ) {
this._CountriesOrigin = CountriesOrigin ;
}
}
My service is on WebAPI and give me an correct answer example: `{"PaisesRepresentantes":[{"PaisID":4,"Designacao":"Alemanha","Sigla":"DEU","NomDesignacaoISO":"GERMANY"},{"PaisID":21,.......
your classes in Java should be something like,
public class ListCountries
{
public List<CountriesRepresented> _countriesRepresented; //Make it private if you want and then you can add getter setter function
public List<CountriesOrigin > _countriesOrigin;
}
public class CountriesRepresented
{
public int CountryID; //Make it private if you want and then you can add getter setter function
public String Designation;
public String Symbol;
public String NomDesignationISO;
}
public class CountriesOrigin
{
public int CountryID; //Make it private if you want and then you can add getter setter function
public String Designation;
public String Symbol;
public String NomDesignationISO;
}
The problem with your existing code is that you have declared variable as _CountriesRepresented rather it should be _countriesRepresented i.e. properties are case sensitive and those are mapped to variables declared in class and do remember to add a default constructor if you add any custom constructor to any of those classes