Guest User

Guest User

  • Tech Writer
  • 270
  • 1.8k

C# How to get Konsole output into files like this assignments?

Jul 22 2022 1:08 PM

Hello

I'm currently learning C# and I have a learning task that I can't quite solve.

Is there someone in the forum who can look through my task and help me with the solution?

Here the two assignments:

For this submission task, create a new project "ESA_Project" in which you copy the latest status of the aircraft project. Complete the project with a Programming that logs a flight's position data to a file can become.

  • The log file should be placed in the executable folder of the program ("Release" or "Debug") can be written
  • The name of each log file should follow the pattern 
  • _---.bin
    be assembled. This can be generated and differentiated programmatically reliably multiple log files with this time-dependent encoding.
  • A string containing the following information should first be written to the file summarizes:
  • Flight "" (type "") departs from position "--" with target position "--".
  • This is the header of the log file, which is then followed by the data.
  • Again, all expressions with angle brackets are replaced by concrete ones Replace values from programming.
  • The x, y and h data of the current position are then to be added to the file be written as int values until the flight is complete. These are, so to speak the data of the file.
  • The logging should be made dependent on the value of a "switch", which you define as a static variable in the Program class:

public static bool log = true;

  • When this switch is set to true, logging occurs when it is set to false is not logged.
  • This task is not only about the technical realization of the aforementioned Requirements, but mainly to fundamental considerations object-oriented Programming. You should e.g. B. If you have the necessary writer declare, make it clear that a writer corresponds to a flight recorder and check which type of aircraft can use a flight recorder at all. examples for such considerations of object-oriented planning there was in this issue, but also when planning the project in the study booklet CSH01B - e.g. B. to settlement of the transponder.

Based on these considerations, the following questions need to be answered:

1a. Where do you declare the Writer object so that it is in the places in the program where you want it to be to whom it is needed is also known?

1b.At what point in the program do you assemble the file path, create the writer and write the header?

1c. Where in the program do you write the data for the x, y, and h values?

1d. At what point in the program do you close the writer?

1e. In each case, how do you ensure that these operations only take place if the "switch" in the program class is set to true?

Enter the program code in each case and briefly explain your programming.

A notice:

BinaryWriter knows a method
public virtual void Write ( string value )
... which not only writes the string to be specified as a parameter to the file, but before that stores information about the length of the string (compare the .NET documentation).

BinaryReader knows a mirror image method
public virtual string ReadString ()
... which first evaluates the length information stored in the binary file and then precisely reads the length of the string that follows, so that the read pointer for further read operations is set exactly to the following byte.


2. Add in the program class FliegerProject (for submission task 3) a method 

public void ESA4Out(string logpath)

My name for this:  public void ProtocolOutput(string protokoll)
This method aims to generate the binary of a flight using programming in ESA 3 is created, read back and output its content to the console. As a result this could look like in Fig. G.1 for two flights:


Add calls to this "ESA4Out" method at the end of the program control in "program bars". So that the "ESA4Out" method always outputs the last logged flight save the path to its log file in a new property, which is only equipped with a get accessor for retrieval. This Property is created where the logging also takes place. My ESA4Out Method is named ProtokollAusgeben.
When programming "ESA4Out" the internal file structure is the log file should be noted, so that in the console first the header and then the flight data be issued. The flight dates begin with the start and end with the reached target position. Because of the rough timing and the resulting rough Position calculations are the specified and the actually reached target position
differ from each other. Explain the main steps of your solution with code snippets.

Thats my Code:

using System;
using System.Threading;
using System.IO;

/* Code Translated in English */

namespace Engl_Code
{
    #region Transponder, Interface, Delegate und Enumerator
    delegate void TransponderDel(string identifier, Position pos);
    delegate void AirplaneRegisterDel(); 
    interface ITransponder
    {
        void Transpond(string identifier, Position pos);
    }
    enum Airbus : short { A300, A310, A318, A319, A320, A321, A330, A340, A380 }
    #endregion

    #region Struct Position
    public struct Position
    {
        public int x, y, h;
        public Position(int x, int y, int h)
        {
            this.x = x;
            this.y = y;
            this.h = h;
        }
        public void ChangePosition(int deltaX, int deltaY, int deltaH)
        {
            x = x + deltaX;
            y = y + deltaY;
            h = h + deltaH;
        }
        public void ChangeHeight(int deltaH)
        {
            h = h + deltaH;
        }
    }
    #endregion

