Telegram API Code - c#

please Help us,
Telegram API code :
messages.dialogs#15ba6c40 dialogs:Vector<Dialog> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Dialogs;
messages.dialogsSlice#71e094f3 count:int dialogs:Vector<Dialog> messages:Vector<Message> chats:Vector<Chat> users:Vector<User> = messages.Dialogs;
---functions---
messages.getDialogs#eccf1df6 offset:int max_id:int limit:int = messages.Dialogs;
how i can make class for this ? - using TLSharp;
i have this class in Request folder ( from TLSharp );
how i can edit this class or create new class and work with Telegram API method ? ( telegram API is very Unclear for we )
using System;
using System.Collections.Generic;
using System.IO;
using TLSharp.Core.MTProto;
namespace TLSharp.Core.Requests
{
class GetHistoryRequest : MTProtoRequest
{
InputPeer _peer;
int _offset;
int _max_id;
int _limit;
public List<Message> messages;
public List<Chat> chats;
public List<User> users;
public GetHistoryRequest(InputPeer peer, int offset, int max_id, int limit)
{
_peer = peer;
_offset = offset;
_max_id = max_id;
_limit = limit;
}
public override void OnSend(BinaryWriter writer)
{
writer.Write(0x92a1df2f);
_peer.Write(writer);
writer.Write(_offset);
writer.Write(_max_id);
writer.Write(_limit);
}
public override void OnResponse(BinaryReader reader)
{
bool messagesSlice = reader.ReadUInt32() == 0xb446ae3; // else messages#8c718e87
if (messagesSlice) reader.ReadInt32(); // count
// messages
var result = reader.ReadUInt32(); // vector#1cb5c415
int messages_len = reader.ReadInt32();
messages = new List<Message>(messages_len);
for (var i = 0; i < messages_len; i++)
{
var msgEl = TL.Parse<Message>(reader);
messages.Add(msgEl);
}
// chats
reader.ReadUInt32();
int chats_len = reader.ReadInt32();
chats = new List<Chat>(chats_len);
for (int i = 0; i < chats_len; i++)
chats.Add(TL.Parse<Chat>(reader));
/*
// users
reader.ReadUInt32();
int users_len = reader.ReadInt32();
users = new List<User>(users_len);
for (int i = 0; i < users_len; i++)
users.Add(TL.Parse<User>(reader));
*/
}
public override void OnException(Exception exception)
{
throw new NotImplementedException();
}
public override bool Confirmed => true;
public override bool Responded { get; }
}
}

Related

TorchSharp Exception with GPU

