Laden...
R
R3turnz myCSharp.de - Member
Süddeutschland Dabei seit 03.01.2016 125 Beiträge
Benutzerbeschreibung

Forenbeiträge von R3turnz Ingesamt 125 Beiträge

13.02.2016 - 20:43 Uhr

Hallo,
ich habe jetzt schon verschiedene Artikel etc. zu diesem Thema gelesen, und werde einfach nicht schlau daraus.
Ich verstehe den Enumerator als "Positionszeiger", der auf ein Element in einer Liste verweist..
Viel mehr jedoch nicht: Wieso exestieren 2 Interfaces : IEnmerable und IEnumirator. Während das eine einfach nur ein Objekt, des Typen eines anderen zurückgibt. Auf z.B. msdn ist die IEnumirator Klasse eine Klasse, die für nichts anderes verwendet wird (Ihr wird einfach das anzuzeigende Array übergeben).Wieso wird aber nicht eigentlich hier auf dieses Objekt verzichtet, und einfach Move Next in die IEnumerable Schnittstelle implemtiert. Einfacher formuliert: Wieso wird ein eigenes IEnumerator Objekt/Klasse bereitgestellt?
Ein anderes Thema ist yield return, das z.B. folgendes Beispiel genannt wird:



  public IEnumerator GetEnumerator() {
    for (int i = 0; i < month.Length; i++)
      yield return month[i];
  }

(von:http://openbook.rheinwerk-verlag.de/visual_csharp_2012/1997_08_006.html#dodtpda373e73-c243-4c75-a259-4ca31dca09a3)

yield muss hier doch eine Art IEnumirator dastellen, da dies ja der Rückgabe Typ ist, wieso werden dann aber nacheinander alle Elemente yield zu übergeben, und nicht die ganze List auf einmal, und yield würde dann dann die Klasse generieren. Vieleicht verwirrt das hier, meine zweite Frage ist einfach formuliert: Wie funktioniert yield?

LG

03.02.2016 - 13:26 Uhr

Hallo,
weder in dem Buch was ich gerade verfolge, noch in der Dokumentation werde ich ganz schlüssig: Ich habe verstanden das ein dynamisches Objekt zur Kompilierzeit noch alle Formen annehemen kann.
Was hier msdn meint verstehe ich nicht:

"Die Rolle des Compilers in diesen Beispielen besteht darin, Informationen zu den Vorgängen zusammenzufassen, die die einzelnen Anweisungen für das Objekt oder den Ausdruck vom Typ dynamic vorsehen.Zur Laufzeit werden die gespeicherten Informationen geprüft, und nicht gültige Anweisungen lösen eine Laufzeitausnahme aus." (msdn)

Auch wofür ich das eigentlich brauche verstehe ich nicht ganz, es wird die Verwendung mit anderen "dynamischen" Sprachen als Beispiel genannt. Bedeutet dynamisch das sich z.B. eine Klasse noch während der Laufzeit in einer solchen noch ändern kann?

LG

30.01.2016 - 19:28 Uhr

Hallo,
ich habe versucht alle vorgeschalgenen Punkte umzusetzen, eine Speicher-Funktion wird folgen, konnte man vieleicht an den leeren Save and Load Methoden sehen 😃 (Wenn ich XML beherrsche werde ich diese Funktion einbauen).
Aktuell besteht das Problem das wenn ich ein Medium erstellen möchte eine StackOverflow Exception geworfen wird. (Im Gleichheits Operator). Ich kann gerade wirklich nicht verstehen wieso hier eine Endlos-Schleife sein sollte.
Außerdem wollte ich in der Attributes Eigenschaft nur das Attribut hinzufügen wenn es dem aktuellen Typ entspricht. (Also keine Lieder einem Film hinzufügen etc.)
Dies kann ich aber nicht, da value ja eine Liste ist. Wie löst man soetwas?
Die Fragen zur Implemtierung von Equals bzw. IEquatable in den Attributen habe ich ja schon in dem anderen Post gestellt.

Also hier das Projekt:
Program.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CD_DVD_Libary
{
    class Program
    {
        static void Main(string[] args)
        {
            var appDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DVDCDLibary");
            var client = new CDDVDLibaryClient();
            client.Proccess(appDir);
        }
    }
}


CDDVDLibaryClient.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CD_DVD_Libary
{
    class CDDVDLibaryClient
    {
        private CDDVDLibary _libary;
        Validator _validator = new Validator();
        public void Proccess(string applicationDirectory)
        {
            Console.WriteLine("CDDVDLibary V.0.6\nIdea from Mycsharp.de\nhttp://www.mycsharp.de/wbb2/thread.php?threadid=43577");
            _libary = new CDDVDLibary(applicationDirectory);
            if (Directory.Exists(applicationDirectory))
            {
                Console.WriteLine("Loaded Program Directory.");
            }
            else
            {
                Console.Write("Creating Program Directory...");
                Directory.CreateDirectory(applicationDirectory);
                Console.WriteLine("Done...");
            }
            bool stop = false;
            do
            {
               
                Console.WriteLine("Main Menu:Add/Remove/Print/Modify/Queries/Exit");
                string cmd = Console.ReadLine();
                if (cmd.ToUpper() == "ADD")
                {
                    Add();
                }
                else if (cmd.ToUpper() == "REMOVE")
                {
                    Remove();
                }
                else if (cmd.ToUpper() == "EXIT")
                {
                    stop = true;
                }
                else if (cmd.ToUpper() == "PRINT")
                {
                    Print();
                }
                else if (cmd.ToUpper() == "MODIFY") 
                {
                    Modify();
                }
                else if(cmd.ToUpper() == "QUERIES")
                {
                    Queries();
                }
                    
                else
                {
                    Console.WriteLine("Try again...");
                }
                Console.WriteLine("Press any key to continue.");
                Console.ReadKey();
                Console.Clear();
            } while (!stop);
            Console.WriteLine("\nSaving...");
            _libary.Save();
            Console.ReadKey();
        }
        private void Add()
        {
            Medium medium;
            Console.Write("What shoud be added?\n0.DVD\n1.CD\nChoose:");
            string input = Console.ReadLine();
            if (input == "0")
            {
                medium = InputMedium(MediumType.DVD);
            }
            else if (input == "1")
            {
                medium = InputMedium(MediumType.CD);
            }
            else
            {
                Console.WriteLine("Can not validate your input.");
                medium = null;
            }

            if (medium != null)
            {
                Console.WriteLine("Added.");
                _libary.Mediums.Add(medium);

            }
                
        }
        private void Remove()
        {
            Medium toRemove = GetMedium();
            if (toRemove != null)
                {
                _libary.Mediums.Remove(toRemove);
                Console.WriteLine("Removed.");
            }
            }
        private void Modify()
        {
            Medium medium = GetMedium();
            if (medium != null)
            {
                int indexOfMedium = _libary.Mediums.IndexOf(medium);
                Console.WriteLine("Choosen Medium:");
                _libary.PrintMedium(medium);
                if (medium.MediumType == MediumType.DVD)
                {
                  
                    Console.Write("Options:\n0.Modify Medium\n1.Add Actor\n2.Remove Actor\nChoose:");
                    string input = Console.ReadLine();
                    if (input == "0")
                    {
                        medium = InputMedium(MediumType.DVD);
                    }
                    else if (input == "1")
                    {
                        Actor temp = InputActor();
                        if (temp != null)
                        medium.Attributes.Add(temp);

                    }
                    else if (input == "2")
                    {
                        IAttribute temp = GetAttribut(medium);
                        if (medium.Attributes.Contains(temp))
                        medium.Attributes.Remove(temp);
                    }
                }
                else if(medium.MediumType == MediumType.CD)
                {
                    Console.Write("Options:\n0.Modify Medium\n1.Add Track\n2.Remove Track\nChoose:");
                    string input = Console.ReadLine();
                    if (input == "0")
                    {
                        medium = InputMedium(MediumType.CD);
                    }
                    else if (input == "1")
                    {
                        Track track = InputTrack();
                        if(track != null)
                        medium.Attributes.Add(track);
                    }
                    else if (input == "2")
                    {
                        IAttribute temp = GetAttribut(medium);
                        if (medium.Attributes.Contains(temp))
                            medium.Attributes.Remove(temp);
                    }
                }
                if (medium != null)
                {
                    _libary.Mediums[indexOfMedium] = medium;
                    Console.WriteLine("Modified.");
                }
            }
            }
        private void Print()
        {
            Console.Write("Printing Options:\n0.Print mediums\n1.Print all\n2.Print single medium\nChoose:");
            string input = Console.ReadLine();
            if (input == "0")
                _libary.PrintMediums();

            else if (input == "1")
                _libary.PrintAll();
            else if (input == "2")
            {
                Medium toPrint = GetMedium();
                if(toPrint != null)
                _libary.PrintMedium(toPrint);
            }
            else
                Console.WriteLine("Try again.");
                    }

        private void Queries()
        {
            Console.Write("Queries:\n0.Compare for identical Mediums\nChoose:");
            string input = Console.ReadLine();
            if (input == "0")
            {
                CompareMediums();
            }
            }
        private void CompareMediums()
        {
        }
    
        private Medium InputMedium(MediumType mediumType)
        {
            Medium output = null;
            
            try
            {
                Console.Write("Name:");
                string name = Console.ReadLine();
                Console.Write("Length:");
               int length = int.Parse(Console.ReadLine());
                Console.Write("Release Year:");
               int releaseYear = int.Parse(Console.ReadLine());
                Console.Write("Release Month:");
                int releaseMonth = int.Parse(Console.ReadLine());
                
                output = new Medium(name, length,new DateTime(releaseYear,releaseMonth,1),mediumType);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return output;
        }
private Actor InputActor()
        {
            Actor output = null;
            try
            {
                string name;
                int age;
                Console.Write("Name:");
                name = Console.ReadLine();
                Console.Write("Age:");
                age = int.Parse(Console.ReadLine());
                output = new Actor(name, age);
            }
        catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return output;
        }
        private Track InputTrack()
        {
            Track output = null;
            try
            {
                string name;
                string artist;
                decimal length;
                Console.Write("Name:");
                name = Console.ReadLine();
                Console.Write("Artist:");
                artist = Console.ReadLine();
                Console.Write("Length (Decimal):");
                length = decimal.Parse(Console.ReadLine());
                output = new Track(name, length, artist);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return output;
        }
        public Medium GetMedium()
        {
            _libary.PrintMediums();
            Medium output;
            Console.Write("Choose:");
            string input = Console.ReadLine();
            
            if(_validator.ValidateIndex(input, _libary.Mediums.Count))
            {
                int validatedinput = int.Parse(input);
                output = _libary.Mediums[validatedinput];
            }
            else
            {
                output = null;
                Console.WriteLine("An validation error occured.");
            }
            return output;
        }
        public IAttribute GetAttribut(Medium parent)
        {
            
            IAttribute output = null;
           
                if (parent != null && parent.Attributes.Any())
                {
                    _libary.PrintMedium(parent);
                    Console.Write("Choose:");
                    string index = Console.ReadLine();
                    if (_validator.ValidateIndex(index, parent.Attributes.Count))
                    {
                        int validatedindex = int.Parse(index);
                        output = parent[validatedindex];
                    }
                    else
                    {
                        Console.WriteLine("An validation error occured");
                    }
                }
                else
                {
                    Console.WriteLine("The Medium has no Attributs.");
                }

            
            return output;
        }
    }
}


CDDVDLibary.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    class CDDVDLibary
    {
        private string _applicationDirectory;

        public string ApplicationDirectory
        {
            get { return _applicationDirectory; }
            set { _applicationDirectory = value; }
        }
        public List<Medium> Mediums = new List<Medium>();

        public Medium this[int index]
        {
            get
            {
                return Mediums[index];
            }
            set
            {
                Mediums[index] = value;
            }
        }
        public CDDVDLibary(string applicationdirectory)
        {
            this.ApplicationDirectory = applicationdirectory;
        }
        public void PrintMediums()
        {
            for(int i = 0; i < Mediums.Count;i++)
            {
                Console.WriteLine(i+"."+Mediums[i].Name);
            }
        }
        public void PrintAll()
        {
                for (int i = 0; i < Mediums.Count; i++)
                {
                    Console.WriteLine(Mediums[i].ToString());
                    
                        for (int a = 0; a < Mediums[i].Attributes.Count; a++)
                        {
                            Console.WriteLine(Mediums[i].Attributes[a].ToString());
                            Console.WriteLine();
                        }
            }
            }
        public void PrintMedium(Medium medium)
        {
            Console.WriteLine(medium.ToString());
            
                for (int a = 0; a < medium.Attributes.Count; a++)
                {
                    Console.WriteLine(medium.Attributes[a].ToString());
                }
            
        }
        public void Save()
        {

        }
        public void Load()
        {

        }

    }
}


Medium.cs:


using System;   
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    public enum MediumType {DVD, CD}
      
    sealed class Medium : IEquatable<Medium>
    {
        public static bool operator ==(Medium medium1,Medium medium2)
        {
            if (medium1 == null|| medium2 == null)
            {
                return Object.Equals(medium1, medium2);
            }           
            return medium1.Equals(medium2) ? true : false;
        }
        public static bool operator !=(Medium medium1,Medium medium2)
        {
            return !(medium1.Equals(medium2));
        }
        public bool Equals(Medium medium)
        {
            if (medium == null) return false;
            if (this.Name != medium.Name)
                return false;
            if (this.Length != medium.Length)
                return false;
            if (this.ReleaseTime != medium.ReleaseTime)
                return false;
            return new HashSet<IAttribute>(Attributes).SetEquals(medium.Attributes);

        }
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            Medium medium = obj as Medium;
            if (medium == null) return false;
            else return Equals(medium);
        }
        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }
        
        public IAttribute this[int index]
        {
            get
            {
                return Attributes[index];
            }
                set
            {
                Attributes[index] = value;
            }
        }
       
        public Medium(string name,int length,DateTime releaseTime,MediumType mediumtype)
        {
            this.Name = name;
            this.Length = length;
            this.ReleaseTime = releaseTime;
            this._mediumType = mediumtype;
        }

        private MediumType _mediumType;

        public MediumType MediumType
        {
            get { return _mediumType; }
        }
      
        public List<IAttribute> Attributes { get; set; }
      
        
        
        private string _name;

        public string Name
        {
            get { return _name; }
            set { if(value != null && value != "")
                {
                    _name = value;
                }
            else
                {
                    throw new Exception("A Medium must have a name!");
                }
            }
        }

        private int _length;

        public int Length
        {
            get { return _length; }
            set {
                if (value < 0)
                    throw new Exception("The length of the film must be over 0!");
                else
                    _length = value;
            }
        }

        private DateTime _releaseTime;

        public DateTime ReleaseTime
        {
            get { return _releaseTime; }
            set
            {
                if (DateTime.Compare(value,DateTime.Now) <= 0)
                {
                    _releaseTime = value;
                }
else
                {
                    throw new Exception("The release time can not be in the future!");
                }
            }
        }

  
        
    }
}