    #region Class Aircraft
    abstract class Aircraft
    {
        protected string identifier;
        public string Identifier
        {
            protected set { Identifier = value; }
            get { return identifier; }
        }

        protected Position pos;
        public abstract void Rising(int meter);
        public abstract void Falling(int meter);
    }
    #endregion

    #region Class Airplane
    class Airplane : Aircraft
    {
        #region Declaration Position, Rising and Falling, Altitude
        protected Position targetPos;
        protected int distancePerBeat;
        protected int altitude;
        protected int risePerBeat;
        protected int riseDownPerBeat;
        protected bool rise = false;
        protected bool fall = false;
        #endregion

        #region Method StartOptions
        public void StartOptions(Position targetPos, int distancePerBeat, int altitude, int risePerBeat, int riseDownPerBeat)
        {
            // neu Lektion 3
            this.targetPos = targetPos;
            this.distancePerBeat = distancePerBeat;
            this.altitude = altitude;
            this.risePerBeat = risePerBeat;
            this.riseDownPerBeat = riseDownPerBeat;
            this.rise = true;
        }
        #endregion

        #region Methods Airplane - Rising - Falling
        public Airplane(string identifier, Position startPos)
        {
            this.identifier = identifier;
            this.pos = startPos;
        }

        public override void Rising(int meter)
        {
            pos.ChangeHeight(meter);
            Console.WriteLine(identifier + "rise " + meter + "Meter, Höhe =" + pos.h);
        }

        public override void Falling(int meter)
        {
            pos.ChangeHeight(-meter);
            Console.WriteLine(identifier + "fall " + meter + "Meter, Height =" + pos.h);
        }
        #endregion

        #region ProtocolFile assemble
        public string ProtocolFile()
        {
            DateTime timer = DateTime.Now;

            string setTime = "" + timer.Year + timer.Month + timer.Day + "_" + timer.Hour + "-" + timer.Minute + "-" + timer.Second + "";
            string path = @".\" + identifier + "_" + setTime + ".bin";
            return path;
        }
        #endregion
    }
    #endregion

    #region Class fixedWingAircraft - ITransponder
    class fixedWingAircraft : Airplane, ITransponder
    {
        #region Declaration BinaryWriter - //Protocol

        protected BinaryWriter bwriter;
        protected string protocol;
        public string Protocol
        {
            set { Protocol = value; }
            get { return protocol; }
        }
        #endregion

        #region Constructor fixedWingAircraft
        protected StreamWriter swriter;
        public fixedWingAircraft(string identifier, Position startPos) : base(identifier, startPos)
        {
            this.swriter = new StreamWriter(ProtocolFile());
        }
        #endregion

        #region Method Transpond
        public void Transpond(string identifier, Position pos)
        {
            double abstand = Math.Sqrt(Math.Pow(this.pos.x - pos.x, 2) + Math.Pow(this.pos.y - pos.y, 2));

            DateTime timestamp = DateTime.Now;

            if (identifier.Equals(this.identifier))
            {
                Console.Write("{0}:{1}:{2}", timestamp.Hour, timestamp.Minute, timestamp.Second);
                Console.Write("\t{0} {1}--{2}--{3}\n", this.identifier, base.pos.x, base.pos.y, base.pos.h);

                //Neu: ESA_Projekt Aufgabe 3
                if (Program.log && bwriter != null)
                {
                    //using(BinaryWriter bwriter = new BinaryWriter)
                    bwriter.Write(pos.x);
                    bwriter.Write(pos.y);
                    bwriter.Write(pos.h);
                }
            }
        }
        #endregion

        // Neu Lektion 3
        double a, b, alpha, a1, b1;
        bool landed = false;

        #region Method InitiateFalling - CalculatePosition - TargetDistance
        private bool InitiateFalling()
        {
            double distance = Math.Sqrt(Math.Pow(distancePerBeat, 2) - Math.Pow(riseDownPerBeat, 2));
            int sinkdistance = (int)(distance * (pos.h - targetPos.h) / riseDownPerBeat);
            int targetdistance = TargetDistance();
            if (sinkdistance >= targetdistance)
            {
                return true;
            }
            else
                return false;
        }

