C# Inconsistent accessibility - c#

I get an inconsistent accessibility error when trying to compile my C# code. I have googled it extensively, but all the cases and answers I find deal with some private-public inconstancy. I have not written private ANYWHERE in my code at all, I have checked and double checked. I read something somewhere that I could try "lowering the scope", but I have no idea what that means. Help.
Sorry for missing code, here it is on github:
https://gist.github.com/jyggorath/7589742
using System;
public class oblig5 {
// // // BEGIN GLOBAL 1 // // //
public const int STRLEN = 40;
public const int MAXPERSONER = 500;
public const int MAXLAG = 50;
public enum funksjon {trener, oppman, ingen};
// // // END GLOBAL 1 // // //
// // // BEGIN PERSON CLASS // // //
public class Person {
// // // privates:
public string navn;
public string adr;
public string mail;
public string klasse;
public int tlf;
public funksjon verv;
public int lagnr;
// // // publics:
// constructor
public Person() {
navn = ""; adr = ""; mail = ""; klasse = "";
tlf = 0; lagnr = 0;
verv = (funksjon)2;
}
// skriv:
public void skriv() {
Console.WriteLine("Navn: {0}\nAdresse: {1}\nMail: {2}\nKlasse: {3}\nTlf: {4}\nLagnr: {5}", navn, adr, mail, klasse, tlf, lagnr);
if (verv == (funksjon)0)
Console.WriteLine("Er Trener\n");
else if (verv == (funksjon)1)
Console.WriteLine("Er Oppmann\n");
else
Console.WriteLine("Har ikkeno verv\n");
lag[lagnr].skriv();
}
public void skriv2() {
Console.WriteLine("Navn: {0}\nAdresse: {1}\nMail: {2}\nKlasse: {3}\nTlf: {4}\n", navn, adr, mail, klasse, tlf);
}
// les:
public void les_data(int lnr) {
lagnr = lnr;
navn = les_str("Personens navn");
adr = les_str("Personens adresse");
mail = les_str("Personens mail");
klasse = les_str("Hvilke klasse går personen i?");
tlf = les_int("Personens telefonnr", 10000000, 99999999);
verv = les_enum();
}
// fil:
public void skriv_til_fil(System.IO.StreamWriter file) {
file.WriteLine(navn);
file.WriteLine(adr);
file.WriteLine(mail);
file.WriteLine(klasse);
file.WriteLine(tlf);
file.WriteLine((int)verv);
file.WriteLine(lagnr);
}
public void les_fra_fil(System.IO.StreamReader file, string nvn) {
navn = nvn;
adr = file.ReadLine();
mail = file.ReadLine();
klasse = file.ReadLine();
tlf = int.Parse(file.ReadLine());
verv = (funksjon)int.Parse(file.ReadLine());
lagnr = int.Parse(file.ReadLine());
}
// sammenligninger:
public bool har_navn(string t) {
return (navn == t);
}
public bool har_verv(funksjon v) {
return (verv == v);
}
public bool tilhorer_lag(int n) {
return (lagnr == n);
}
}
// // // END PERSON CLASS // // //
// // // BEGIN LAG CLASS // // //
public class Lag {
// // // privates:
public string navn;
public string adr;
public string mail;
public string hjemmeside;
// // // publics:
public Lag() {
navn = ""; adr = ""; mail = ""; hjemmeside = "";
}
public void skriv() {
Console.WriteLine("Lagnavn: {0}\nLagadresse: {1}\nLagmail: {2}\nLaghjemmeside: {3}\n", navn, adr, mail, hjemmeside);
}
public void les_data(string t) {
navn = t;
adr = les_str("Lagets adresse");
mail = les_str("Lagets mail");
hjemmeside = les_str("Lagets hjemmeside");
}
public bool har_navn(string t) {
return (navn == t);
}
}
// // // END LAG CLASS // // //
// // // BEGIN GLOBAL 2 // // //
// things:
public static Person[] personer = new Person[MAXPERSONER + 1];
public static Lag[] lag = new Lag[MAXLAG + 1];
public static int siste_person = 0, siste_lag = 0;
// funskjoner:
public static void skriv_meny() {
Console.WriteLine("\n\nFØLGENDE KOMMANDOER ER LOVLIG:");
Console.WriteLine("\tA = skriv ALT om En person");
Console.WriteLine("\tB = skriv ALLE trenere ELLER oppmenn");
Console.WriteLine("\tC = skriv ALT om et gitt lag");
Console.WriteLine("\tL = nytt Lag legges inn");
Console.WriteLine("\tP = ny Person legges inn");
Console.WriteLine("\tQ = Quit/Avslutt");
}
public static char les_char(string t) {
Console.Write(string.Concat("\n", t, ": "));
char retur = Console.ReadLine().ToUpper()[0];
return retur;
}
public static int les_int(string t, int min, int max) {
int retur = min - 1;
do {
Console.Write(string.Concat("\t", t, " (", min.ToString(), "-", max.ToString(), "): "));
retur = int.Parse(Console.ReadLine());
} while (retur < min || retur > max);
return retur;
}
public static string les_str(string t) {
return Console.ReadLine();
}
public static funksjon les_enum() {
char ch = '\0';
do {
Console.Write("\tT(rener) eller O(ppmann): ");
ch = Console.ReadLine().ToUpper()[0];
} while (ch != 'T' && ch != 'O');
return ((ch == 'T') ? (funksjon)0 : (funksjon)1);
}
public static int finn_person(string t) {
for (int i = 1; i <= siste_person; i++)
if (personer[i].har_navn(t))
return i;
return 0;
}
public static int finn_lag(string t) {
for (int i = 1; i <= siste_lag; i++)
if (lag[i].har_navn(t))
return i;
return 0;
}
public static void skriv_person() {
string nvn = les_str("Navn på person");
int person_nr = finn_person(nvn);
if (person_nr == 0)
Console.WriteLine("Personen fins ikke");
else
personer[person_nr].skriv();
}
public static void skriv_verv() {
funksjon v = les_enum();
for (int i = 1; i < siste_person; i++) {
if (personer[i].har_verv(v))
personer[i].skriv();
}
}
public static void skriv_lag() {
string lagnvn = les_str("Navn på lag");
int lagnr = finn_lag(lagnvn);
if (lagnr == 0)
Console.WriteLine("Laget fins ikke");
else {
lag[lagnr].skriv();
for (int i = 1; i <= siste_person; i++) {
if (personer[i].tilhorer_lag(lagnr))
personer[i].skriv2();
}
}
}
public static void nytt_lag() {
if (siste_lag < MAXLAG) {
string lagnvn = les_str("Lagets navn");
if (finn_lag(lagnvn) == 0) {
siste_lag++;
lag[siste_lag] = new Lag();
lag[siste_lag].les_data(lagnvn);
}
else
Console.WriteLine("Laget fins fra før!");
}
else
Console.WriteLine("Lag er full!");
}
public static void ny_person() {
if (siste_person < MAXPERSONER) {
string lagnvn = les_str("Hvilke lag tilhører personen?");
int lagnr = finn_lag(lagnvn);
if (lagnr != 0) {
siste_person++;
personer[siste_person] = new Person();
personer[siste_person].les_data(lagnr);
}
else
Console.WriteLine("Laget fins ikke!");
}
else
Console.WriteLine("Personer er fulle!");
}
public static void skriv_til_fil() {
System.IO.StreamWriter file = new System.IO.StreamWriter("personer.dta");
for (int i = 1; i <= siste_person; i++) {
personer[i].skriv_til_fil(file);
}
}
public static void les_fra_fil() {
string buffer;
try {
System.IO.StreamReader file = new System.IO.StreamReader("personer.dta");
while ((buffer = file.ReadLine()) != null) {
siste_person++;
personer[siste_person] = new Person();
personer[siste_person].les_fra_fil(file, buffer);
}
}
catch {
Console.WriteLine("Finner ikke filen!");
}
}
// // // END GLOBAL 2 // // //
// // // BEGIN MAIN // // //
public static void Main() {
char kommando;
les_fra_fil();
skriv_meny();
kommando = les_char("Ønske");
while (kommando != 'Q') {
switch (kommando) {
case 'A':
skriv_person(); break;
case 'B':
skriv_verv(); break;
case 'C':
skriv_lag(); break;
case 'L':
nytt_lag(); break;
case 'P':
ny_person(); break;
default:
skriv_meny();
break;
}
kommando = les_char("Ønske");
}
skriv_til_fil();
Console.WriteLine("\n");
}
// // // END MAIN // // //
}
Sorry for strange variable names. This is code ported from C++ assignments from my Norwegian teacher (I didn't change them 'cause I'm Norwegian as well, and I never thought I would be getting these problems)
As you can see, ALL classes defined in my code is public. So that is not my problem. The errors are generated on lines 126 and 127, as well as 160. The errors deal with the assignments of variables with my custom classes as type, and with my function returning a custom enum type. Help?

My psychic debugging sense tells me that you're not declaring a class as public
public class MyType
IF you want to make a public field of MyType, it's not enough to just type class MyType you have to make it public explicitly.

Related

(C# VB) Could I change all variables' values in a class dynamically?

I've seen ways to list all variables in a certain class, but is there a way to set their values?
I want a method I can call, and it can reset all variables' values to false / 0 , I know I can manually set those to false / 0, but any change to their values would mess up everything, and I'm just seeing if there's anything more dynamic / easy way that this could be done ?
Currently I'm doing the following:
// These are just some of the vars that are here.
Error = false;
double GUM = 0, MUM = 0;
decimal Mass = 0, GAcc = 0, Fg = 0, FµsRes = 0, FµkRes = 0, Fµs = FµsNS.Value, Fµk = FµkNS.Value;
As others have mentioned, you could use Reflection to set all the class fields to their default values:
using System;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
myClass.Error = true;
myClass.GUM = 1;
myClass.MUM = 2;
myClass.Mass = 3.5m;
myClass.GAcc = 4.5m;
myClass.Fg = 5.5m;
ResetFields(myClass);
// All fields are reseted
}
public static void ResetFields(object source)
{
foreach (var fieldInfo in source.GetType().GetFields() )
{
fieldInfo.SetValue(source, GetDefault(fieldInfo.FieldType) );
}
}
public static object GetDefault(Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
}
public class MyClass
{
public bool Error = false;
public double GUM = 0, MUM = 0;
public decimal Mass = 0, GAcc = 0, Fg = 0;
//etc etc
}
}
A better approach however, is to create a class to only hold the values and re-create it when needed:
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
myClass.Variables = new MyVariables();
myClass.Variables.Error = true;
myClass.Variables.GUM = 1;
myClass.Variables.MUM = 2;
myClass.Variables.Mass = 3.5m;
myClass.Variables.GAcc = 4.5m;
myClass.Variables.Fg = 5.5m;
myClass.Variables = new MyVariables();
// All fields are reseted
}
}
public class MyVariables
{
public bool Error = false;
public double GUM = 0, MUM = 0;
public decimal Mass = 0, GAcc = 0, Fg = 0;
}
public class MyClass
{
public MyVariables Variables;
// etc etc
public int Xyz
{
get { return Variables.GUM + Variables.MUM; } // Use calculated properties
}
}
}
The GetDefault method is shown in this answer.