In my codebase I use TorchSharp to train a regression model. When using the CPU everything works fine, just when using the GPU i get a KeyNotFoundException at the optimizer.step() method call.
I have extracted the code into an example program that can be used to reproduce the problem.
It seems to have to do something with the custom CancelOut module and its weight parameters. If I remove it from the Sequential module the exception does not happen.
I am wondering if I am doing something wrong or if this is a TorchSharp bug that only occurs with GPU training, since CPU training works fine.
Here is the code:
using TorchSharp;
using TorchSharp.Modules;
using TorchSharp.Utils;
using static TorchSharp.torch.nn;
var module = Sequential(
new CancelOut(10),
Linear(10, 1)
);
var x = Enumerable.Range(0, 100).Select(x => new float[10]).ToArray();
var y = new float[100];
var trainer = new RegressionTorchTrainer(module, x, y, device: torch.CUDA);
trainer.Train();
public class CancelOut : Module
{
private readonly Parameter weights;
public CancelOut(int size) : base(nameof(CancelOut))
{
weights = Parameter(torch.zeros(size) + 4);
RegisterComponents();
}
public override torch.Tensor forward(torch.Tensor x)
{
return (x * torch.sigmoid(weights));
}
}
public class RegressionTorchTrainer : IDisposable
{
private readonly torch.Device? device;
private readonly torch.nn.Module module;
private readonly torch.Tensor xt;
private readonly torch.Tensor yt;
private readonly torch.Tensor wt;
public RegressionTorchTrainer(torch.nn.Module module, float[][] x, float[] y, float[]? weight = null, torch.Device? device = null)
{
this.device = device;
this.module = module;
xt = torch.tensor(x.SelectMany(x => x).ToArray(), x.Length, x[0].Length, device: this.device);
yt = torch.tensor(y, device: this.device);
wt = weight != null ? torch.tensor(weight, device: this.device) : torch.ones(y.Length, device: device);
}
public void Train(int iterations = 100, int batchSize = 128, double learningRate = 0.001, torch.optim.Optimizer? optimizer = null, long? seed = null)
{
if (seed != null)
torch.random.manual_seed(seed.Value);
var disposeOptimizer = optimizer == null;
optimizer ??= torch.optim.SGD(module.parameters(), learningRate);
var criterion = torch.nn.functional.mse_loss(torch.nn.Reduction.None);
if (device != null)
module.to(device);
module.train();
for (int iter = 0; iter < iterations; iter++)
{
using var permutation = torch.randperm(xt.size(0), device: device);
for (int i = 0; i < xt.size(0); i += batchSize)
{
using var indices1 = torch.arange(i, Math.Min(i + batchSize, xt.size(0)), device: device);
using var indices2 = permutation.index_select(0, indices1);
using var xb = xt.index_select(0, indices2);
using var yb = yt.index_select(0, indices2);
using var wb = wt.index_select(0, indices2);
using var prediction = module.forward(xb).view(-1);
using var loss = criterion(prediction, yb);
using var wloss = loss * wb;
using var mloss = wloss.mean();
optimizer.zero_grad();
mloss.backward();
optimizer.step();
GC.Collect(0);
}
}
if (disposeOptimizer)
optimizer.Dispose();
}
public void Dispose()
{
xt.Dispose();
yt.Dispose();
GC.SuppressFinalize(this);
}
}
public class RegressionTorchModel : IDisposable
{
private readonly torch.Device? device;
private readonly torch.nn.Module module;
private readonly bool ownsModule;
public RegressionTorchModel(torch.nn.Module module, bool ownsModule = true, torch.Device? device = null)
{
this.device = device;
this.module = module;
this.ownsModule = ownsModule;
}
public float Predict(float[] x)
{
module.to(device).eval();
using var xt = torch.tensor(x, device: device);
using var prediction = module.forward(xt);
using var predictionCpu = prediction.cpu();
return predictionCpu.item<float>();
}
public float[] Predict(float[][] x)
{
module.to(device).eval();
using var xt = torch.tensor(x.SelectMany(x => x).ToArray(), x.Length, x[0].Length, device: device);
using var prediction = module.forward(xt);
using var predictionCpu = prediction.cpu();
using var accessor = new TensorAccessor<float>(predictionCpu);
return accessor.ToArray();
}
public static RegressionTorchModel Load(string filename, torch.Device? device = null)
=> new(torch.nn.Module.Load(filename), true, device);
public void Save(string filename)
=> module.Save(filename);
public void Dispose()
{
if (ownsModule)
module.Dispose();
}
}

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;
}
}
}
}

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.

c# Anonymous Methods variable scope strange behavior with yield return,Is a compiler bug or work as intend?

I am using yield return stuff as coroutine in my unity 3d program.
I am using Unity3d 4.3 with c# 3.5.
If this is a bug in c#,where should I report it to c# team?
public class ClosureTest : TestMonoBehaviour {
public void doTest() {
var a = Test3();
a.MoveNext();
a.MoveNext();
}
class Ctest2 {
public int a;
}
class Ctest1 {
public Ctest2 t2;
}
IEnumerator Test3() {
yield return null;
var c2FuncList = new List<Func<Ctest2>>();
var c1List = new List<Ctest1>();
for (var i = 0; i < 3; i++)
{
var ic1 = new Ctest1();
ic1.t2 = new Ctest2();
ic1.t2.a = i;
c1List.Add(ic1);
}
foreach (var ic1 in c1List)
{
var ic2 = ic1.t2;
c2FuncList.Add(delegate {
return ic2;
});
}
for (var i = 0; i < 3; i++)
{
Equal(c2FuncList[i]().a, i); // always 2.
}
}
}
If I run doTest,Equal in that class will say need 0,but get 2.

C# Inconsistent accessibility

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.

Categories

Resources