IAttribute.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    interface IAttribute
    {
        string Name { get; set; }


    }
}


Track.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    public class Track : IAttribute,IEquatable<Track>
    {
        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }
        public static bool operator ==(Track track1,Track track2)
        {
            if (track1 == null || track2 == null)
                return Object.Equals(track1, track2);
            return track1.Equals(track2);
        }
        public static bool operator !=(Track track1,Track track2)
        {
            return  track1 == track2 ? false : true ;
        }
            public override bool Equals(object obj)
        {
            if (obj == null) return false;
            IAttribute attribut = obj as IAttribute;
            if (attribut == null) return false;
            return Equals(attribut);
        }
        public bool Equals(Track other)
        {
            if (other == null) return false;
            if (other.Name != this.Name) return false;
            if (other.Artist != this.Artist) return false;
            if (other.Length != this.Length) return false;
            return true;

        }
        private string _name;

        public string Name
        {
            get { return _name; }
            set
            {
                if (value != null && value != "")
                    _name = value;
                else
                    throw new Exception("An track needs a name!");
            }
        }

        private decimal _length;

        public decimal Length
        {
            get { return _length; }
            set
            {
                if (value > 0)
                    _length = value;
                else
                    throw new Exception("The length can not be under 0 minutes.");

            }
        }
        private string _artist;

        public string Artist
        {
            get { return _artist; }
            set
            {
                if (value != null && value != "")
                    _artist = value;
                else
                    throw new Exception("A artist needs a name!");
            }
        }

        public Track(string name,decimal length,string artist)
        {
            this.Name = name;
            this.Length = length;
            this.Artist = artist;

        }
        public override string ToString()
        {
            return string.Format("Track Name={0} Artist={1} Length={2}",Name,Artist,Length);
        }
    }
}


Actor.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
   public class Actor : IAttribute,IEquatable<Actor>
    {
        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            Actor actor1 = obj as Actor;
            if (actor1 == null) return false;
            return Equals(actor1);
           
        }
        public static bool operator ==(Actor actor1,Actor actor2)
        {
            if (actor1 == null || actor2 == null) return Object.Equals(actor1, actor2);
            return actor1.Equals(actor2);
        }
        public static bool operator !=(Actor actor1,Actor actor2)
        {
            return actor1 == actor2 ? false : true;
        }
        public bool Equals(Actor other)
        {
            if (other == null) return false;
            if (this.Name != other.Name) return false;
            if (this.Age != other.Age) return false;
            return true;
        }
        private string _name;

        public string Name
        {
            get { return _name; }
            set
            {
                if (value != null && value != "")
                    _name = value;
                else
                    throw new Exception("An actor needs an name!");
            }
        }
        private int _age;

        public int Age
        {
            get { return _age; }
            set
            {
                if (value < 0)
                    throw new Exception("A actor can't be jounger than 0!");
                else if (value > 100)
                    throw new Exception("The actor isn't older than 100, is he?");
                else
                    _age = value;
            }
        }

        public Actor(string name,int age)
            {
            this.Name = name;
            this.Age = age;
        }
    
    public override string ToString()
        {
            return string.Format("Actor Name={0} Age={1}",Name,Age);
        }



    }
}


Validator.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    class Validator
    {
        public bool ValidateIndex(string value,int arrayLength)
        {
            int output = 0;
            if (!int.TryParse(value,out output) )
            {
                return false;
            }

            if(output < arrayLength && output > 0)
            {
                return true;
            }
            return false;
        }

    }
}


LG

28.01.2016 - 19:14 Uhr

Hallo,
ich habe mich wieder drangestzt und die Änderungen so gut ich konnte umgesetzt:
Medium.cs:


    abstract class Medium : IEquatable<Medium>
    {
        public static bool operator ==(Medium medium1,Medium medium2)
        {
if(medium1 == null|| medium2 == null)
            {
                return Object.Equals(medium1, medium2);
            }           
            return medium1.Equals(medium2) ? true : false;
        }
        public static bool operator !=(Medium medium1,Medium medium2)
        {
            return !(medium1 == medium2);
        }
        public bool Equals(Medium medium)
        {
            if (medium == null) return false;
            if (this.Name != medium.Name)
                return false;
            if (this.Length != medium.Length)
                return false;
            if (this.ReleaseTime != medium.ReleaseTime)
                return false;
            return new HashSet<IAttribut>(Attributs).SetEquals(medium.Attributs);

        }
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            Medium medium = obj as Medium;
            if (medium == null) return false;
            else return Equals(medium);
        }
        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }
        
        public  IAttribut this[int index]
        {
            get
            {
                return Attributs[index];
            }
                set
            {
                Attributs[index] = value;
            }
        }
        private List<IAttribut> _attributs = new List<IAttribut>();
        public List<IAttribut> Attributs
        {
            get
            {
                return _attributs;
            }
            set
            {
                _attributs = value;
            }
        }
        public Medium(string name,int length,DateTime releaseTime)
        {
            this.Name = name;
            this.Length = length;
            this.ReleaseTime = releaseTime;

        }

        private string _name;

        public string Name
        {
            get { return _name; }
            set { if(value != null && value != "")
                {
                    _name = value;
                }
            else
                {
                    throw new Exception("A Medium must have a name!");
                }
            }
        }

        private int _length;

        public int Length
        {
            get { return _length; }
            set {
                if (value < 0)
                    throw new Exception("The length of the film must be over 0!");
                else
                    _length = value;
            }
        }

        private DateTime _releaseTime;

        public DateTime ReleaseTime
        {
            get { return _releaseTime; }
            set
            {
                if (DateTime.Compare(value,DateTime.Now) <= 0)
                {
                    _releaseTime = value;
                }
else
                {
                    throw new Exception("The release time can not be in the future!");
                }
            }
        }

  
        
    }

Track.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    public class Track : IAttribut,IEquatable<Track>
    {
        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }
        public static bool operator ==(Track track1,Track track2)
        {
            if (track1 == null || track2 == null)
                return Object.Equals(track1, track2);
            return track1.Equals(track2);
        }
        public static bool operator !=(Track track1,Track track2)
        {
            return  track1 == track2 ? false : true ;
        }
            public override bool Equals(object obj)
        {
            if (obj == null) return false;
            IAttribut attribut = obj as IAttribut;
            if (attribut == null) return false;
            return Equals(attribut);
        }
        public bool Equals(Track other)
        {
            if (other == null) return false;
            if (other.Name != this.Name) return false;
            if (other.Artist != this.Artist) return false;
            if (other.Length != this.Length) return false;
            return true;

        }
        private string _name;

        public string Name
        {
            get { return _name; }
            set
            {
                if (value != null && value != "")
                    _name = value;
                else
                    throw new Exception("An track needs a name!");
            }
        }

        private decimal _length;

        public decimal Length
        {
            get { return _length; }
            set
            {
                if (value > 0)
                    _length = value;
                else
                    throw new Exception("The length can not be under 0 minutes.");

            }
        }
        private string _artist;

        public string Artist
        {
            get { return _artist; }
            set
            {
                if (value != null && value != "")
                    _artist = value;
                else
                    throw new Exception("A artist needs a name!");
            }
        }

        public Track(string name,decimal length,string artist)
        {
            this.Name = name;
            this.Length = length;
            this.Artist = artist;

        }
        public override string ToString()
        {
            return string.Format("Track Name={0} Artist={1} Length={2}",Name,Artist,Length);
        }
    }
}


