How inheritance variables from another class? - c#

I don't know how to inheritance a variables from another class. I write code in C# and I created two classes
First one is Osoba (engl. Person) which has variables ime, prezime, OIB (engl. name, last name, ID) and I have another class Racun (engl. account) which means bank account.
Class Racun has variables podaci o vlasniku računa (engl. account holder information), broj računa (engl. serial number of account) and stanje računa (engl. bank account balance).
Well podaci o vlasniku računa (engl. account holder information) needs to have variables from class Osoba. How can I do that?
I will show you my two created classes with code. If you notice both classes need to have 3 variables, I didn't create first variable in class Racun (engl. account) because the first one need to contain variables from class Osoba (engl. Person).
Osoba.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vjezba6_1
{
class Osoba
{
public string ime { get; set; }
public string prezime { get; set; }
public int oib { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.ime = tempIme;
this.prezime = tempPrezime;
this.oib = tempOib;
}
}
}
Racun.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Vjezba6_1
{
class Racun
{
public int brojRacuna { get; set; }
public int stanjeRacuna { get; set; }
public Racun(int tempPovr, int tempbrojRacuna, int tempstanjeRacuna)
{
this.povr = tempPovr;
this.brojRacuna = tempbrojRacuna;
this.stanjeRacuna = tempstanjeRacuna;
}
}
}