Xceed.Words.NET DocX - Add document to Maindocument and reset Numbered lists to 1

Good day,
I try that when I connect two documents, the numbered lists are reset. As in the example below.
I use the Xceed.Words.NET DocX libary.
In this Sample, the Template is :
Test Header
List:
1) <-This should be one
And the Result is:
Test Header
List:
1) <-This should be one
Test Header
List:
2) <-This should be one
Test Header
List:
3) <-This should be one
With the following code I am able to create the lists with similar formatting, but the formatting does not match 100%. Does anyone have any idea which way to try otherwise?
Note the number of existing paragraphs and call the function to reset the list after inserting the document.
/// <summary>
/// Insert complete WordFile
/// </summary>
/// <param name="wordFile"></param>
public void InsertWordTemplate(IWordFile wordFile, bool InsertPageBreak)
{
if (wordFile != null && wordFile.IsFileOk)
{
int pargraphCount = Document.Paragraphs.Count - 1;
// NotNeeded for this Problem wordFile.RemoveStyles();
// NotNeeded for this Problem RemoveHeaderAndFooter(wordFile);
Document.InsertDocument(wordFile.Document);
// NotNeeded for this Problem ReplaceSectionBreak(InsertPageBreak, pargraphCount);
ResetNumberedList(pargraphCount);
logger.Info("Word file inserted: " + wordFile.File.FullName);
}
else
{
logger.Warn("Word file is not okay - will not be inserted: " + wordFile?.File?.FullName);
}
}
In the Word document, three different names are used in a list, only from the 4th level is worked with a level. For other Word templates they are called different.
private void ResetNumberedList(int pargraphCount)
{
string styleName1 = "ListNumbers";
string styleName2 = "PIgeordneteListe2Ebene";
string styleName3 = "PIgeordneteListe3Ebene";
NumberedListReset numberedListReset = new NumberedListReset(Document, styleName1, styleName2, styleName3);
bool OnlyFirstFoundList = true;
numberedListReset.Reset(pargraphCount, OnlyFirstFoundList);
}
Below is the helper class with which I try to reset the numbering. I do this by myself
I notice the formatting of the individual list items, create new lists, fill them with the old values, set the styles correctly again and then insert everything into old place.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Xceed.Document.NET;
using Xceed.Words.NET;
namespace PIB.Report.DataWriter.WordExport
{
public class NumberedListReset
{
private readonly DocX _Document;
private readonly string _StyleName1;
private readonly string _StyleName2;
private readonly string _StyleName3;
public NumberedListReset(DocX Document, string StyleName1, string StyleName2, string StyleName3)
{
_Document = Document;
_StyleName1 = StyleName1;
_StyleName2 = StyleName2;
_StyleName3 = StyleName3;
}
public void Reset(int StartParagraphNumber, bool OnlyFirstFinding)
{
for (int i = StartParagraphNumber; i < _Document.Paragraphs.Count; i++)
{
var paragraph = _Document.Paragraphs[i];
if (paragraph.IsListItem == true && paragraph.ListItemType == ListItemType.Numbered && paragraph.StyleName == _StyleName1)
{
//int? numId = GetNumId(paragraph);
//if (numId != -1)
//{
//}
ResetFoundList(ref i);
if (OnlyFirstFinding == true)
{
break;
}
}
}
}
private void ResetFoundList(ref int ParagraphCounter)
{
List<ParagraphMemorize> ParagraphMemorizes = CreateMemorizeListItems(ParagraphCounter);
if (ParagraphMemorizes.Count != 0)
{
RemoveOldParagraphsFromDocument(ParagraphMemorizes);
List numberedList = CreateNewDocumentList();
FillDocumentList(ParagraphMemorizes, numberedList);
List<Paragraph> actualListData = numberedList.Items;
ResetSyleNames(ParagraphMemorizes, actualListData);
InsertNewParagraphsToDocument(ParagraphCounter, actualListData);
ParagraphCounter += ParagraphMemorizes.Count;
}
}
private List<ParagraphMemorize> CreateMemorizeListItems(int ParagraphCounter)
{
List<ParagraphMemorize> ParagraphMemorizes = new List<ParagraphMemorize>();
for (int ii = ParagraphCounter; ii < _Document.Paragraphs.Count; ii++)
{
var paragraph = _Document.Paragraphs[ii];
if (!NameIsKnown(paragraph.StyleName))
{
break;
}
ParagraphMemorize paragraphMemorize = new ParagraphMemorize(paragraph);
paragraphMemorize.ListLevel = GetListLevel(paragraph);
ParagraphMemorizes.Add(paragraphMemorize);
}
return ParagraphMemorizes;
}
private void RemoveOldParagraphsFromDocument(List<ParagraphMemorize> ParagraphMemorizes)
{
ParagraphMemorizes.ForEach(m => _Document.RemoveParagraph(m.Paragraph));
}
private List CreateNewDocumentList()
{
return _Document.AddList(startNumber: 1);
}
private void FillDocumentList(List<ParagraphMemorize> ParagraphMemorizes, List numberedList)
{
for (var ii = 0; ii < ParagraphMemorizes.Count; ii++)
{
//numberedList.AddItem(ParagraphMemorizes[ii].Paragraph); //Raised an Error
ParagraphMemorize paragraphMemorize = ParagraphMemorizes[ii];
int listLevel = GetListLevel(paragraphMemorize);
_Document.AddListItem(numberedList, paragraphMemorize.Text, listLevel);
}
}
private static void ResetSyleNames(List<ParagraphMemorize> ParagraphMemorizes, List<Paragraph> actualListData)
{
for (int ii = 0; ii < actualListData.Count; ii++)
{
actualListData[ii].StyleName = ParagraphMemorizes[ii].StyleName;
}
}
private void InsertNewParagraphsToDocument(int i, List<Paragraph> actualListData)
{
Paragraph paragraph = _Document.Paragraphs[i];
for (int ii = 0; ii < actualListData.Count; ii++)
{
paragraph.InsertParagraphBeforeSelf(actualListData[ii]);
}
}
private bool NameIsKnown(string Name)
{
return Name == _StyleName1 | Name == _StyleName2 | Name == _StyleName3;
}
private int GetListLevel(ParagraphMemorize paragraphMemorize)
{
if (paragraphMemorize.StyleName == _StyleName1)
{
return 0;
}
else if (paragraphMemorize.StyleName == _StyleName2)
{
return 1;
}
else if (paragraphMemorize.StyleName == _StyleName3)
{
return (int)paragraphMemorize.ListLevel;
}
else
{
return 0;
}
}
private int? GetNumId(Paragraph paragraph)
{
var numIds = paragraph.ParagraphNumberProperties.Descendants().Where(e => e.Name.LocalName.Equals("numId"));
foreach (var numId in numIds)
{
XNamespace nsW = Namespace.WordNamespace;
var values = numId.Attributes(XName.Get("val", nsW.ToString()));
foreach (var value in values)
{
int resultId = 0;
int.TryParse(value.Value, out resultId);
return resultId;
}
}
return null;
}
private int? GetListLevel(Paragraph paragraph)
{
var numIds = paragraph.ParagraphNumberProperties.Descendants().Where(e => e.Name.LocalName.Equals("ilvl"));
foreach (var numId in numIds)
{
XNamespace nsW = Namespace.WordNamespace;
var values = numId.Attributes(XName.Get("val", nsW.ToString()));
foreach (var value in values)
{
int resultId = 0;
int.TryParse(value.Value, out resultId);
return resultId;
}
}
return null;
}
private class ParagraphMemorize
{
public Paragraph Paragraph { get; set; }
public string Text { get; set; }
public string StyleName { get; set; }
public int? ListLevel { get; set; }
public ParagraphMemorize(Paragraph Paragraph)
{
this.Paragraph = Paragraph;
this.Text = Paragraph.Text;
this.StyleName = Paragraph.StyleName;
}
}
}
}