Actor.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
   public class Actor : IAttribut,IEquatable<Actor>
    {
        public override int GetHashCode()
        {
            return Name.GetHashCode();
        }
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            Actor actor1 = obj as Actor;
            if (actor1 == null) return false;
            return Equals(actor1);
           
        }
        public static bool operator ==(Actor actor1,Actor actor2)
        {
            if (actor1 == null || actor2 == null) return Object.Equals(actor1, actor2);
            return actor1.Equals(actor2);
        }
        public static bool operator !=(Actor actor1,Actor actor2)
        {
            return actor1 == actor2 ? false : true;
        }
        public bool Equals(Actor other)
        {
            if (other == null) return false;
            if (this.Name != other.Name) return false;
            if (this.Age != other.Age) return false;
            return true;
        }
        private string _name;

        public string Name
        {
            get { return _name; }
            set
            {
                if (value != null && value != "")
                    _name = value;
                else
                    throw new Exception("An actor needs an name!");
            }
        }
        private int _age;

        public int Age
        {
            get { return _age; }
            set
            {
                if (value < 0)
                    throw new Exception("A actor can't be jounger than 0!");
                else if (value > 100)
                    throw new Exception("The actor isn't older than 100, is he?");
                else
                    _age = value;
            }
        }

        public Actor(string name,int age)
            {
            this.Name = name;
            this.Age = age;
        }
    
    public override string ToString()
        {
            return string.Format("Actor Name={0} Age={1}",Name,Age);
        }



    }
}


Ich habe aber noch zwei Fragen:
Equals von Object wird ausgeführt um zu überprüfen ob vieleicht beide Objekte null sind, und so vieleicht auch noch true zurück gegeben wird, oder?


if (actor1 == null || actor2 == null) return Object.Equals(actor1, actor2);

Ich habe jetzt im IAttribut nichts definiert, da sich Track und Actor so unterscheiden, das eine abstrakte Klasse keinen Sinn machen würde. Zuerst wollte ich die Schnittstelle IEquatable in der Schnittstelle implementieren, hier wurde aber ein Fehler angezeigt. Wie soll ich das am besten lösen?

LG

PS: Ich habe gerade gesehen das es noch einiges zu ändern gibt (Aus dem anderen Post), werde ich noch machen 😉

24.01.2016 - 18:09 Uhr

Hallo,
mein erster Post ist mir wirklich nicht gelungen...

Ich möchte ereichen das gleiche Medien, also auch wenn die Werte (z.B. Name) gleich sind true zurück gegeben wird. Der nächste Schritt wäre dann: Wie verwende ich eine Schleife die eine Liste untereinander auf Gleichheit überprüft?

LG

24.01.2016 - 14:06 Uhr

Hallo,
ich meinte diese Stelle:


if(((Object)medium1) == null||((Object)medium2) == null)

Ich kann durch das Parameter ja schon sicher gehen das es ein Medium ist und muss erst gar nicht casten. Wieso wird hier nicht direkt auf null überprüft...


public static bool operator ==(Medium medium1,Medium medium2)

Okay nun versuche ich meine Schelifen Idee zu erklären:
Ich habe eine Liste von Medien, wenn ich jetzt einfach eines durch eine Schleife auswähle überprüfe und das überprüfte Medium in der Liste belasse würde die gleiche Untersuchung mehrmals durchgeführt werden:
Beispiel:
Mediums enthält:
1.CD 1
2.DVD 1
1.Durchlauf:
Wählt CD 1 aus, überprüft gegen DVD, nicht identisch,weiter
2 Durchlauf:
Wählt DVD 1 aus, überprüft gegen CD, nicht identisch, fertig

Hier wird 2 mal genau das selbe überprüft,das habe ich versucht habe zu umgehen, dies ist mir wahrscheinlich aber nicht gelungen, wenn du nicht erkennst was ich versucht habe.

LG

24.01.2016 - 08:42 Uhr

Hallo,
ich habe versucht die Implemtierung von der Dokumentation möglichst gut zu übernehmen.


  public static bool operator ==(Medium medium1,Medium medium2)
        {
if(((Object)medium1) == null||((Object)medium2) == null)
            {
                return Object.Equals(medium1, medium2);
            }           
            return medium1.Equals(medium2) ? true : false;
        }
        public static bool operator !=(Medium medium1,Medium medium2)
        {
            return !(medium1 == medium2);
        }
        public bool Equals(Medium medium)
        {
            if (medium == null) return false;
            if (this.Name == medium.Name && this.ReleaseTime == medium.ReleaseTime && this.Attributs == medium.Attributs) return true;
            return false;
        }
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            Medium medium = obj as Medium;
            if (medium == null) return false;
            else return Equals(medium);
        }

Ich habe aber dazu noch ein paar Fragen: Wieso wird zuerst in ein Objekt konvertiert und erst dann auf null geprüft, und nicht einfach direkt auf null geprüft. (Was erst in Equals getan wird.) Bei der allgemeinen Überschreibung wird in ein Medium konvertiert, aber dann könnte ich ja direkt ein Medium der Überladung übergeben.

Jetzt komme ich auch mit einer konkreten Fehlermeldung in der Schleife:


 checkedMediums.Add(temp[0]);
                temp.RemoveAt(0);
   for (int i = 0;i <= temp.Count - 1;i++)
                {
                    for (int a = 0; a <= checkedMediums.Count - 1; a++)
                    {


                        if (temp[i] == checkedMediums[a])
                        {
                            checkedMediums.Add(temp[0]);
                            output.Add(temp[0]);

                        }
                        else
                        {
                            checkedMediums.Add(temp[0]);

                        }
                        temp.RemoveAt(0);
                    }
                }

Wenn ich nur auf größer als am Anfang überprüfe wird die Schleife bei 2 Elementen gar nicht ausgeführt, wenn ich auch auf Gleichheit überprüfe wird aber eine out-of-range Exception geworfen.

LG

23.01.2016 - 19:48 Uhr

Hallo,
mir ist bewusst das dabei nur true zurück gegeben wird, wenn das genau gleiche Objekt übergeben wird, deswegen verwende ich ja auch Equals um mich auf die Werte zu überprüfen:


return medium1.Equals(medium2) ? true : false;


        public bool Equals(Medium medium)
        {
            if (obj == null) return false;
            if (this.Name == ((Medium)obj).Name && this.ReleaseTime == ((Medium)obj).ReleaseTime && this.Attributs == ((Medium)obj).Attributs) return true;
            return false;
        }

Habe ich dich vieleicht nicht richtig verstanden?

LG

23.01.2016 - 17:14 Uhr

Hallo,
der Post ist mir nicht besonders gelungen, also hier nochmal ein Versuch.
Es geht um die Überprüfung auf Gleichheit.
Obwohl die Objekte gleich sind (Siehe Anhang) wird nicht true bei der Überprüfung zurückgegeben. Da ich aber nur einen Operator verwende kann ich den Code auch nicht direkt ansehen, sondern es wird direkt zu else gesprungen. Also muss der Fehler im Operator liegen...

LG

22.01.2016 - 16:20 Uhr

Hallo,
ich habe ein Gleichheits-Überprüfung in meine CD-DVD Bibliothek eingebaut. Diese funktioniert aber nicht richtig, obwohl die Medien identisch sind.
Compare Mediums:


  var output = new List<Medium>();
            var checkedMediums = new List<Medium>();
            var temp = _libary.Mediums;
            if (_libary.Mediums.Any())
            {
                checkedMediums.Add(temp[0]);
                temp.RemoveAt(0);
                for (int i = 0;i <= temp.Count - 1;i++)
                {
                    foreach(Medium medium in checkedMediums)
                    {
                        if(temp[i] == medium)
                        {
                            checkedMediums.Add(temp[0]);
                            output.Add(temp[0]);
                           
                        }
                        else
                        {
                            checkedMediums.Add(temp[0]);
                           
                        }
                        temp.RemoveAt(0);
                    }
                }
            }
            else
            {
                Console.WriteLine("Found no mediums!");
            }
            return output.ToArray();

Medium Klasse:


abstract class Medium
    {
        public static bool operator ==(Medium medium1,Medium medium2)
        {
            if (ReferenceEquals(medium1, medium2)) return true;
            if (ReferenceEquals(medium1, null)) return false;
            return medium1.Equals(medium2) ? true : false;
        }
        public static bool operator !=(Medium medium1,Medium medium2)
        {
            return !(medium1 == medium2);
        }
        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            if (this.Name == ((Medium)obj).Name && this.ReleaseTime == ((Medium)obj).ReleaseTime && this.Attributs == ((Medium)obj).Attributs) return true;
            return false;
        }
        public  IAttribut this[int index]
        {
            get
            {
                return Attributs[index];
            }
                set
            {
                Attributs[index] = value;
            }
        }
        private List<IAttribut> _attributs = new List<IAttribut>();
        public List<IAttribut> Attributs
        {
            get
            {
                return _attributs;
            }
            set
            {
                _attributs = value;
            }
        }
        public Medium(string name,int length,DateTime releaseTime)
        {
            this.Name = name;
            this.Length = length;
            this.ReleaseTime = releaseTime;

        }

        private string _name;

        public string Name
        {
            get { return _name; }
            set { if(value != null && value != "")
                {
                    _name = value;
                }
            else
                {
                    throw new Exception("A Medium must have a name!");
                }
            }
        }

        private int _length;

        public int Length
        {
            get { return _length; }
            set {
                if (value < 0)
                    throw new Exception("The length of the film must be over 0!");
                else
                    _length = value;
            }
        }

        private DateTime _releaseTime;

        public DateTime ReleaseTime
        {
            get { return _releaseTime; }
            set
            {
                if (DateTime.Compare(value,DateTime.Now) <= 0)
                {
                    _releaseTime = value;
                }
else
                {
                    throw new Exception("The release time can not be in the future!");
                }
            }
        }

  
        
    }

Wo liegt mein Fehler?

LG

16.01.2016 - 20:26 Uhr

Hallo,
ich habe einiges über die IDisposable Schnittstelle gelesen, und habe nun das folgende Gerüst:


bool disposed = false;

protected virtual void Dispose(bool disposing)
{
if(!disposed)
{
if(disposing)
[
//Auch "verwaltete" Objekt disposen//
GC.SupressFinalize();
}
else
{
//Nur fremde Resourcen disposen//
}
disposed = true;
}
else
throw new ObjectDisposedException();
}
public void Dispose()
{
Dispose(true);
}
~MyClass()
{
Dispose(false);
}