        private void CalculatePosition(double distance, int risePerBeat)
        {
            // modifizierte Übernahme der bisherigen Berechungen aus "Manage"
            a = targetPos.x - pos.x;
            b = targetPos.y - pos.y;
            alpha = Math.Atan2(b, a);
            a1 = Math.Cos(alpha) * distance;
            b1 = Math.Sin(alpha) * distance;
            pos.ChangePosition((int)a1, (int)b1, risePerBeat);
        }

        private int TargetDistance()
        {
            return (int)Math.Sqrt(Math.Pow(targetPos.x - pos.x, 2) + Math.Pow(targetPos.y - pos.y, 2));
        }
        #endregion

        #region Method Manage
        public void Manage()
        {
            if (rise)
            {
                if (this.InitiateFalling())
                {
                    rise = false;
                    fall = true;
                }
                else if (pos.h > altitude)
                {
                    rise = false;
                }
            }
            else if (fall)
            {
                if (pos.h <= targetPos.h + riseDownPerBeat)
                    landed = true;
            }
            else
            {
                //Horizontalflug
                if (this.InitiateFalling())
                {
                    fall = true;
                }
            }
            if (!landed)
            {
                // Zunächst die aktuelle Position ausgeben:
                Program.transponder(identifier, pos);

                //"Strecke" (am Boden) berechnen:
                if (rise)
                {
                    double distance = Math.Sqrt(Math.Pow(distancePerBeat, 2) - Math.Pow(risePerBeat, 2));
                    this.CalculatePosition(distance, risePerBeat);
                }
                else if (fall)
                {
                    double distance = Math.Sqrt(Math.Pow(distancePerBeat, 2) - Math.Pow(riseDownPerBeat, 2));
                    this.CalculatePosition(distance, -riseDownPerBeat);
                }
                else
                {
                    // im Horizontalflug ist "distance" gleich "distancePerBeat"
                    this.CalculatePosition(distancePerBeat, 0);
                }
            }
            else
            {
                // Flieger derigistrieren, Transponder abschalten, Abschlussmeldung
                Program.airplaneRegister -= this.Manage;
                Program.transponder -= this.Transpond;
            }
        }
        #endregion
    }
    #endregion

    #region Class JetPlane
    class JetPlane : fixedWingAircraft
    {
        public Airbus typ;

        #region Passengers booking
        private int seats;
        private int passengers;
        public int Passengers
        {
            set
            {
                if (seats < (passengers + value))
                    Console.WriteLine("Keine Buchung: Die " + "Fluggastzahl würde mit der Zubuchung " + "von {0} Plätzen die verfügbaren Plätze " + "von {1} um {2} übersteigen!", value, seats, value + passengers - seats);
                else
                    passengers += value;
            }
            get { return passengers; }
        }
        #endregion

        #region Constructor JetPlane
        public JetPlane(string identifier, Position startPos) : base(identifier, startPos)
        {
            bool initialized = this.TakeOff();
            if (initialized)
            {
                Program.transponder += this.Transpond;
                Program.airplaneRegister += this.Manage;
            }
        }
        #endregion

        #region Method TakeOff
        public bool TakeOff()
        {
            #region StreamReader zum Einlesen der .init Dateien
            string pfad = ".\\" + identifier + ".init";
            StreamReader reader;
            try
            {
                reader = new StreamReader(File.Open(pfad, FileMode.Open));
            }
            catch (IOException e)
            {
                Console.WriteLine("{0} Fehler beim Zugriff auf die Datei " + pfad, e.GetType().Name);
                return false;
            }

            int[] data = new int[9];
            for (int i = 0; i < 9; i++)
            {
                string str = reader.ReadLine();
                str = str.Substring(str.IndexOf('=') + 1);
                data[i] = Int32.Parse(str);
            }
            reader.Close();
            #endregion

            this.targetPos.x = data[0];
            this.targetPos.y = data[1];
            this.targetPos.h = data[2];
            distancePerBeat = data[3];
            altitude = data[4];
            risePerBeat = data[5];
            riseDownPerBeat = data[6];

            Array typen = Enum.GetValues(typeof(Airbus));
            this.typ = (Airbus)typen.GetValue(data[7]);
            seats = data[8];

            Console.ForegroundColor = ConsoleColor.DarkRed;
            Console.WriteLine("Flug {0} (Typ {1}) startet an Position " + pos.x + "--" + pos.y + "--" + pos.h + " mit Zielposition " + targetPos.x + "--" + targetPos.y + "--" + targetPos.h, identifier, typ);
            Console.ResetColor();

            rise = true;
            Console.WriteLine();
            return true;
        }
        #endregion