How to invoke Method immediately after instantiating

I have a controller that calls an api to get a list of Positions and Employees . First it puts the api results into a model class - IDMSElements (1). Then the controller takes the IDMSElements object and converts it to a PositionSlots object (2). Then the PositionSlots object needs to be updated with additional data from a database (3). So in simplified version of my controller I have:
(1) IDMSElements elements = getslots.CopyDocToElements(doc);
(2) PositionSlots myslots = (PositionSlots)elements;
(3) myslots.UpdateDetails(db);
I am concerned about the myslots.UpdateDetails(db) because additional code in the controller depends on UpdateDetails having been run. I would like the UpdateDetails to be run by default when creating the PositionSlots object. But I think multiple database calls in a constructor probably should not be done. How can I make it so the UpdateDetails is automatically invoked after the PositionSlots object is instantiated?
Thank you very much!
Controller:
[Authorize]
public class PSListController : Controller
{
private static readonly log4net.ILog _logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private PositionControlContext db = new PositionControlContext();
private GetPositionSlots getslots = new GetPositionSlots();
...
public async Task<ActionResult> ByCostCenter(int costCenter)
{
string ssapiuri = getslots.BuildAPIuri($"/current/?UDAKunit={costCenter.ToString()}");
_logger.Debug($"{ssapiuri.ToString()}");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
HttpResponseMessage result = await getslots.GetDataFromIDMSapi(ssapiuri);
stopWatch.Stop();
_logger.Debug($"Response received. Milliseconds elapsed: {stopWatch.Elapsed.TotalMilliseconds.ToString()}");
if (result.StatusCode != HttpStatusCode.OK)
{
_logger.Debug("Error retrieving data from API. Milliseconds elapsed: " + stopWatch.Elapsed.TotalMilliseconds.ToString());
throw new HttpException(404, "NotFound");
}
stopWatch.Restart();
XDocument doc = XDocument.Load(result.Content.ReadAsStreamAsync().Result);
stopWatch.Stop();
_logger.Debug($"API result loaded into XDocument. Milliseconds elapsed: {stopWatch.Elapsed.TotalMilliseconds.ToString()}\n");
_logger.Debug(doc.ToString());
IDMSElements elements = getslots.CopyDocToElements(doc);
XMLDocStats docstats = new XMLDocStats(elements);
_logger.Debug(docstats.ToString());
PositionSlots myslots = (PositionSlots)elements;
myslots.UpdateDetails(db);
//because this is dependent upon UpdatePositionSlotId having been run
//need to find a way to force UpdateDetails to run other than calling from Controller??
var mainPositionSlots = myslots.PositionsCurrentAndActive;
var budget = db.Database.SqlQuery<Budget>("GetBudgetForCostCenter #costCenter = {0}", costCenter);
List<Budget> budgetRows = budget.ToList();
JobClassGroups jobClassGroups = new JobClassGroups(mainPositionSlots, budgetRows);
Department dept = db.Departments.AsNoTracking().Where(d => d.CostCenter == costCenter).SingleOrDefault();
var model = new ByCostCenter_vm(dept, myslots, jobClassGroups);
ViewBag.stats = docstats.ToString();
return View("ByCostCenter", model);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
IDMSElements Class:
public class IDMSElements
{
//properties
public ICollection<IDMSElementData> Elements { get; set; }
//constructors
public IDMSElements() { }
public IDMSElements(ICollection<IDMSElementData> elList)
{
Elements = elList;
}
//methods
public static explicit operator PositionSlots(IDMSElements obj)
{
//this is assuming we are looking at a list of elements
//that contains the "current" positions
Dictionary<string, PositionSlotDetail> positionSlots = new Dictionary<string, PositionSlotDetail>();
var sorted = from element in obj.Elements
orderby element.positionNbr
select element;
foreach (IDMSElementData el in sorted)
{
if (!positionSlots.ContainsKey(el.positionNbr))
{
PositionSlotDetail psd = new PositionSlotDetail
{
CostCenter = Int32.Parse(el.UDAKunit),
CostCenter_7Char = el.UDAKunit,
PositionNumber = el.positionNbr,
PositionSlotId = 0,
JobClassId = el.jobClassCode.Replace("-", ""),
JobClassFullDisplayCd = string.Empty,
JobTitle = string.Empty,
SalaryGradeCd = string.Empty,
FTE_percent = el.FTEpercent / 100,
EmployeeId = el.employeeID,
EmployeeName = String.Empty,
PositionEffDate = el.positionEffDate,
PositionEffDateNext = el.positionEffDateNext,
PositionBeginDate = el.positionBeginDate,
PositionEndDate = el.positionEndDate,
DirectLeaderID = string.Empty,
DirectLeaderName = string.Empty,
DirectLeaderNetID = string.Empty,
FLSAstatusCode = el.FLSAstatusCode,
FLSAstatusDesc = el.FLSAstatusDesc,
EmploymentTypeCode = el.employmentTypeCode,
EmploymentTypeDesc = el.employmentTypeDesc,
IsOverloaded = false,
};
positionSlots[el.positionNbr] = psd;
}
Assignment newAssignment = new Assignment
{
PvID = el.employeeID,
AssignBeginDate = el.assignBeginDate,
AssignEndDate = el.assignEndDate,
AssignEffDate = el.assignEffDate,
AssignEffDateNext = el.assignEffDateNext,
};
PositionSlotDetail thePSD = positionSlots[el.positionNbr];
thePSD.Assignments.Add(newAssignment);
if (thePSD.Assignments.Any(assignment => Regex.IsMatch(assignment.PvID, #"^\d+$")))
{
thePSD.Status = "FILLED";
if (thePSD.Assignments.Where(assignment => Regex.IsMatch(assignment.PvID, #"^\d+$")).Count() > 1)
{
thePSD.IsOverloaded = true;
}
}
else
{
thePSD.Status = "VACANT";
}
}
var output = new PositionSlots(positionSlots.Values.ToList());
return output;
}
...
}
PositionSlots class:
public class PositionSlots
{
//Constructor
public PositionSlots(ICollection<PositionSlotDetail> pslist)
{
Positions = pslist;
}
//properites
public ICollection<PositionSlotDetail> Positions { get; }
private bool DetailsUpdated { get; set; } = false;
public IEnumerable<PositionSlotDetail> PositionsCurrentAndActive
{
get
{
return from position in Positions
where position.PositionSlotId > 0 && position.PositionEndDate >= DateTime.Today
select position;
}
}
public IEnumerable<PositionSlotDetail> PositionsNotFoundInPositionControl
{
get
{
return from position in Positions
where position.PositionSlotId == 0
select position;
}
}
public IEnumerable<PositionSlotDetail> PositionsClosed
{
get
{
return from psd in Positions
where psd.PositionEndDate < DateTime.Today
&& psd.PositionSlotId > 0
select psd;
}
}
public decimal ActualFTETotal
{
get
{
return (from position in PositionsCurrentAndActive
from assignment in position.Assignments
where position.Assignments.Count() >= 1 && (!assignment.PvID.Equals("VACANT"))
select position.FTE_percent).Sum();
}
}
public int FilledTotal
{
get
{
return PositionsCurrentAndActive.Where(x => x.Status == "FILLED").Count();
}
}
public int VacantTotal
{
get
{
return PositionsCurrentAndActive.Where(x => x.Status == "VACANT").Count();
}
}
public int OverloadedTotal
{
get
{
return PositionsCurrentAndActive.Where(x => x.IsOverloaded).Count();
}
}
//methods
public void UpdateDetails(PositionControlContext db)
{
if (!DetailsUpdated)
{
UpdateJobClassificationInfo(db);
UpdateEmployeeName(db);
UpdatePositionSlotId(db); //if not found, PositionSlotId = 0
//UpdateIsBudgeted(db);
UpdateDirectLeader(db);
DetailsUpdated = true;
}
else
{
return;
}
}
private void UpdateJobClassificationInfo(PositionControlContext db)
{
string[] jobClassIds = (from x in Positions select x.JobClassId).Distinct().ToArray();
var JobClassList = (from jc in db.JobClassifications where jobClassIds.Contains(jc.JobClassId) select jc).ToDictionary(jc => jc.JobClassId, jc => jc, StringComparer.OrdinalIgnoreCase);
foreach (PositionSlotDetail psd in Positions)
{
if (!string.IsNullOrWhiteSpace(psd.JobClassId) && !psd.JobClassId.Equals("MISSING"))
{
JobClassification jobClassification;
if (JobClassList.TryGetValue(psd.JobClassId, out jobClassification))
{
psd.JobClassFullDisplayCd = jobClassification.JobClassFullDisplayCd;
psd.JobTitle = jobClassification.JobTitle;
psd.SalaryGradeCd = jobClassification.SalaryGradeCd;
}
else
{
psd.JobClassFullDisplayCd = ($"{psd.JobClassId} not found in view V_JobClassifications.");
psd.JobTitle = ($"{psd.JobClassId} not found in view V_JobClassifications.");
psd.SalaryGradeCd = "--";
}
}
else
{
psd.JobClassFullDisplayCd = "MISSING";
psd.JobTitle = "MISSING";
}
}
return;
}
private void UpdateEmployeeName(PositionControlContext db)
{
string[] empIdsStr = (from position in Positions
from assignment in position.Assignments
where (!assignment.PvID.Equals("VACANT"))
select assignment.PvID).Distinct().ToArray();
// Positions.SelectMany(x => x.Assignments).SelectMany(x => x.PvID).ToArray();
//string[] empIdsStr = (from x in Positions where (!x.EmployeeId.Contains("VACANT")) select x.EmployeeId).Distinct().ToArray();
//int[] empIdsInt = Array.ConvertAll(empIdsStr, int.Parse);
var EmployeeList = (from emp in db.IdAM_personLU where empIdsStr.Contains(emp.pvID) select emp).ToDictionary(emp => emp.pvID,
emp => emp.EmployeeFullName, StringComparer.OrdinalIgnoreCase);
EmployeeList["VACANT"] = "VACANT";
foreach (PositionSlotDetail psd in Positions)
{
string empName;
if (EmployeeList.TryGetValue(psd.EmployeeId, out empName))
{
psd.EmployeeName = empName;
}
else
{
psd.EmployeeName = ($"{psd.EmployeeId} not found in Employee table.");
}
foreach (Assignment emp in psd.Assignments)
{
string empName2;
if (EmployeeList.TryGetValue(emp.PvID, out empName2))
{
emp.EmpDisplayName = empName2;
}
else
{
emp.EmpDisplayName = ($"{psd.EmployeeId} not found in Employee table.");
}
}
}
return;
}
private void UpdateDirectLeader(PositionControlContext db)
{
string[] empIdsStr = (from x in Positions where (!x.EmployeeId.Contains("VACANT")) select x.EmployeeId).Distinct().ToArray();
//int[] empIdsInt = Array.ConvertAll(empIdsStr, int.Parse);
Dictionary<string, IdAM_arborLU> DirectLeader = new Dictionary<string, IdAM_arborLU>();
var EmployeeDirectLeaderList = (from emp in db.IdAM_arborLU where empIdsStr.Contains(emp.emp_pvID) select emp).ToDictionary(emp => emp.emp_pvID,
emp => emp, StringComparer.OrdinalIgnoreCase);
foreach (PositionSlotDetail psd in Positions)
{
if (psd.EmployeeId != "VACANT") //will just leave DirectLeaderId and DirectLeaderName as string.Empty
{
IdAM_arborLU supervisor;
if (EmployeeDirectLeaderList.TryGetValue(psd.EmployeeId, out supervisor))
{
psd.DirectLeaderName = supervisor.sup_name;
psd.DirectLeaderID = supervisor.sup_pvID;
psd.DirectLeaderNetID = supervisor.sup_netID;
}
else
{
psd.DirectLeaderName = ($"{psd.EmployeeId} not found in Arbor table.");
}
}
foreach (Assignment emp in psd.Assignments)
{
if (psd.EmployeeId != "VACANT")
{
IdAM_arborLU supervisor2;
if (EmployeeDirectLeaderList.TryGetValue(psd.EmployeeId, out supervisor2))
{
emp.DirectLeaderName = supervisor2.sup_name;
emp.DirectLeaderID = supervisor2.sup_pvID;
emp.DirectLeaderNetID = supervisor2.sup_netID;
}
else
{
emp.DirectLeaderName = ($"{psd.EmployeeId} not found in Arbor table.");
emp.DirectLeaderID = "--";
emp.DirectLeaderNetID = "--";
}
}
}
}
return;
}
private void UpdatePositionSlotId(PositionControlContext db)
{
string[] posnumber = (from x in Positions
select x.PositionNumber).ToArray();
var slots = (from ps1 in db.PositionSlots
where posnumber.Contains(ps1.PositionNumber)
select ps1).ToDictionary(ps => ps.PositionNumber.Trim(), ps => ps.PositionSlotId, StringComparer.OrdinalIgnoreCase);
foreach (PositionSlotDetail psd in Positions)
{
int posSlotId = 0;
if (slots.TryGetValue(psd.PositionNumber, out posSlotId))
{
psd.PositionSlotId = posSlotId;
}
}
return;
}
private void UpdateIsBudgeted(PositionControlContext db)
{
string[] posnumber = (from x in Positions
select x.PositionNumber).ToArray();
var slots = (from ps1 in db.PositionSlots
where posnumber.Contains(ps1.PositionNumber)
select ps1).ToDictionary(ps => ps.PositionNumber.Trim(), ps => ps.IsBudgeted, StringComparer.OrdinalIgnoreCase);
foreach (PositionSlotDetail psd in Positions)
{
bool isbudgeted = false;
if (slots.TryGetValue(psd.PositionNumber, out isbudgeted))
{
psd.IsBudgeted = isbudgeted;
}
}
return;
}
}
you can achieve this by writing a method:
IDMSElement.ToPositionSlot(db)
and then use it as follow:
PositionSlots myslots = elements.Select(x => x.ToPositionSlot(db))

How to assign a value to a field in different class?

In this program, I have 2 classes Application and Customer. I want to initialize Standard Fare with some value which should be entered by the user. Standard Fare field is in Customer class.
I did this, but it is not showing the desired result. When Calculate function is called The Value of Standard fare is becoming zero.
When I initialize the value of STANDARD_FARE in Customer class itself, then the program is working as desired.
How can I input the value given by the user to STANDARD_FARE?
Also methods like GetAge(), GetPassNo() in Application class is not returning the value of the same.
class Application
{
private static int Nop ;
private static double TotalFare=0;
Customer cust= new Customer();
static void Main(string[] args)
{
Application obj = new Application();
Console.Write("Enter the STANDARD RATE of the tour ");
obj.cust.StandardFare = int.Parse(Console.ReadLine());
a:
Console.Clear();
Console.WriteLine("Enter the number of passengers");
Nop = int.Parse(Console.ReadLine());
Application[] app = new Application[Nop];
if (Nop <= 0)
{
Console.WriteLine("Please enter a valid number of passengers");
Console.ReadKey();
goto a;
}
for (int i = 0; i < Nop; i++)
{
app[i] = new Application();
app[i].GetInformationFromCust();
}
for (int j = 0; j < Nop; j++)
{
app[j].cust.Display();
}
}
public int GetInformationFromCust()
{
b:
Console.Clear();
int slen = 0;
Console.WriteLine("Enter the title of the passenger");
cust.Customer_Title = Console.ReadLine();
Console.WriteLine("\r\nEnter passenger's First name :");
cust.Customer_FName = Console.ReadLine();
Console.WriteLine("\r\nEnter passenger's Last name :");
cust.Customer_LName = Console.ReadLine();
slen = cust.Customer_FName.Length + cust.Customer_LName.Length;
if (slen < 5 || slen > 15)
{
Console.WriteLine("\r\nName should be between 5 to 15 characters, Please try again ");
Console.ReadLine();
goto b;
}
c:
long x = 0, len = 0;
Console.WriteLine("\r\nEnter the passport number of the passenger ");
cust.CustomerPassNo = int.Parse(Console.ReadLine());
x = cust.CustomerPassNo;
while (x > 0)
{
x = x / 10;
++len;
}
if (len != 8)
{
Console.WriteLine("\r\nInvalid passport number, passport should be of 8 digits ");
goto c;
}
d:
Console.WriteLine("\r\nEnter the age of the passenger :");
cust.Customer_Age = int.Parse(Console.ReadLine());
if (cust.Customer_Age < 0)
{
Console.WriteLine("\r\nInvalid age, please enter a valid age ");
goto d;
}
cust.CalculatePrice();
return 0;
}
public int GetAge()
{
return cust.Customer_Age;
}
public double GetAirFare()
{
return cust.CustomerTicket ;
}
public long GetPassportNo()
{
return cust.CustomerPassNo;
}
public string GetTitle()
{
return cust.Customer_Title;
}
}
class Customer
{
const double K_DISCOUNT = 0.10;
const double S_DISCOUNT = 0.20;
private double STANDARD_FARE;
private string CustomerName { get; set; }
private int CustomerAge;
private string CustomerFName;
private string CustomerLName;
private long CustomerPassport;
private double CustomerPrice;
private string CustomerTitle;
private double KidDiscount;
private double SeniorDiscount;
public Customer()
{
this.KidDiscount = K_DISCOUNT;
this.SeniorDiscount = S_DISCOUNT;
}
public double StandardFare
{
get { return STANDARD_FARE; }
set { STANDARD_FARE = value; }
}
public int Customer_Age
{
get { return CustomerAge; }
set { CustomerAge = value; }
}
public string Customer_Title
{
get { return CustomerTitle; }
set { CustomerTitle = value; }
}
public string Customer_FName
{
get { return CustomerFName; }
set { CustomerFName = value; }
}
public string Customer_LName
{
get { return CustomerLName; }
set { CustomerLName = value; }
}
public long CustomerPassNo
{
get { return CustomerPassport; }
set { CustomerPassport = value; }
}
public double CustomerTicket
{
get { return CustomerPrice; }
set { CustomerPrice = value; }
}
public int CalculatePrice()
{
if (CustomerAge < 3)
{
CustomerPrice = 0;
}
else if (CustomerAge >= 3 && CustomerAge < 18)
{
CustomerPrice = STANDARD_FARE - (STANDARD_FARE * KidDiscount);
}
else if (CustomerAge > 65)
{
CustomerPrice = STANDARD_FARE - (STANDARD_FARE * SeniorDiscount);
}
else
{
CustomerPrice = STANDARD_FARE;
}
return 0;
}
public void Display()
{
//some code here
}
}
You are populating your array app with instances of Application that still have the default STANDARD_FARE value (which is 0.0), because you have never set it on those instances. You only set it on the obj.cust instance, which you never again use. Because STANDARD_FARE is an instance variable, changes to it have no affect on other (or future) instances.
You have the same problem in reverse with all the Application.Get* functions; they are getting properties of an object (obj.cust) that has never had any properties set, other than StandardFare/STANDARD_FARE.
The most obvious fix is to do away with obj and obj.cust entirely - they have no use other than to be confusing - and make STANDARD_FARE a static variable (and its setter StandardFare a static property).
BTW, your naming conventions are terrible and inconsistent; if I were your grader I'd dock you points for using unclear variable names(app, nop), and for using ALL_CAPS for non-constants (STANDARD_FARE). I'd also object to using a private auto-backed property (CustomerName, which is also never used) instead of simply a private variable, for not using auto-backed properties elsewhere (StandardFare as an explicitly-coded public getter and setter for STANDARD_FARE, etc.), and for copying constant values into non-settable instance variables (K_DISCOUNT to KidDiscount; just use the constant directly, or at least make KidDiscount static and add some non-private access to it). As others have mentioned, you of course should not be using goto in place of loops. I'll also mention the error-prone and inefficient checking the length of the passport number by repeated division instead of simply checking whether it's less than 99999999 (in theory, passport numbers might start with a zero, which would look like less than 8 digits after parsing, but you could also make sure it's greater than 10000000 if you want).

return results from a third method to another method

I have following problem:
In method 1 I get a string list and pass it to method
In method 2 I generate a 2d array based on the list and pass the list further to method 3
In method 3 I convert the 2d array to a data table
Now I want to return the data table back to method 1, but I don't know how to do that. The picture shows my problem:
My code:
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
Document doc = commandData.Application.ActiveUIDocument.Document;
View activeView = commandData.View;
if(activeView is ViewSchedule)
{
GetDimensions(activeView as ViewSchedule);
}
return Result.Succeeded;
}
public void GetDimensions(ViewSchedule schedule)
{
TableSectionData bodySelection = schedule.GetTableData().GetSectionData(SectionType.Body);
int numberOfRows = bodySelection.NumberOfRows;
int numberOfColumns = bodySelection.NumberOfColumns;
string[,] values = new string[numberOfRows,numberOfColumns];
FillArray(SectionType.Body, bodySelection, numberOfColumns, numberOfRows, values, schedule);
}
public void FillArray(SectionType secType, TableSectionData data,
int numberOfColumns, int numberOfRows, string[,] values, ViewSchedule schedule)
{
for (int r = data.FirstRowNumber; r < numberOfRows; r++)
{
for (int c = data.FirstColumnNumber; c < numberOfColumns; c++)
{
values[r, c] = schedule.GetCellText(secType, r, c);
}
}
}
Now I want to return the filled array to Execute.
It's impossible to pass it this way directly. There are three options:
make method 2 take the result and pass it back:
int Method2()
{
var method3Result = Method3();
return method3Result;
}
void Method1()
{
var result = Method2(); //indirectly gets from Method3
}
provide a shared state:
public class Method3Result { public int Value { get; set; } }
public class X
{
private Method3Result method3Result = new Method3Result();
public void Method1()
{
Method2();
//process result from method3Result
}
public void Method2()
{
Method3();
}
public void Method3()
{
method3Result.Value = 3;
}
}
provide a callback:
public void Method1()
{
int method3Result;
Method2(value => method3Result = value);
}
public void Method2(Action<int> callback)
{
Method3(callback);
}
public void Method3(Action<int> callback)
{
callback(3);
}
}
In your case option 1 seems straightforward:
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
Document doc = commandData.Application.ActiveUIDocument.Document;
View activeView = commandData.View;
string[,] values = null;
if (activeView is ViewSchedule)
{
values = GetDimensions(activeView as ViewSchedule);
}
return Result.Succeeded;
}
public string[,] GetDimensions(ViewSchedule schedule)
{
//...
return values;
}
Also, it seems that it would be clearer to change FillArray to something like CreateArray and make it also return the array:
public void FillArray(SectionType secType, TableSectionData data, int numberOfColumns, int numberOfRows, string[,] values, ViewSchedule schedule)
{
string[,] values = new string[numberOfRows,numberOfColumns];
for (int r = data.FirstRowNumber; r < numberOfRows; r++)
{
for (int c = data.FirstColumnNumber; c < numberOfColumns; c++)
{
values[r, c] = schedule.GetCellText(secType, r, c);
}
}
return values;
}
so it's easier to use.

Categories

Resources