Erstmal, ist das so richtig?
Als nächstes nun zur eigentlichen Frage:
Ab wann soll ich IDisposable implementieren?Klar, bei verwalteten Fremdresourcen, aber für verwaltete Objekte nur wenn diese auch Dispose implementieren oder auch bei einfachen null Zuweisungen?
Bisher habe ich noch nie Dispose implemtiert und es hat nie Probleme gegeben, deswegen denke ich eher an ersteres,richtig? (Jedoch auch wenn z.B. ein Stream Writer verwaltet wurde!)

LG

PS: Ich habe den FAQ Thread gelesen, und mir wird nicht klar:brauche ich die disposed Variable jetzt oder nicht. Es gab keine eindeutige Meinung.

09.01.2016 - 11:56 Uhr

Hallo,
diesesmal mit dem 2ten Anlauf, und auch im richtigen Forum.
Diese Version funktioniert komplet.
Ich möchte diese aber nochmal hier posten bevor ich mich an Detrails mache: Linq,Und solche Geschichten wie : ReleaseYear in ReleaseDate umbennenen und das dann als Time und nicht als int..,Save(),Load()

Program.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CD_DVD_Libary
{
    class Program
    {
        static void Main(string[] args)
        {
            var appDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DVDCDLibary");
            var client = new CDDVDLibaryClient();
            client.Proccess(appDir);
        }
    }
}


CDDVDLibaryClient.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CD_DVD_Libary
{
    class CDDVDLibaryClient
    {
        private CDDVDLibary libary;
        Validator validator = new Validator();
        public void Proccess(string applicationDirectory)
        {
            Console.WriteLine("CDDVDLibary V.0.6\nIdea from Mycsharp.de\nhttp://www.mycsharp.de/wbb2/thread.php?threadid=43577");
            libary = new CDDVDLibary(applicationDirectory);
            if (Directory.Exists(applicationDirectory))
            {
                Console.WriteLine("Loaded Program Directory.");
            }
            else
            {
                Console.Write("Creating Program Directory...");
                Directory.CreateDirectory(applicationDirectory);
                Console.WriteLine("Done...");
            }
            bool stop = false;
            do
            {
               
                Console.WriteLine("Main Menu:Add/Remove/Print/Modify/Exit");
                string cmd = Console.ReadLine();
                if (cmd.ToUpper() == "ADD")
                {
                    Add();
                }
                else if (cmd.ToUpper() == "REMOVE")
                {
                    Remove();
                }
                else if (cmd.ToUpper() == "EXIT")
                {
                    stop = true;
                }
                else if (cmd.ToUpper() == "PRINT")
                {
                    Print();
                }
                else if (cmd.ToUpper() == "MODIFY") 
                {
                    Modify();
                }
                else
                {
                    Console.WriteLine("Try again...");
                }
                Console.WriteLine("Press any key to continue.");
                Console.ReadKey();
                Console.Clear();
            } while (!stop);
            Console.WriteLine("\nSaving...");
            libary.Save();
            Console.ReadKey();
        }
        private void Add()
        {
            IMedium medium;
            Console.Write("What shoud be added?\n0.DVD\n1.CD\nChoose:");
            string input = Console.ReadLine();
            if (input == "0")
            {
                medium = InputDVD();
            }
            else if (input == "1")
            {
                medium = InputCD();
            }
            else
            {
                Console.WriteLine("Can not validate your input.");
                medium = null;
            }
            libary.Mediums.Add(medium);
            Console.WriteLine("Added.");
        }
        private void Remove()
        {
            IMedium toRemove = GetMedium();
            if (toRemove != null)
                {
                libary.Mediums.Remove(toRemove);
                Console.WriteLine("Removed.");
            }
            }
        private void Modify()
        {
            IMedium medium = GetMedium();
            if (medium != null)
            {
                int indexOfMedium = libary.Mediums.IndexOf(medium);
                Console.WriteLine("Choosen Medium:");
                libary.PrintMedium(medium);
                if (medium is DVD)
                {
                  
                    Console.Write("Options:\n0.Modify Medium\n1.Add Actor\n2.Remove Actor\nChoose:");
                    string input = Console.ReadLine();
                    if (input == "0")
                    {

                        medium = InputDVD();
                        libary.Mediums.Add(medium);
                    }
                    else if (input == "1")
                    {
                        medium.Attributs.Add(InputActor());
                    }
                    else if (input == "2")
                    {
                        medium.Attributs.Remove(GetAttribut());
                    }
                }
                else
                {
                    Console.Write("Options:\n0.Modify Medium\n1.Add Track\n2.Remove Track\nChoose:");
                    string input = Console.ReadLine();
                    if (input == "0")
                    {

                        medium = InputDVD();
                        libary.Mediums.Add(medium);
                    }
                    else if (input == "1")
                    {
                        medium.Attributs.Add(InputTrack());
                    }
                    else if (input == "2")
                    {
                        medium.Attributs.Remove(GetAttribut());
                    }
                }
                libary.Mediums[indexOfMedium] = medium;
            }
            }
        private void Print()
        {
            Console.Write("Printing Options:\n0.Print mediums\n1.Print all\nChoose:");
            string input = Console.ReadLine();
            if (input == "0")
                libary.PrintMediums();

            else if (input == "1")
                libary.PrintAll();
            else
                Console.WriteLine("Try again.");
                    }
        private CD InputCD()
        {
            CD output = null;
            string name;
            int length;
            int releaseYear;
            try
            {
                Console.Write("Name:");
                name = Console.ReadLine();
                Console.Write("Length:");
                length = int.Parse(Console.ReadLine());
                Console.Write("Release Year:");
                releaseYear = int.Parse(Console.ReadLine());
                output = new CD(name, length, releaseYear);
            }
            catch
            {
                Console.WriteLine("An Input Error occured.");
            }
            return output;
        }
        private DVD InputDVD()
        {
            DVD output = null;
            string name;
            int length;
            int releaseYear;
            try
            {
                Console.Write("Name:");
                name = Console.ReadLine();
                Console.Write("Length:");
                length = int.Parse(Console.ReadLine());
                Console.Write("Release Year:");
                releaseYear = int.Parse(Console.ReadLine());
                output = new DVD(name, length, releaseYear);
            }
            catch
            {
                Console.WriteLine("An Input Error occured.");
            }
            return output;
        }
private Actor InputActor()
        {
            Actor output = null;
            try
            {
                string name;
                int age;
                Console.Write("Name:");
                name = Console.ReadLine();
                Console.Write("Age:");
                age = int.Parse(Console.ReadLine());
                output = new Actor(name, age);
            }
        catch
            {
                Console.WriteLine("An Input Error occured");
            }
            return output;
        }
        private Track InputTrack()
        {
            Track output = null;
            try
            {
                string name;
                string artist;
                decimal length;
                Console.Write("Name:");
                name = Console.ReadLine();
                Console.Write("Artist:");
                artist = Console.ReadLine();
                Console.Write("Length (Decimal):");
                length = decimal.Parse(Console.ReadLine());
                output = new Track(name, length, artist);
            }
            catch
            {
                Console.WriteLine("An Input Error occured.");
            }
            return output;
        }
        public IMedium GetMedium()
        {
            libary.PrintMediums();
            IMedium output;
            Console.Write("Choose:");
            string input = Console.ReadLine();
            
            if(validator.ValidateIndex(input, libary.Mediums.Count - 1))
            {
                int validatedinput = int.Parse(input);
                output = libary.Mediums[validatedinput];
            }
            else
            {
                output = null;
                Console.WriteLine("An validation error occured.");
            }
            return output;
        }
        public IAttribut GetAttribut()
        {
            IMedium medium = GetMedium();
            IAttribut output = null;
            if (medium != null)
            {
               if(medium.Attributs.Any())
                {
                    libary.PrintMedium(medium);
                    Console.Write("Choose:");
                    string index = Console.ReadLine();
                    if(validator.ValidateIndex(index, medium.Attributs.Count - 1))
                    {
                        int validatedindex = int.Parse(index);
                        output = medium.Attributs[validatedindex];
                    }
                    else
                    {
                        Console.WriteLine("An validation error occured");
                    }
                }
               else
                {
                    Console.WriteLine("The Medium has no Attributs.");
                }

            }
            return output;
        }
    }
}


CDDVDLibary:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    class CDDVDLibary
    {
        private string _applicationDirectory;

        public string ApplicationDirectory
        {
            get { return _applicationDirectory; }
            set { _applicationDirectory = value; }
        }
        public List<IMedium> Mediums = new List<IMedium>();

        public CDDVDLibary(string applicationdirectory)
        {
            this.ApplicationDirectory = applicationdirectory;
        }
        public void PrintMediums()
        {
            for(int i = 0; i <= Mediums.Count - 1;i++)
            {
                Console.WriteLine(i+"."+Mediums[i].Name);
            }
        }
        public void PrintAll()
        {
            for (int i = 0; i <= Mediums.Count - 1; i++)
            {
                Console.WriteLine(Mediums[i].ToString());
                if(Mediums[i].Attributs.Any())
                    {
                    for (int a = 0; a <= Mediums[i].Attributs.Count - 1; a++)
                    {
                        Console.WriteLine(Mediums[i].Attributs[a].ToString());
                    }
                }
            }
        }
        public void PrintMedium(IMedium medium)
        {
            Console.WriteLine(medium.ToString());
            if (medium.Attributs.Any())
            {
                for (int a = 0; a <= medium.Attributs.Count; a++)
                {
                    medium.Attributs[a].ToString();
                }
            }
        }
        public void Save()
        {

        }
        public void Load()
        {

        }

    }
}


IMedium.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    interface IMedium
    {
        
        string Name { get; set; }
        int Length { get; set; }
        int ReleaseYear { get; set; }
        List<IAttribut> Attributs { get; set; }
    }
}


DVD.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    class DVD : IMedium
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private int _length;

        public int Length
        {
            get { return _length; }
            set { _length = value; }
        }

        private int _releaseYear;

        public int ReleaseYear
        {
            get { return _releaseYear; }
            set { _releaseYear = value; }
        }
        private List<IAttribut> _attributs = new List<IAttribut>();
        public List<IAttribut> Attributs
        {
            get { return _attributs; }
            set { _attributs = value; }
        }
        public DVD(string name,int length,int releaseYear)
        {
            this.Name = name;
            this.Length = length;
            this.ReleaseYear = releaseYear;
        }
        public override string ToString()
        {
            return string.Format("DVD Name={0} Length={1} ReleaseYear={2}",Name,Length,ReleaseYear);
        }

    }
}


CD.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    class CD : IMedium
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private int _length;

        public int Length
        {
            get { return _length; }
            set { _length = value; }
        }

        private int _releaseYear;

        public int ReleaseYear
        {
            get { return _releaseYear; }
            set { _releaseYear = value; }
        }

        private List<IAttribut> _attributs = new List<IAttribut>();
        public List<IAttribut> Attributs
        {
            get { return _attributs; }
            set { _attributs = value; }
        }

        public CD(string name,int length,int realeaseYear)
        {
            this.Name = name;
            this.Length = length;
            this.ReleaseYear = realeaseYear;
        }
        public override string ToString()
        {
            return string.Format("CD Name={0} Length={1} ReleaseYear={2}", Name, Length, ReleaseYear);
        }


    }
}