        #region Method BlackBox
        public void BlackBox()
        {
            if (Program.log)
            {
                DateTime timestamp = DateTime.Now;
                string pfad = identifier + "_" + timestamp.Year + timestamp.Month + timestamp.Day + "_" + timestamp.Hour + ":" + timestamp.Minute + ":" + timestamp.Second + ".bin";
                protocol = ProtocolFile();
                if (TakeOff() == true)
                {
                    bwriter = new BinaryWriter(File.Open(protocol, FileMode.Create));
                    string header1 = "Flug \"" + identifier + "\" (Typ " + this.typ + ") startet an Position " + pos.x + "--" + pos.y + "--" + pos.h + " mit Zielposition " + targetPos.x + "--" + targetPos.y + "--" + targetPos.h;
                    bwriter.Write(header1);
                }
                else if (TakeOff() == true)
                {
                    bwriter = new BinaryWriter(File.Open(protocol, FileMode.Create));
                    string header2 = "Flug \"" + identifier + "\" (Typ " + this.typ + ") startet an Position " + pos.x + "--" + pos.y + "--" + pos.h + " mit Zielposition " + targetPos.x + "--" + targetPos.y + "--" + targetPos.h;
                    bwriter.Write(header2);
                }
            }
        }
        #endregion

        #region Write Header Test
        //public void WriteHeader()
        //{
        //    File.WriteAllText(Dateipfad(), "Flug " + identifier + " startet an Position " + pos.x + "-" + pos.y + "-" + pos.h + " mit Zielposition " + targetPos.x + "-" + targetPos.y + "-" + targetPos.h); //Schreibt die Kopfzeile in die Datei
        //}

        //public void WritePosition(Position pos)
        //{
        //    File.AppendText("\n" + pos.x + " " + pos.y + " " + pos.h);//Schreibt eine Position in die Liste der Datei
        //}
        #endregion


        #region Method Booking
        public void Booking(int places)
        {
            Passengers += places;
        }
        #endregion
    }
    #endregion

    #region Class Program
    class Program
    {
        #region Declaration for Transponder, Register and Protocol
        // static Variable als Schalter für das Flugprotocol
        public static bool log = true;

        public static TransponderDel transponder;
        public delegate void AirplaneRegisterDel();
        public static AirplaneRegisterDel airplaneRegister;
        #endregion

        #region Method ProgramBeat
        public void ProgramBeat()
        {
            JetPlane plane1 = new JetPlane("LH 500", new Position(3500, 1400, 180));
            JetPlane plane2 = new JetPlane("LH 3000", new Position(3000, 2000, 100));

            while (airplaneRegister != null)
            {
                airplaneRegister();
                Console.WriteLine();
                Thread.Sleep(1000);
            }
        }
        #endregion

        #region Method ProtocolOutput 
        //Neu: ESA_Projekt Aufgabe 4
        public void ProtocolOutput (string protocol)
        {
            BinaryReader reader = new BinaryReader(File.Open(protocol, FileMode.Open));
            Console.WriteLine(reader.ReadString());
            bool goOn = true;
            while (goOn)
            {
                try
                {
                    for (int i = 0; i < 3; i++)
                        Console.Write("\t{0}", reader.ReadInt32());
                }
                catch
                {
                    goOn = false;
                }
                reader.Close();
                Console.WriteLine();
            }
        }
        #endregion

        static void Main(string[] args)
        {
            Program test = new Program();
            test.ProgramBeat();
            Console.ReadLine();
        }
    }
    #endregion
}

And here the content of the 2 files that are required (debug folder) to start the program.
The files  are simple textfiles and must be named:

LH 3000.init

targetPos.x=1000
targetPos.y=500
targetPos.h=200
distancePerBeat=160
altitude=350
risePerBeat=25
riseDownPerBeat=15
typ=4
seats=290

LH 500.init

targetPos.x=1000
targetPos.y=500
targetPos.h=200
distancePerBeat=200
altitude=300
risePerBeat=20
riseDownPerBeat=10
typ=3
seats=250

 


Answers (2)