If your povr variable needs to hold the same pieces of information as in Osoba, you can either have povr be a reference to an instance of Osoba:
class Racun
{
public Osoba povr { get; set; }
public int brojRacuna { get; set; }
public int stanjeRacuna { get; set; }
public Racun(Osoba tempPovr, int tempbrojRacuna, int tempstanjeRacuna)
{
this.povr = tempPovr;
//etc
Or you could make a struct to hold common information:
namespace Vjezba6_1
{
struct PodaciOVlasnikuRacuna //i'm sure you can shorten this, but i don't know the language
{
public string ime;
public string prezime;
//other account holder information
}
}
And use this in your classes, like so:
namespace Vjezba6_1
{
class Osoba
{
public PodaciOVlasnikuRacuna podaci { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.podaci.ime = tempIme;
this.podaci.prezime = tempPrezime;
this.podaci.oib = tempOib;
}
}
}

namespace Vjezba6_1_v2
{
class Osoba
{
public Podaci povr { get; set; }
public Osoba(string tempIme, string tempPrezime, int tempOib)
{
this.povr.ime = tempIme;
this.povr.prezime = tempPrezime;
this.povr.oib = tempOib;
}
}
}

Related

C# How to call method from another class

I'm beginner with C# I need little help how to call method from one Class to another class. Since C# is strongly typed language I found it difficult to navigate through classes, methods etc.
I want to take 'GetSalesRevenue() - Class Salesman' and use it at departments 'GetRevenue() - Class Departments ';
This is my first attempt with C# OOP. Any help is appreciated!
using System;
using System.Collections.Generic;
using System.Text;
namespace EmployeeDepartment
{
class Departments
{
public Departments(string[] developers, string[] salesman)
{
Developers = developers;
Salesman = salesman;
}
public string[] Developers { get; set; }
public string[] Salesman { get; set; }
public void GetRevenue(Salesman value)
{
Console.WriteLine("Sum of revenus from All salesmen");
}
public void GetSkillset()
{
Console.WriteLine("Print all skills from the developers in the deparment");
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace EmployeeDepartment
{
class Salesman : Employee
{
public Salesman(string name, string surname, int age, int salary, int salesrevenue, int salarysalesman) : base(name, surname, age, salary)
{
SalesRevenue = salesrevenue;
SalarySalesman = salarysalesman;
}
private double SalesRevenue { get; set; }
public double SalarySalesman { get; set; } = 400;
// Salary is default 400 and Role is default Sales
public double AddRevenue(double addRevenue)
{
return SalesRevenue += addRevenue;
}
public double GetSalesRevenue()
{
return SalesRevenue;
}
public double GetSalary(double plus)
{
return (SalesRevenue / 10) * 100;
}
}
}
I guess you're looking for something like this:
class Departments
{
public Departments(string[] developers, string[] salesman)
{
Developers = developers;
Salesman = salesman;
}
public string[] Developers { get; set; }
public string[] Salesman { get; set; }
public void GetRevenue(Salesman salesman)
{
double revenue = salesman.GetSalesRevenue();
Console.WriteLine($"Sum of revenus from All salesmen: {revenue}" );
}
public void GetSkillset()
{
Console.WriteLine("Print all skills from the developers in the deparment");
}
}

The entity type 'xxx' requires a primary key,but i already defined it?

My entity is derived from Entity class, so it should by default have an id of type int, but for some reason EntityFramework does not recognize it. I even tried to manually make my primary key(commented out) but it still won't work.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;
namespace Test.Models
{
[Table("AppTasks")]
public class Task : Entity, IHasCreationTime
{
//[Key]
//public int Id { get; set; }
public const int MaxTitleLength = 256;
public const int MaxDescriptionLength = 64 * 1024;
[Required]
[StringLength(MaxTitleLength)]
public string Title { get; set; }
[StringLength(MaxDescriptionLength)]
public string Description { get; set; }
public TaskState State { get; set; }
public DateTime CreationTime { get; set; }
public Task()
{
CreationTime = Clock.Now;
State = TaskState.Open;
}
public Task(string title, string description = null) : this()
{
Title = title;
Description = description;
}
}
public enum TaskState : byte
{
Open = 0,
Completed = 1
}
}
Try using a concrete IEntityTypeConfiguration<T>:
public class TaskConfiguration : IEntityTypeConfiguration<Task>
{
public void Configure(EntityTypeBuilder<Task> builder)
{
builder.HasKey(tsk => tsk.Id);
//builder.HasMany(...) relationships et al.
}
}
And in your DbContext definition (or whatever you have called it):
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.ApplyConfiguration(new TaskConfiguration());
}
This should definitely configure EFCore in a way, that Id will be the primary key for this entity. As an added benefit, you get a bit more flexibility and cleaner code.

.Add does not exist in the current context

I'm creating my first app in Xamarin.forms and want to add information about the characters. I followed the Microsoft docs but I keep getting the error that ".Add does not exist in the current context"
I've been the last hour or two searching online but nothing seems to have fixed it. Any help would be greatly appreciated, thanks!
using SQLite;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace CharCreator
{
public class Character
{
[PrimaryKey, AutoIncrement]
public int charIndex { get; set; }
public string charName { get; set; }
public string charClass { get; set; }
public string charRace { get; set; }
public int[] charStats { get; set; }
public int classId { get; set; }
public string className { get; set; }
}
}
public class CharClasses
{
List<CharClasses> classList = new List<CharClasses>();
classList.Add(new CharClasses() {classId = 1, className = "Barbarian"});
}
Your problem begins with the declaration
List<CharClasses> classList = new List<CharClasses>();
You are declaring a List of CharClasses instead of a List of Character. Then you try initialize this list with a first element. But you cannot add code outside a method.
So, if you really need to have CharClasses initialized with a List<Character> containig at least one element then you need to write this
public class CharClasses
{
public List<Character> classList = new List<Character>()
{
new Character {classId = 1, className = "Barbarian"}
};
--- other class method follows
}
This syntax is explained in documentation at Object and Collection Initializers

How to bind an advBandedGridView at run time?

I am new in the using of DevExpress. I need to design and bind a complex DataGrid.
I have designed it using the Designer. The datagrid is of type Master-Detail, and it contains the 'MainGrid' and other detail grids. One of them is of type: 'advBandedGridView'
The design of the MainGrid is as shown below:
And the design of the 'advBandedGridView' is as follows:
Now, I need to fill my DataGrid using Lists collections, so I used the following Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
ArrayList a = new ArrayList();
Term_Space_Grid t = new Term_Space_Grid("x", "y", true, "z");
t.expansions = new List<MyExpansions>();
t.expansions.Add(new MyExpansions(0, "Aya", 0, 0, 0, 0, 0));
a.Add(t);
resultsGridControl.DataSource = a;
}
}
public class Term_Space_Grid
{
public string x { get; set; }
public string y { get; set; }
public string g { get; set; }
public bool z { get; set; }
public List<MyExpansions> expansions { get; set; }
public Term_Space_Grid(string x, string y, bool z, string g)
{
this.x = x;
this.y = y;
this.z = z;
this.g = g;
}
}
public class MyExpansions
{
public Morphos morphos { get; set; }
public Semantics semantics { get; set; }
public MyExpansions(int morphoID, string morphoDerivation, int synID, int subID, int supID, int hasID, int insID)
{
this.morphos = new Morphos(morphoID, morphoDerivation);
this.semantics = new Semantics(synID, subID, supID, hasID, insID);
}
}
public class Morphos
{
//public List<Morph> morph{ get; set; }
public Morph morph { get; set; }
public Morphos(int morphoID, string morphoDerivation)
{
//this.morph = new List<Morph>();
//this.morph.Add(new Morph(morphoID, morphoDerivation));
this.morph = new Morph(morphoID, morphoDerivation);
}
}
public class Semantics
{
public List<Sem> synonyms { get; set; }
public List<Sem> subClasses { get; set; }
public List<Sem> superClasses { get; set; }
public List<Sem> hasInstances { get; set; }
public List<Sem> instanceOf { get; set; }
public Semantics(int id1,int id2, int id3, int id4, int id5 )
{
this.synonyms = new List<Sem>();
this.subClasses = new List<Sem>();
this.superClasses = new List<Sem>();
this.hasInstances = new List<Sem>();
this.instanceOf = new List<Sem>();
this.synonyms.Add(new Sem(id1));
this.subClasses.Add(new Sem(id2));
this.superClasses.Add(new Sem(id3));
this.hasInstances.Add(new Sem(id4));
this.instanceOf.Add(new Sem(id5));
}
}
public class Morph
{
public int MorphoID { get; set; }
public string MorphoDerivation { get; set; }
public Morph(int morphoID, string morphoDerivation)
{
this.MorphoID = morphoID;
this.MorphoDerivation = morphoDerivation;
}
}
public class Sem
{
public int SemID { get; set; }
//public string MorphoDerivation { get; set; }
public Sem(int semID)
{
this.SemID = semID;
}
}
}
However, I found that the result is built as a new DataGrid that has not any designed form. I mean that the detail tabs that I define in the Designer are not appeared in the resulted grid.
The result is as follows:
Notes
The design of the resulted grid which is totally different from my design, I think it is just like the Lists objects.
The other problem which is the appearance of :
"WindowsFormsApplication2.Morphos" and "WindowsFormsApplication2.Semantics" at the cells of the grid rather than the values that I passed!
Firstly, you should create associations between your data object properties and GridView columns via GridColumn.FildName property.
For your main view (gridView2) it looks like this:
// gridColumn1
this.gridColumn1.Caption = "ID";
this.gridColumn1.FieldName = "x"; // associate this column with Term_Space_Grid.x property
this.gridColumn1.Name = "gridColumn1";
Please read the following article for more details: Creating Columns and Binding Them to Data Fields
Secondly, you can not directly bind columns to object's nested properties (for example to MyExpansions.semantics.subclasses.SemID).
To bypass this restriction you can use several approaches:
The simplest approach is using Unbound Columns and the corresponding ColumnView.CustomUnboundColumnData event (you can handle this event to provide data from nested objects).
You can also use the approach demonstrated in the following KB article: How to display and edit complex data properties in grid columns
Thirdly, to get official and guaranteed answer you should address any urgent question related to any DevExpress products directly to DevExpress Support Center.

C# and WCF Reference issue

Got all mixed up and I'm sure it's a silly one.
Solution:
Project 1. Compania.
Linea.cs: Just the Linea class with different constructors and that's it for now.
Project 2. Bandeja.
Class.cs: Here I wrote all the methods I'll be needing when working with Linea. (getLinea() is the one I'll be showing you in the example below)
Project 3. WCFWebService.
A WCF service calling the C# methods.
References.
from Bandeja to Compania.
from WCFWebService to Compania.
from WCFWebService to Bandeja.
The only one error I get while building comes from the service.
Service Class
namespace WCFWebService
{
[DataContract]
public class WSBandeja : IWSBandeja
{
public Compania.Linea getLinea()
{
Compania.Linea linea = new Compania.Linea();
return linea.
}
}
}
When I enter return.linea. I can't find the method getLinea() contained in class.cs inside Project Bandeja, just the parameters.
Any suggestion is most welcome since I'm new to C# and WebServices.
Thanks.
EDIT.
Compania Project - Linea.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Compania
{
public class Linea
{
public string ani { get; set; }
public int teleprom { get; set; }
public string actividad { get; set; }
public DateTime fechaIngreso { get; set; }
public string reclamo { get; set; }
public string producto { get; set; }
public string observacion { get; set; }
public int tipoActividad { get; set; }
public string tipoAveria { get; set; }
public int reiteros { get; set; }
public int call { get; set; }
public bool trabajado { get; set; }
}
}
Bandeja Project - Class.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Web;
namespace Bandeja
{
public class Bandeja
{
public static string getNewConnection()
{
return ConfigurationManager.ConnectionStrings["BO"].ConnectionString;
}
public Compania.Linea getLinea()
{
var cLinea = new Compania.Linea();
string connectionString = getNewConnection();
SqlConnection conn = new SqlConnection(connectionString);
using(conn)
{
string variable = "GESTIONAR MANUALMENTE";
var command = new SqlCommand("Bandeja_test");
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#linea", variable));
conn.Open();
SqlDataReader newReader = command.ExecuteReader();
while (newReader.Read())
{
cLinea = new Compania.Linea();
cLinea.ani = newReader["Línea"].ToString();
cLinea.fechaIngreso = Convert.ToDateTime(newReader["Fecha Ingreso"]);
cLinea.producto = newReader["Producto"].ToString();
cLinea.observacion = newReader["Observación"].ToString();
}
}
return cLinea;
}
}
}
The Web Service Interface.
namespace WCFWebService
{
[ServiceContract]
public interface IWSBandeja
{
[OperationContract]
Compania.Linea getLinea();
}
}
Looks like you are instantiating the wrong class. Try this.
[DataContract]
public class WSBandeja : IWSBandeja
{
public Compania.Linea getLinea()
{
Bandeja.Bandeja bandeja = new Bandeja.Bandeja();
return bandeja.getLinea();
}
}
Try
[ServiceContract]
public class WSBandeja : IWSBandeja
{
[OperationContract]
public Compania.Linea getLinea()
{
Compania.Linea linea = new Compania.Linea();
return linea.
}
}
And then define a [DataContract] for the complex type
namespace Compania
{
[DataContract]
public class Linea
{
[DataMember]
//whatever properties you have
}
See this page for more info on DataContracts and complex types

Categories

Resources