IAttribut.cs:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    interface IAttribut
    {
        string Name { get; set; }



    }
}

Track.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    public class Track : IAttribut
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private decimal _length;

        public decimal Length
        {
            get { return _length; }
            set { _length = value; }
        }
        private string _artist;

        public string Artist
        {
            get { return _artist; }
            set { _artist = value; }
        }

        public Track(string name,decimal length,string artist)
        {
            this.Name = name;
            this.Length = length;
            this.Artist = artist;

        }
        public override string ToString()
        {
            return string.Format("Track Name={0} Artist={1} Length={2}",Name,Artist,Length);
        }
    }
}


Actor.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
   public class Actor : IAttribut
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        public Actor(string name,int age)
            {
            this.Name = name;
            this.Age = age;
        }
    
    public override string ToString()
        {
            return string.Format("Actor Name={0} Age={1}",Name,Age);
        }



    }
}


Validator.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    class Validator
    {
        public bool ValidateIndex(string value,int arrayLength)
        {
            int output = 0;
            if (!int.TryParse(value,out output) )
            {
                return false;
            }

            if(output <= arrayLength && output >= 0)
            {
                return true;
            }
            return false;
        }

    }
}


Passt diesesmal meine OOP?
Wo kann ich etwas am Stil ändern oder eleganter lösen?

LG

08.01.2016 - 20:51 Uhr

Hallo,
ich habe mich jetzt an die Bibliothek gemacht, habe bisjetzt:
-Grundlegende Funktionen(Erstellen,Löschen,Anzeigen)
geplant sind:
-Linq Abfragen
-Schauspieler/Track's hinzufügen
Das bisherige Projekt:
Programm.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CD_DVD_Libary
{
    class Program
    {
        static void Main(string[] args)
        {
            var appDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DVDCDLibary");
            var client = new CDDVDLibaryClient();
            client.Proccess(appDir);
        }
    }
}


CDDVVDLibaryClient.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace CD_DVD_Libary
{
    class CDDVDLibaryClient
    {
        private CDDVDLibary libary;
        public void Proccess(string applicationDirectory)
        {
            Console.WriteLine("CDDVDLibary V.0.5");
            libary = new CDDVDLibary(applicationDirectory);
            if (Directory.Exists(applicationDirectory))
            {
                Console.WriteLine("Loaded Program Directory.");
            }
            else
            {
                Console.Write("Creating Program Directory...");
                Directory.CreateDirectory(applicationDirectory);
                Console.WriteLine("Done...");
            }
            bool stop = false;
            do
            {
               
                Console.WriteLine("Main Menu:Add/Remove/Exit");
                string cmd = Console.ReadLine();
                if(cmd.ToUpper() == "ADD")
                {
                    Add();
                }
                else if(cmd.ToUpper() == "REMOVE")
                {
                    Remove();
                }
                else if(cmd.ToUpper() ==  "Exit")
                {
                    stop = true;
                }
                else if(cmd.ToUpper() == "Print")
                {
                    libary.Print();
                }
                else
                {
                    Console.WriteLine("Try again...");
                }
                Console.Clear();
            } while (!stop);
            Console.WriteLine("\nSaving...");
            libary.Save();
            Console.ReadKey();
        }
        private void Add()
        {
            IMedium medium;
            Console.Write("What shoud be added?\n0.DVD\n1.CD\nChoose:");
            string input = Console.ReadLine();
            if (input == "0")
            {
                medium = InputDVD();
            }
            else if (input == "1")
            {
                medium = InputCD();
            }
            else
            {
                Console.WriteLine("Can not validate your input.");
                medium = null;
            }
            libary.Mediums.Add(medium);
            Console.WriteLine("Added.");
        }
        private void Remove()
        {
            IMedium toRemove = GetMedium();
            libary.Mediums.Remove(toRemove);
            Console.WriteLine("Removed.");
        }
        private CD InputCD()
        {
            CD output = null;
            string name;
            int length;
            int releaseYear;
            try
            {
                Console.Write("Name:");
                name = Console.ReadLine();
                Console.Write("Length:");
                length = int.Parse(Console.ReadLine());
                Console.WriteLine("Release Year:");
                releaseYear = int.Parse(Console.ReadLine());
                output = new CD(name, length, releaseYear);
            }
            catch
            {
                Console.WriteLine("An Input Error occured.");
            }
            return output;
        }
        private DVD InputDVD()
        {
            DVD output = null;
            string name;
            int length;
            int releaseYear;
            try
            {
                Console.Write("Name:");
                name = Console.ReadLine();
                Console.Write("Length:");
                length = int.Parse(Console.ReadLine());
                Console.Write("Release Year:");
                releaseYear = int.Parse(Console.ReadLine());
                output = new DVD(name, length, releaseYear);
            }
            catch
            {
                Console.WriteLine("An Input Error occured.");
            }
            return output;
        }
        public IMedium GetMedium()
        {
            libary.Print();
            IMedium output;
            Console.Write("Choose:");
            string input = Console.ReadLine();
            Validator validator = new Validator();
            if(validator.ValidateIndex(input, libary.Mediums.Count - 1))
            {
                int validatedinput = int.Parse(input);
                output = libary.Mediums[validatedinput];
            }
            else
            {
                output = null;
                Console.WriteLine("An Validation error occured.");
            }
            return output;
        }
    }
}


CDDVDLibary.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    class CDDVDLibary
    {
        private string _applicationDirectory;

        public string ApplicationDirectory
        {
            get { return _applicationDirectory; }
            set { _applicationDirectory = value; }
        }
        public  List<IMedium> Mediums;

        public CDDVDLibary(string applicationdirectory)
        {
            this.ApplicationDirectory = applicationdirectory;
        }
        public void Print()
        {
            for(int i = 0; i < Mediums.Count - 1;i++)
            {
                Console.WriteLine(i+"."+Mediums[i].Name);
            }
        }
        public void Save()
        {

        }
        public void Load()
        {

        }

    }
}


Validator.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    class Validator
    {
        public bool ValidateIndex(string value,int arrayLength)
        {
            int output = 0;
            if (!int.TryParse(value,out output) )
            {
                return false;
            }

            if(output <= arrayLength && output >= 0)
            {
                return true;
            }
            return false;
        }

    }
}


IMedium.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    interface IMedium
    {
        
        string Name { get; set; }
        int Length { get; set; }
        int ReleaseYear { get; set; }
        
    }
}


CD.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
   public class CD : IMedium
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private int _length;

        public int Length
        {
            get { return _length; }
            set { _length = value; }
        }

        private int _releaseYear;

        public int ReleaseYear
        {
            get { return _releaseYear; }
            set { _releaseYear = value; }
        }
        
        public List<Track> Tracks = new List<Track>();

        public CD(string name,int length,int realeaseYear)
        {
            this.Name = name;
            this.Length = length;
            this.ReleaseYear = realeaseYear;
        }


        
    }
}


DVD.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    class DVD : IMedium
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private int _length;

        public int Length
        {
            get { return _length; }
            set { _length = value; }
        }

        private int _releaseYear;

        public int ReleaseYear
        {
            get { return _releaseYear; }
            set { _releaseYear = value; }
        }
        public List<Actor> actors = new List<Actor>();

        public DVD(string name,int length,int releaseYear)
        {
            this.Name = name;
            this.Length = length;
            this.ReleaseYear = releaseYear;
        }


    }
}


IAttribut.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    interface IAttribut
    {
        string Name { get; set; }



    }
}


Actor.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
   public class Actor : IAttribut
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        public Actor(string name,int age)
            {
            this.Name = name;
            this.Age = age;
        }
    
    public override string ToString()
        {
            return "Actor Name=" + Name + "Age:" + Age;
        }



    }
}


Track.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CD_DVD_Libary
{
    public class Track : IAttribut
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        private decimal _length;

        public decimal Length
        {
            get { return _length; }
            set { _length = value; }
        }
        private string _artist;

        public string Artist
        {
            get { return _artist; }
            set { _artist = value; }
        }

        public Track(string name,decimal length,string artist)
        {
            this.Name = name;
            this.Length = length;
            this.Artist = artist;

        }
        public override string ToString()
        {
            return "Track Name=" + Name + " Artist=" + Artist + " Length=" + Length;
        }
    }
}


Ich habe folgende Fragen:
-Soll ich Save/Load/Print als ErweiterungsMethode in List<> implemtieren? Damit würde CDDVDLibary fast unnötig, sollte ich dieses dann löschen oder belassen.
-Eine Null Exception wird ausgelöst wenn ich eine DVD/CD der Liste hinzügen will, das Problem ist die Variable ist garnicht null, hat das etwas mit der generischen Liste zu tun?

LG

PS:Habe gerade gesehen, dass ich die .ToString Methode in DVD/CD vergessen habe.

08.01.2016 - 13:05 Uhr

Hallo,
ich möchte mich noch in OOP beschäftigen, und habe aus dem Projekt Thread Inperation geholt.
Ich möchte aber nicht drauflos programmieren, sondern ersteinmal ein Gerüst haben. Ich habe es mir so gedacht:

->CDDVDLibaryClient
-Proccess()

->CDDVDLibary
-List<IMedium> mediums
-Save
-Load
-Print
(Vieleicht Ausgaben nach Typen z.B. nur DVD's ausgeben. Dazu wäre Linq nützlich, muss ich mir erst noch beibringen)

->IMedium
-Name
-Länge
-Erscheinungsdatum
-Event Input Needed

->DVD : IMedium
-List<Schauspieler>
-Sprache
-Untertiel
-Hörausgabe

->CD : IMedium
-List<titel>Titel

->IAttribut
Name
InputNeeded Event

Die restlichen Klassen für die Attrribute..

Ist das Gerüst so okay?

LG

PS:Mir ist gerade aufgefallen, dass ich alles auf deutsch habe, werde später aus z.B. Schauspieler Actor machen.

07.01.2016 - 13:48 Uhr

Okay, ich habe alle Variaben angespasst und überall wo es möglich war ein var eingesetzt. Den Namen der Event Mezhode habe ich angepasst: PasswordLoader_InputNeeded. Was meinst du mit nicht richtig implementiert?
Ich habe einen delegaten mit EventHandler am Ende:


delegate void InputNeededEventHandler(object sender, EventArgs e);

Das Event:(In der Schnittstelle und in den Loader Klassen)


public event InputNeeded;

Und ich habe in der abbonierenden Klasse eine Methode die Methode mit Objekt_Ereignisname benannt 😉

Wo habe ich einen Fehler?

LG

06.01.2016 - 20:12 Uhr

Und die nächste Version 😉
Program.cs:


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    namespace Password_Checker_Rework_2
    {
        class Program
        {
            static void Main(string[] args)
            {
                var appDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),"passwordchecker");
                var passwordcheckerclient = new PasswordCheckClient();
                passwordcheckerclient.Proccess(appDir);
            }
        }
    }

PasswordCheckerClient:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Password_Checker_Rework_2
{
    class PasswordCheckClient
    {
        private string passwordfilepath;

        public string Passwordfilepath
        {
            get { return passwordfilepath; }
            set { passwordfilepath = value; }
        }
        private PasswordChecker passwordchecker;
        public void Proccess(string applicationdirectory)
        {
            if (Directory.Exists(applicationdirectory))
            {
                Console.WriteLine("Loaded Programm-Directory...");
            }
            else if (!Directory.Exists(applicationdirectory))
            {
                Console.Write("Creating Program-Directory...");
                Directory.CreateDirectory(applicationdirectory);
                Console.WriteLine("Done...");
            }
            Console.Write("PasswordChecker\nPath:");
            Passwordfilepath = Console.ReadLine();




            FileInfo sourcefileinfo = new FileInfo(Passwordfilepath);


            if (sourcefileinfo.Exists)
            {
                Console.Write("Your password:");
                var password = Console.ReadLine();

                var checker = new PasswordChecker(password, Passwordfilepath);
                IPasswordLoader passwordLoader;


                if (FileisZip(sourcefileinfo))
                {
                    passwordLoader = new ZipPasswordLoader(applicationdirectory);
                    passwordLoader.InputNeeded += ZipFileInputNeeded;
                }
                else if (FileisText(sourcefileinfo))
                {
                    passwordLoader = new TextPasswordLoader();
                }
                else
                {
                    passwordLoader = null;
                    Console.WriteLine("Unsupported password file type.");
                }

                try
                {
                    Console.WriteLine("Started Reading...");
                    checker.CheckPasswords(passwordLoader);

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }



            else
            {
                Console.WriteLine("Your file does not exists!");
            }
                Console.WriteLine("Cleaning up application directory...");
                Directory.Delete(applicationdirectory, true);
                Console.ReadKey();

            
        }
        private bool FileisZip(FileInfo sourcefileinfo)
        {
            return sourcefileinfo.Extension.ToUpper() == ".ZIP";
        }
        private bool FileisText(FileInfo sourcefileinfo)
        {
            return sourcefileinfo.Extension.ToUpper() == ".TXT";
        }
        private void ZipFileInputNeeded(object sender,EventArgs args)
        {
            ZipPasswordLoader loader = sender as ZipPasswordLoader;
            Console.Write("Choose entry:");
            loader.Choosenentry = Console.ReadLine();
        }

    }
}


PasswordChecker.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Password_Checker_Rework_2
{
    
    class PasswordChecker
    {

        private string passwordtocheck;

        public string Passwordtocheck
        {
            get { return passwordtocheck; }
            set { passwordtocheck = value; }
        }
        private string sourcepath;

        public string Sourcepath
        {
            get { return sourcepath; }
            set { sourcepath = value; }
        }

        public PasswordChecker(string passwordtocheck,string sourcepath)
        {
            this.Passwordtocheck = passwordtocheck;
            this.Sourcepath = sourcepath;
        }
        public void CheckPasswords(IPasswordLoader Loader)
        {
            string[] passwordlist;
            passwordlist = Loader.Load(Sourcepath);
            if (passwordlist != null)
            {
                Console.WriteLine("Finished reading...");
                bool foundedpassword = false;
                for (int i = 0; i <= passwordlist.Length - 1; i++)
                {
                    if (Passwordtocheck == passwordlist[i])
                    {
                        Console.WriteLine("{0,-20}{1}", passwordlist[i], "TRUE");
                        foundedpassword = true;
                        break;
                    }

                    else
                    {
                        Console.WriteLine("{0,-20}{1}", passwordlist[i], "FALSE");
                    }
                }
                if (foundedpassword)
                    Console.WriteLine("Founded your password! Better choose another one...");
                else
                    Console.WriteLine("Don't founded your password!");
            }
            
        }
                


    }
}


IPasswordLoader.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Password_Checker_Rework_2
{
    delegate void InputNeededEventHandler(object sender, EventArgs args);
    interface IPasswordLoader
    {
       
        string[] Load(string sourcepath);
        event InputNeededEventHandler InputNeeded;


    }
}


Zippasswordloader.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Compression;
using System.IO;
namespace Password_Checker_Rework_2
{



    class ZipPasswordLoader : IPasswordLoader
    {
        private string applicationdirectory;
        public ZipPasswordLoader(string applicationdirectory)
        {
            this.applicationdirectory = applicationdirectory;
        }
        private string choosenentry;

        public string Choosenentry
        {
            get { return choosenentry; }
            set { choosenentry = value; }
        }
        public event InputNeededEventHandler InputNeeded;

        public string[] Load(string sourcepath)
        {
            List<string> output = new List<string>();
           
                FileStream fs = new FileStream(sourcepath, FileMode.Open);
                ZipArchive archive = new ZipArchive(fs);
                Console.WriteLine("Entries in Archive:");

                for (int i = 0; i <= archive.Entries.Count - 1; i++)
                {
                    Console.WriteLine(i + "." + archive.Entries[i].Name);
                }
                if (Choosenentry != null) InputNeeded(this, null);
                
                Validator validator = new Validator();

                if (validator.InputIndexIsValid(choosenentry, archive.Entries.Count))
                {
                    int validatedchoosenentry = int.Parse(choosenentry);
                    ZipArchiveEntry entry = archive.Entries[validatedchoosenentry];

                    string extractedfilepath = Path.Combine(applicationdirectory, entry.Name);
                    entry.ExtractToFile(extractedfilepath);

                    StreamReader reader = new StreamReader(extractedfilepath);
                    while (reader.Peek() != -1)
                    {
                        output.Add(reader.ReadLine());

                    }
                    reader.Close();

                }
                else
            {
                throw new Exception("Can not validate your input!");
            }
            
            return output.ToArray();
        }
    }
}


TextPasswordLoader.cs:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Password_Checker_Rework_2
{
    class TextPasswordLoader : IPasswordLoader
    {
        public event InputNeededEventHandler InputNeeded;


        public string[] Load(string sourcepath)
        {
            
            List<string> output = new List<string>();
            try
            {
                var reader = new StreamReader(sourcepath);
                while (reader.Peek() != -1)
                {
                    output.Add(reader.ReadLine());
                }

                reader.Close();
            }
            catch
            {
                throw new Exception("Error while loading .txt file.");
            } 
            return output.ToArray();
        }
    }
}


Validator.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Password_Checker_Rework_2
{
    class Validator
    {
      
           public bool InputIndexIsValid(string value, int arrayLength)
        {
            int output;
            if (!int.TryParse(value, out output))
            {
                return false;
            }
            if (output <= arrayLength - 1 && output >= 0)
            {
                return false;
            }
            return true;
        }
    


    }
}


Ist meine Umsetzung okay? Ich habe mich entschieden in Proccess und LoadPassworts die Konsole zu verwenden...

LG

LG

06.01.2016 - 15:37 Uhr

@LaTino Das Problem mit der Event-Lösung ist, dass Password-Checker das Event garnicht besitzt.
Soll ich denn IPasswordLoader einfach in ein ZipFilePasswordLoader konvertieren? Das wäre für mich nicht so schön, bin aber wie allen schon aufgefallen ist kein Profi.. Also kann man das so lösen?

Ich bin gerade dabei alle Consoles aus den Klassen zu entfernen, dabei ist mir aufgefallen:
-Die Klassen sind nun allgemeiner, egal ob sie aus der Console oder aus einer FensterAnwendung gestartet werden..
-Das Problem ist aber, dass ich wesentlich weniger Auskunft über den Fehler bzw. das Ereigniss geben kann.. Soll ich eine Exception schmeißen, und in der Message den Grund mitgeben und bei einem Ereigniss also z.B. Das Extrahieren wurde beendet eine event feuern, bei dem dann in Proccess einfach die Ausgabe erfolgt?

LG

PS: Vielen Dank für die ganze Hilfe, hilft mir extrem weiter. Ich habe aber erst jetzt gemerkt wie wichtig Praxis ist!

06.01.2016 - 10:18 Uhr

Ich hoffe das wird jetzt der letzte Versuch, dieses Program hinzubekommen.
Program.cs


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    namespace Password_Checker_Rework_2
    {
        class Program
        {
            static void Main(string[] args)
            {
                var appDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),"passwordchecker");
                var passwordcheckerclient = new PasswordCheckClient();
                passwordcheckerclient.Proccess(appDir);
            }
        }
    }


PasswordCheckerClient.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Password_Checker_Rework_2
{
    class PasswordCheckClient
    {
        private string passwordfilepath;

        public string Passwordfilepath
        {
            get { return passwordfilepath; }
            set { passwordfilepath = value; }
        }
        private PasswordChecker passwordchecker;
        public void Proccess(string applicationdirectory)
        {
            if(Directory.Exists(applicationdirectory))
            {
                Console.WriteLine("Loaded Programm-Directory...");
            }
            else if(!Directory.Exists(applicationdirectory))
            {
                Console.Write("Creating Program-Directory...");
                Directory.CreateDirectory(applicationdirectory);
                Console.WriteLine("Done...");
            }
            Console.Write("PasswordChecker\nPath:");
            Passwordfilepath = Console.ReadLine();

            

           
            FileInfo sourcefileinfo = new FileInfo(Passwordfilepath);
            if(sourcefileinfo.Exists)
            {
                Console.Write("Your password:");
                string password = Console.ReadLine();
               
                PasswordChecker checker = new PasswordChecker(password,Passwordfilepath);
                if (FileisZip(sourcefileinfo))
                {
                    ZipPasswordLoader loader = new ZipPasswordLoader(applicationdirectory);
                    checker.CheckPasswords(loader);
                }
                else if (FileisText(sourcefileinfo))
                {
                    TextPasswordLoader loader = new TextPasswordLoader();
                    checker.CheckPasswords(loader);
                }
                else
                {
                    Console.WriteLine("Your format is not supported!");
                }

            }
         else
            {
                Console.WriteLine("Yout file does not exists!");
            }
            Console.WriteLine("Cleaning up application directory...");
            Directory.Delete(applicationdirectory, true);
            Console.ReadKey();
                   
        }
        private bool FileisZip(FileInfo sourcefileinfo)
        {
            return sourcefileinfo.Extension.ToUpper() == ".ZIP";
        }
        private bool FileisText(FileInfo sourcefileinfo)
        {
            return sourcefileinfo.Extension.ToUpper() == ".TXT";
        }
    }
}


PasswordChecker.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Password_Checker_Rework_2
{
    class PasswordChecker
    {

        private string passwordtocheck;

        public string Passwordtocheck
        {
            get { return passwordtocheck; }
            set { passwordtocheck = value; }
        }
        private string sourcepath;

        public string Sourcepath
        {
            get { return sourcepath; }
            set { sourcepath = value; }
        }

        public PasswordChecker(string passwordtocheck,string sourcepath)
        {
            this.Passwordtocheck = passwordtocheck;
            this.Sourcepath = sourcepath;
        }
        public void CheckPasswords(IPasswordLoader Loader)
        {
            Console.WriteLine("Press any key to start checking...");
            Console.ReadKey();
            string[] passwordlist;
            passwordlist = Loader.Load(Sourcepath);
            if (passwordlist != null)
            {
                bool foundedpassword = false;
                for (int i = 0; i <= passwordlist.Length - 1; i++)
                {
                    if (Passwordtocheck == passwordlist[i])
                    {
                        Console.WriteLine("{0,-20}{1}", passwordlist[i], "TRUE");
                        foundedpassword = true;
                        break;
                    }

                    else
                    {
                        Console.WriteLine("{0,-20}{1}", passwordlist[i], "FALSE");
                    }
                }
                if (foundedpassword)
                    Console.WriteLine("Founded your password! Better choose another one...");
                else
                    Console.WriteLine("Don't founded your password!");
            }
            
        }
                


    }
}


IPasswordLoader.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Password_Checker_Rework_2
{
    interface IPasswordLoader
    {
        string[] Load(string sourcepath);



    }
}


TextPasswordLoader.cs:



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Password_Checker_Rework_2
{
    class TextPasswordLoader : IPasswordLoader
    {



        public string[] Load(string sourcepath)
        {
            Console.WriteLine("Started reading....");
            List<string> output = new List<string>();
            var reader = new StreamReader(sourcepath);
            while(reader.Peek() != -1)
            {
                output.Add(reader.ReadLine());
            }
            Console.WriteLine("Finished Reading...");
            reader.Close();
            return output.ToArray();
        }
    }
}


ZipPasswordLoader.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Compression;
using System.IO;
namespace Password_Checker_Rework_2
{



    class ZipPasswordLoader : IPasswordLoader
    {
        private string applicationdirectory;
        public ZipPasswordLoader(string applicationdirectory)
        {
            this.applicationdirectory = applicationdirectory;
        }
        public string[] Load(string sourcepath)
        {
            List<string> output = new List<string>();
            FileStream fs = new FileStream(sourcepath, FileMode.Open);
            ZipArchive archive = new ZipArchive(fs);
            Console.WriteLine("Entries in Archive:");

            for (int i = 0;i <= archive.Entries.Count - 1;i++)
            {
                Console.WriteLine(i+"."+archive.Entries[i].Name);
            }
            string choosenentry = Console.ReadLine();
            Validator validator = new Validator();

            if(validator.InputIndexIsValid(choosenentry, archive.Entries.Count))
            {
                int validatedchoosenentry = int.Parse(choosenentry);
                ZipArchiveEntry entry = archive.Entries[validatedchoosenentry];
                Console.WriteLine("Extracting entry to application directory...");
                string extractedfilepath = Path.Combine(applicationdirectory, entry.Name);
                entry.ExtractToFile(extractedfilepath);
                Console.WriteLine("Completed!");
                StreamReader reader = new StreamReader(extractedfilepath);
                while(reader.Peek() != -1)
                {
                    output.Add(reader.ReadLine());

                }
                reader.Close();
                Console.WriteLine("Completed reading!");   
            }
            else
            {
                Console.WriteLine("Can not validate Input");
            }
            return output.ToArray();
        }
    }
}


Validator.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Password_Checker_Rework_2
{
    class Validator
    {
      
           public bool InputIndexIsValid(string value, int arrayLength)
        {
            int output;
            if (!int.TryParse(value, out output))
            {
                return false;
            }
            if (output <= arrayLength - 1 && output >= 0)
            {
                return false;
            }
            return true;
        }
    


    }
}


Eigentlich wollte ich jegliche Nutzerinput in Proccess() haben. Dann würde aber das sourcepath Parameter in ZipLoader keinen Sinn machen, da ich dann einfach der Klasse über den Konstruktor das Zip Archive Entry übergeben... Was ist in diesem Fall besser?

LG

05.01.2016 - 11:49 Uhr

Vielen Dank für die Antworten, vorallem für die Grafik von LaTino... Ich habe aber noch drei Fragen dazu:
-In Proccess ist der Ablauf und der User-Input?
-Wie soll ich den applictationdirectory-pfad in die ZipFilePasswordLoader bekommen?
-Wenn ich mit dem Interface eine Klasse zum Laden einer Datenband bereitstelllen möchte brauche ich kein path parameter, sonder andere.Die Frage ist mehr theoretisch, aber wie würde ich soetwas umsetzten?

LG und nochmal vielen Dank...

04.01.2016 - 22:38 Uhr

Ich habe jetzt eine Version entwickelt, in der wie T-Virus meinte nur Program und eine Parser Klasse existieren. Sie ist überhaupt nicht getestet, noch habe bisher auf richtiges Englisch geachtet.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Compression;
namespace Password_Checker_Rework
{
    delegate string[] LoadMethode(string sourcepath);
    class Program
    {
        string applicationdirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "passwordchecker");

        static void Main(string[] args)
        {
            Program program = new Program();
            #region ProgrammFolderCreation
            DirectoryInfo programmfolderinfo = new DirectoryInfo(program.applicationdirectory);

            if (!programmfolderinfo.Exists)
            {
                programmfolderinfo.Create();
                Console.WriteLine("Created Program-Folder.");
            }
            else if (programmfolderinfo.Exists)
            {
                Console.WriteLine("Loaded Program-Folder.");
            }

            #endregion
            Console.Write("Filepath to sourcelist:");
            string sourcepath = Console.ReadLine();
            if (File.Exists(sourcepath))
            {
                FileInfo sourcefileinfo = new FileInfo(sourcepath);

                Console.WriteLine("Detecting file-type...");
                LoadMethode LoadmethodeHandler = null;
                if (sourcefileinfo.Extension == ".zip")
                {
                    LoadmethodeHandler += program.LoadPasswordsfromzip;
                }

                else if (sourcefileinfo.Extension == ".txt")
                {
                    LoadmethodeHandler += program.LoadPasswordsfromtxt;
                }
                else
                {
                    Console.WriteLine("Your data-type is not supported!");
                }
                if (LoadmethodeHandler != null)
                {
                    string[] passwords = LoadmethodeHandler(sourcefileinfo.FullName);
                    if(passwords != null)
                    {
                        Console.Write("Your Password:");
                        string password = Console.ReadLine();

                        bool success = program.CheckPasswords(passwords, password);
                        if(success)
                        {
                            Console.WriteLine("Founded your password!");

                        }
                        else
                        {
                            Console.WriteLine("Did not find your password!");
                        }
                    }
                }

            }
            else
            {
                Console.WriteLine("Your file does not exist.");
            }
            Console.WriteLine("Cleaning up programm data...");
            Directory.Delete(programmfolderinfo.FullName, true);
            Console.ReadKey();
        }

        private string[] LoadPasswordsfromtxt(string sourcepath)
        {
            Console.WriteLine("Opening .txt file...");
            StreamReader reader = new StreamReader(sourcepath);
            Console.WriteLine("Reading Passwords...");
            string[] output = ReadPasswords(reader);
            return output;
        }

        private string[] LoadPasswordsfromzip(string sourcepath)
        {
            string[] output = null;
            FileStream fs = new FileStream(sourcepath, FileMode.Open);
            System.IO.Compression.ZipArchive archive = new ZipArchive(fs);
            for (int i = 0; i < archive.Entries.Count - 1; i++)
            {
                Console.WriteLine(i + "." + archive.Entries[i].Name);
            }
            Console.Write("Choose:");
            string choosenentry = Console.ReadLine();
            Parser parser = new Parser();
            int choosenentryint = parser.Parsestringtofile(choosenentry, 0, archive.Entries.Count - 1);
            if (choosenentryint != -1)
            {
                ZipArchiveEntry entry = archive.GetEntry(archive.Entries[choosenentryint].FullName);
                Console.WriteLine("Extracting to temp-folder...");
                string extractedfilepath = Path.Combine(applicationdirectory, "passwords.txt");
                entry.ExtractToFile(extractedfilepath);
                Console.WriteLine("Opening file...");

                output = LoadPasswordsfromtxt(extractedfilepath);
            }
            else
            {
                Console.WriteLine("Could not parse your input.");
            }
            return output;
        }
        private string[] ReadPasswords(StreamReader reader)
        {
            List<string> passwords = new List<string>();
            while (reader.Peek() != -1)
            {
                passwords.Add(reader.ReadLine());
            }
            return passwords.ToArray();

        }
        private bool CheckPasswords(string[] passwords,string password)
        {
            Console.WriteLine("Press any key to start reading...");
            Console.ReadKey();
            Console.WriteLine("{0,-20}{1}","PASSWORD", "ACCORDANCE");
            bool success = false;
            for(int i = 0;i <= passwords.Length - 1;i++)
            {
                if(passwords[i] == password)
                {
                    success = true;
                    Console.WriteLine("{0,-20}{1}",passwords[i],"TRUE");
                    break;
                }
                else
                {
                    Console.WriteLine("{0,-20}{1}",passwords[i],"FALSE");
                }
            }
            return success;
        }

    }
}

Parser.cs:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Password_Checker_Rework
{
    class Parser
    {
public int Parsestringtofile(string value,int min,int max)
        {
            int output;
            bool parsesuccess = int.TryParse(value, out output);
            if(parsesuccess)
            {
                if(output <= max && output >= min)
                {
                    return output;
                }
                else
                {
                    return -1;
                }
            }
else
            {
                return -1;
            }

        }


    }
}


Ist mir diese Version besser gelungen?
Wo wäre eine Klasse jetzt noch sinnvoll zu implementieren? Für den Program-Ordner?

LG

04.01.2016 - 20:15 Uhr

Habe den Beitrag editiert 🙂

04.01.2016 - 19:42 Uhr

Es geht um die Implementierung der Klassen im Zusammenhang mit Simple Responsibility Principle.
Der Grundstatz ist so wie ich es verstanden habe: Jede Klasse hat eine Aufgabe.

Ich habe nun die Programmstruktur mit diesem Grundsatz durchdacht:
Das Program soll die möglichkeit haben die Liste in den Arbeitsspeicher zu laden. Das ist für mich eine Aufgabe. Der Rückgabewert dieser Methode wäre ein Stream-Reader. Oben wurde aber gesagt man sollte nur Daten, also z.B. eine Liste zurückgeben.Um dies umzusetzen müsste ich einfach in der Klasse den Stream Reader als Feld bereitstellen und dann die Methode GetPasswords implemntieren, die die Passwörter ausliest. Das Auslesen wäre für mich aber schon eine andere Aufgabe, die dann ja schon wieder in eine andere Klasse gehört. Wie soll ich das lösen?

LG

04.01.2016 - 18:36 Uhr

Sorry, aber ich verstehe immer noch nicht was du mit Objekt von Daten zürückgeben meinst. Soll ich den Streamreader als Eigenschaft bereitstellen, und dann zum schließen einfach die Close Methode der Eigenschaft aufrufen 😉

LG

04.01.2016 - 17:18 Uhr

Hallo,
ich werde das komplette Projekt nochmal komplett neu beginnen. Dafür brauche ich aber noch ein paar Inforamtionen:
-In Main ist static unnütz sehe ich ein.
-Aber in Load_Method und Parser_Methods sehe ich keinen Sinn von nicht static.. Die bereitgestellten Methoden funktionieren ohne oder mit static fast gleich. Ich könnte mir aber z.B. vorstellen hier einen ein string Feld mit dem Programm-Ordner Pfad zu erstellen, aber lohnt es sich?
Ich kann eurer Diskussion über Dispose bzw. den Finalizer nicht ganz folgen...:
->Der Destruktor wird doch in die Finalize Methode umgewandelt.In dieser sollen Fremdresourcen freigegeben werden?
->Was verstehe ich unter Fremdresourcen? Bisher verstehe ich auch ein File als Fremdresource.
->Die Dispose Methode ist da um dieses Ereigniss auslösen zu können. Was soll ich hier freigeben bzw. wann lohnt sich die Implementierung.

-Also für meine Directory Klasse ist es besser wenn ich einfach eine Delete Methode bereitstelle?
-Soll ich nun die Load_Methods Klasse auflösen und einfach alles in Main() implementieren, oder diese belassen.
-Ich kann mir die Umsertzung nicht vorstellen:

Die Methode loadtxt gibt, einen StreamReader zurück was nicht so schon ist. Da er Dispose Implementiert und es schöner ist wenn einen Klasse die ein Objekt erzeugt es auch Disposed.

-Das Englisch werde ich nochmal anschauen...
-Was von welcher Methode soll ich aufteileen?

LG
LG

04.01.2016 - 12:49 Uhr

Hallo,
ich habe gerade mein erstes richtiges Projekt vertiggestellt. Es ist ein Tool um eine Passwort-Liste einzulesen und damit sein Passwort zu überprüfen:

Program.cs:


    delegate StreamReader Loadmethode(string path);
    class Program
    {
        
        static string targetedpassword = null;
        static Directory_System tempfiles;
       
       
        
        static void Main(string[] args)
        {
            Console.Title = "Password-Checker";
            try
            {
                tempfiles = new Directory_System(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "password_checker_temp"));
                Console.WriteLine("Created Temp-Folder:\n" + tempfiles.DirectoryPath);
            }
           catch
            {
                Console.WriteLine("Cant create Temp-Folder!");
            }
        if(tempfiles != null)
            {
                Console.WriteLine("This programm will read a passwordlist (.zip or .txt file)\nand check about the accordance to one password of the list.");
                Console.Write("Path to the password-list:");
                string path = Console.ReadLine();

                FileInfo info = null;





                info = new FileInfo(path);


                if (info != null && info.Exists)
                {
                    Loadmethode LoadmethodeHandler = null;
                    string detectedmethod = null;
                    if (info.Extension == ".zip")
                    {
                        detectedmethod = ".zip";
                        LoadmethodeHandler = ziploadsetup;

                    }
                    else if (info.Extension == ".txt")
                    {
                        detectedmethod = ".txt";
                        LoadmethodeHandler = Load_Methods.loadtxt;
                    }
                    if (detectedmethod != null)
                    {
                        Console.WriteLine("Detected your file as a:{0} file.", detectedmethod);
                    }
                    else
                    {
                        Console.WriteLine("Can not detect your data type.");
                        LoadmethodeHandler = null;
                        Console.Write("Methods:\n0.zip\n1.txt\nChoose:");

                        if (Console.ReadKey().Key == ConsoleKey.D0)
                        {
                            LoadmethodeHandler += ziploadsetup;
                        }

                        else
                        {
                            LoadmethodeHandler += Load_Methods.loadtxt;
                        }
                    }

                    StreamReader reader = LoadmethodeHandler(path);


                    if (reader != null)
                    {
                        Console.Write("Your Password:");
                        targetedpassword = Console.ReadLine();
                        Console.Write("Press any key to start reading...");
                        Console.ReadKey();
                        Console.Clear();
                        Console.WriteLine("{0,-20}{1}", "password", "accordance");
                        bool founded = false;
                        while (reader.Peek() != -1)
                        {
                            string readedline = reader.ReadLine();
                            if (readedline == targetedpassword)
                            {
                                Console.WriteLine("{0,-20}{1}", readedline, "TRUE");
                                founded = true;
                                break;
                            }
                            else
                            {
                                Console.WriteLine("{0,-20}{1}", readedline, "FALSE");
                            }

                        }
                        if (founded == true)
                        {
                            Console.WriteLine("Founded your password! Better chosse another one.");

                        }
                        else
                        {
                            Console.WriteLine("Did not found your password.");
                        }
                        reader.Close();

                    }

                }
                else
                {
                    Console.WriteLine("Your file does not exists.");
                }
                Console.WriteLine("Cleaning up the temp programm data.");
                tempfiles.Dispose();
                Console.ReadKey();
            }    
       
        }
        public static StreamReader ziploadsetup(string path)
        {
            Console.WriteLine();
            StreamReader reader = null;
            FileStream fs = null;
            try
            {
                fs = new FileStream(path, FileMode.Open);
            }


            catch
            {
                Console.WriteLine("Can not open your path");
            }
            ZipArchive archive = null;
            if (fs != null)
            {
                try
                {
                    archive = new ZipArchive(fs, ZipArchiveMode.Update);

                }
                catch
                {
                    Console.WriteLine("Can not open as a Zip-File.");
                }
            }
            if (archive != null)
            {
                Console.WriteLine("Zip-loading:");
                Console.WriteLine("Entries in path:");
                for (int i = 0; i <= (archive.Entries.Count - 1); i++)
                {
                    Console.WriteLine("{0}.{1}", i, archive.Entries[i].Name);

                }


                Console.WriteLine("Choose your Textdocument\n(The program will try to open any document as an .txt file):");
                string documentchoose = Console.ReadLine();
                int a = Parser_Methods.Parse_string_to_int(documentchoose, 0, (archive.Entries.Count - 1));
                if (a != -1)
                {
                    Console.Write("The programm supports to zip loading methods:\n0.Loading in RAM/{0}\n1.Extracting to file and reading.\nChoose:", archive.Entries[a].Length + " Bytes");
                    string loadingmethode = Console.ReadLine();
                    int b = Parser_Methods.Parse_string_to_int(loadingmethode, 0, 1);
                    if (b != -1)
                    {
                        switch (b)
                        {
                            case 0:
                                Console.WriteLine("The file is maybe to large and can overload your RAM:{0}.\nDo you really want to start loading? Y/N", archive.Entries[a].Length + " Bytes");
                                if (Console.ReadKey().Key == ConsoleKey.Y)
                                {
                                    reader = Load_Methods.load_zip_in_ram(archive.Entries[a]);
                                    Console.WriteLine("\nLoaded successfull:\n" + Path.Combine(path, archive.Entries[a].FullName));
                                }
                                else
                                {
                                    Console.WriteLine("Exiting...");
                                }
                                break;
                            case 1:
                                reader = Load_Methods.load_zip_from_extractet_file(archive.Entries[a],tempfiles.DirectoryPath);
                                break;
                        }
                    }
                    else
                    {
                        Console.WriteLine("Can not parse your input.");

                    }

                }
                else
                {
                    Console.WriteLine("Can not parse your input.");
                }


            }
            return reader;
        }


    }


Load_Methods.cs:


static class Load_Methods
    {
        public static StreamReader loadtxt(string path)
        {
            Console.WriteLine();

            StreamReader reader = null;
            try
            {
                reader = new StreamReader(path);

            }
            catch
            {
                Console.WriteLine("Can not open as .txt!");

            }
            Console.WriteLine("Succesfully loaded as .txt!");
            return reader;
        }
  
        public static StreamReader load_zip_in_ram(ZipArchiveEntry entry)
        {
            Stream stream = entry.Open();
            StreamReader reader = new StreamReader(stream);

            return reader;
        }
        public static StreamReader load_zip_from_extractet_file(ZipArchiveEntry entry,string destination )
        {
            StreamReader reader = null;
            try
            {

                Directory.CreateDirectory(destination);
                string filedestination = Path.Combine(destination, "temp.txt");
                Console.WriteLine("Writing to this file:\n" + filedestination);
                entry.ExtractToFile(filedestination);

                reader = new StreamReader(filedestination);
                Console.WriteLine("Completed!");
            }
            catch
            {
                Console.WriteLine("Error while extracting or reading out of temp file!");
            }
            return reader;
        }



    }

Directory_System.cs:


        public class Directory_System: IDisposable
        {
            private string directorypath;

            public string DirectoryPath
            {
                get { return directorypath; }
                set
            {
                if(Directory.Exists(value))
                directorypath = value;
                else if(!Directory.Exists(value))
                {
                    try
                    {
                        Directory.CreateDirectory(value);
                        directorypath = value;
                    }
                catch
                    {
                        throw new Exception();                  
                    }
                    }
            }
            }

        public Directory_System(string destinationpath)
            {
            this.DirectoryPath = destinationpath;
        }
        bool disposed = false;
        public void Dispose()
        {
            if (!disposed)
            {

                Dispose(true);
                GC.SuppressFinalize(this);
                disposed = true;
            }
        }
        protected virtual void Dispose(bool disposing)
        {
            if(disposing)
            {
                Directory.Delete(DirectoryPath, true);
                this.DirectoryPath = null;
                
            }
            else
            {
                Directory.Delete(DirectoryPath, true);
            }
        }
        ~Directory_System()
        {
            Dispose(false);
        }
    }


Parser_Methods.cs:


 static class Parser_Methods
    {
        public static int Parse_string_to_int(string value, int min, int max)
        {
            int output = 0;
            bool parsesuccess = int.TryParse(value, out output);
            if (parsesuccess && output >= min && output <= max)
            {

            }
            else
            {
                output = -1;
            }
            return output;

        }
    }

Nun zu meiner Frage: Habe ich die Objektorientierung richtig angewandt?
Es wäre zwar nett wenn jemand den Code durchsehen würde, aber hier ein paar Fragen die ich mit stelle:
-Ab wann sollte ich Methoden in eigne Klassen verschieben? (z.B. Parser_Methods.cs)
-Sollte man für Directory_System eine eigene Klasse machen, oder einfach einen string in Main() mit dem Pfad dazu verwalten?
-Ist die Verwendung von Dispose() richtig statt einfach z.B. Clean_up_Directory bereitzustellen?

-Sollte ich in Load_zip_from_extract_file den Pfad zum Programm-Ordner als einfachen string übergeben, oder das Directory_System Objekt mit der Pfadeigenschaft weitergeben?

Vielen Dank im voraus für die Antworten, klar ist es ein bisschen Aufwand den Code durchzusehen, ich habe mich in meinem ersten richtigen Objekt hier aber bemüht die Varaiblen-Namen möglichst einfach lesbar zu halten.

Grüße!

PS: Hoffe das es nun besser verständlich ist, der Code dürfte nun normal lesbar sein, und ich hab die Fragen nochmmal anders formuliert, um sie besser verständlich zu machen....Ich poste einfach mal hier, da es meiner ANsicht besser passt als in die Grundlagen zu C# Rubrik