<repo_name>SamyCoenen/.NetEncryptCommWPF<file_sep>/BasicSec/BasicSec/ContactVerwijderen.xaml.cs
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BasicSec
{
    /// <summary>
    /// Interaction logic for ContactVerwijderen.xaml
    /// </summary>
    public partial class ContactVerwijderen : Window
    {

        public List<string> contacten = new List<string>(); //lijst van alle zenders en ontvangers

        public ContactVerwijderen()
        {
            ContactenUpdate();

            InitializeComponent();

            ButtonCheck();

            listBoxContacten.ItemsSource = contacten;
        }

        private void buttonVerwijderen_Click(object sender, RoutedEventArgs e)
        {
            Directory.Delete(@".\Contacten\" + listBoxContacten.SelectedItem.ToString(), true);
            contacten.Clear();
            ContactenUpdate();
            listBoxContacten.Items.Refresh();
            ButtonCheck();
        }

        public void ContactenUpdate()
        {
            foreach (string naam in Directory.GetDirectories(@".\Contacten"))
            {
                contacten.Add(naam.Remove(0, 12));
            }
        }

        public void ButtonCheck()
        {
            if (contacten.Count == 0)
            {
                buttonVerwijderen.IsEnabled = false;
            }
            else
            {
                buttonVerwijderen.IsEnabled = true;
                listBoxContacten.SelectedIndex = 0;
            }
        }
    }
}
<file_sep>/BasicSec/BasicSec/TcpServer.cs
﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;

namespace BasicSec
{
    class TcpServer
    {
        private TcpListener _server;
        private AutoResetEvent connectionWaitHandle = new AutoResetEvent(false);
        private Boolean _isRunning;
       private string path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

        public TcpServer(int port,TextBox statusTextBox,TextBox textTextBox)
        {
            Console.WriteLine("i come here");
            _server = new TcpListener(IPAddress.Any, port);
            _server.Start();

            _isRunning = true;

            while (true)
            {
                //IAsyncResult result = _server.BeginAcceptTcpClient(HandleAsyncConnection, _server);
                //connectionWaitHandle.WaitOne(); // Wait until a client has begun handling an event
                //connectionWaitHandle.Reset(); // Reset wait handle or the loop goes as fast as it can (after first request)
                TcpClient client = _server.AcceptTcpClient();
                StreamReader sReader = new StreamReader(client.GetStream(), Encoding.UTF8);
                
                
                String sData = null;

                while (client.Connected)
                {
                    // reads from stream
                    while (sReader.EndOfStream == false)
                    {
                        sData += sReader.ReadLine();
                    }
                    if (sData.Equals("De text hash is OK"))
                    {
                        Application.Current.Dispatcher.Invoke(
                      DispatcherPriority.Background,
                      new Action(() =>
                          // shows content on the console.
                          
                          textTextBox.Text = File.ReadAllText(path+"\\CryptoSavedChatFile.txt")

                          ));
                    }
                    Application.Current.Dispatcher.Invoke(
                       DispatcherPriority.Background,
                       new Action(() =>
                           // shows content on the console.
                           statusTextBox.Text =  System.DateTime.Now +": "+ sData + Environment.NewLine + statusTextBox.Text

                           ));
                    client.Close();
                }

                    // to write something back.
                    // sWriter.WriteLine("Meaningfull things here");
                    // sWriter.Flush();

                }
            }
        

        //public void HandleAsyncConnection(IAsyncResult obj)
        //{
        //    // retrieve client from parameter passed to thread
        //    TcpClient client = _server.AcceptTcpClient();

        //    // sets two streams
           
        //    StreamReader sReader = new StreamReader(client.GetStream(), Encoding.UTF8);
        //    // you could use the NetworkStream to read and write, 
        //    // but there is no forcing flush, even when requested

        //    Boolean bClientConnected = true;
        //    String sData = null;

        //    while (bClientConnected)
        //    {
        //        // reads from stream
        //        sData = sReader.ReadLine();

        //        // shows content on the console.
        //        ((MainWindow) System.Windows.Application.Current.MainWindow).listStatus.Text +=Environment.NewLine +  new DateTime().TimeOfDay+sData;
        //        Console.WriteLine("Client &gt; " + sData);

        //        // to write something back.
        //        // sWriter.WriteLine("Meaningfull things here");
        //        // sWriter.Flush();
        //    }
        //}
    }
}
<file_sep>/BasicSec/BasicSec/ContactToevoegen.xaml.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BasicSec
{
    /// <summary>
    /// Interaction logic for ContactenToevoegen.xaml
    /// </summary>
    public partial class ContactenToevoegen : Window
    {
        public ContactenToevoegen()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            string naam = textBoxNaam.Text;
            string ip = textBoxIP.Text;

            if (Directory.Exists(@".\Contacten\" + naam))
            {
                MessageBox.Show("Dit contact bestaat al");
            }
            else
            {
                Directory.CreateDirectory(@".\Contacten\" + naam);
                using (StreamWriter outputFile = new StreamWriter(@".\Contacten\" + naam + @"\IP.txt"))
                {
                    outputFile.WriteLine(ip);
                    MessageBox.Show("Dit contact is goed toegevoegd!");
                }
            }
        }
    }
}
<file_sep>/BasicSec/BasicSec/MainWindow.xaml.cs
﻿using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using MahApps.Metro.Controls;

namespace BasicSec
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        private string filepath=null;
        private List<string> contacten = new List<string>(); //lijst van alle zenders en ontvangers
       private  NetworkStream stream;
        private byte[] buf;
       
        public MainWindow()
        {
            InitializeComponent();
     
                Thread thread = new Thread(() =>
                {
                    TcpServer server = new TcpServer(8889, listStatus,textBoxBoodschap);
                    //System.Windows.Threading.Dispatcher.Run();
                });
                thread.Start();
 
            if (!Directory.Exists(@".\Contacten"))
            {
                Directory.CreateDirectory(@".\Contacten");
            }
                        ContactenUpdate();       
            listBoxZenders.ItemsSource = contacten;
            listBoxZenders.SelectedIndex = 0;
            //listBoxOntvangers.ItemsSource = contacten;
            //listBoxOntvangers.SelectedIndex = 1;         
           // IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());       
        }

        //RadioButtons
        //private void radioButton(object sender, RoutedEventArgs e)
        //{
        //    if (radioButtonEncrypteren.IsChecked == true)
        //    {
        //        radioButtonDecrypteren.IsChecked = false;
        //        buttonEncrypterenDecrypteren.Content = "Encrypteren";
        //        labelHashCheck.Visibility = System.Windows.Visibility.Hidden;
        //    }
        //    else if (radioButtonDecrypteren.IsChecked == true)
        //    {
        //        radioButtonEncrypteren.IsChecked = false;
        //        buttonEncrypterenDecrypteren.Content = "Decrypteren";
        //        labelHashCheck.Visibility = System.Windows.Visibility.Visible;
        //    }
        //}

        //encrypteren en decrypteren
        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            //    if (radioButtonDecrypteren.IsChecked == true)
            //    {
            //        if (File.Exists(@".\Boodschap.txt"))
            //        {
            //            File.Delete(@".\Boodschap.txt");
            //        }
            //        StreamWriter outputFile = new StreamWriter(@".\Boodschap.txt");
            //        outputFile.WriteLine(textBoxBoodschap.Text);
            //        outputFile.Close();
            //        outputFile.Dispose();
            //string destinationip = GetIP(listBoxOntvangers.SelectedItem.ToString());
            //string destinationusername = listBoxOntvangers.SelectedItem.ToString();
            //        NaarServerSturen(sourceip + ";" + destinationip + ";" + filelocation + ";" + sourceusername + ";" + destinationusername);
            //    }
            //    else if (radioButtonEncrypteren.IsChecked == true)
            //    {
            //        if (File.Exists(@".\Boodschap.txt"))
            //        {
            //            File.Delete(@".\Boodschap.txt");
            //        }

            //        StreamWriter outputFile = new StreamWriter(@".\Boodschap.txt");
            //        outputFile.WriteLine(textBoxBoodschap.Text);
            //        outputFile.Close();
            //        outputFile.Dispose();

            //        string sourceip = GetIP(listBoxZenders.SelectedItem.ToString());
            //        string destinationip = GetIP(listBoxOntvangers.SelectedItem.ToString());
            //        string filelocation = System.IO.Path.GetFullPath(@".\Boodschap.txt");
            //        string sourceusername = listBoxZenders.SelectedItem.ToString();
            //        string destinationusername = listBoxOntvangers.SelectedItem.ToString();
            //string filelocation = System.IO.Path.GetFullPath(@".\Boodschap.txt");
            //string destinationusername = listBoxZenders.SelectedItem.ToString();
            string sourceip = GetIP(listBoxZenders.SelectedItem.ToString());
                  
            


            string textPath = System.IO.Path.GetFullPath("./CryptoSavedChatFile.txt");
            
            if (textBoxBoodschap.IsEnabled == true)
            {
                File.WriteAllText(textPath, textBoxBoodschap.Text);
                NaarServerSturen(sourceip +  ";" + textPath);
            }
            else if (textBoxBoodschap.IsEnabled==false)
            {
                NaarServerSturen(sourceip +";" + filepath );
            }        
            }

        public string GetIP(string naam)
        {
            StreamReader reader = new StreamReader(@".\Contacten\" + naam + @"\IP.txt");
            string ip = reader.ReadLine();
            reader.Close();
            reader.Dispose();
            return ip;
        }

        public void NaarServerSturen(string text)
        {
             TcpClient client = new TcpClient("127.0.0.1", 8888); //connecteren met de server
          
         
            stream = client.GetStream();
            buf = Encoding.UTF8.GetBytes(text + "\n");
            stream.Write(buf, 0, text.Length + 1);
            stream.Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            
        }

        public void ContactenUpdate()
        {
            foreach (string naam in Directory.GetDirectories(@".\Contacten"))
            {
                contacten.Add(naam.Remove(0, 12));
            }
            buttonCheck();
        }

        public void buttonCheck()
        {
            if (contacten.Count >= 1)
            {
                listBoxZenders.SelectedIndex = 0;
                //listBoxOntvangers.SelectedIndex = 1;
                buttonEncrypterenDecrypteren.IsEnabled = true;
            }
            else buttonEncrypterenDecrypteren.IsEnabled = false;

        }

        void ContactenUpdaten(object sender, EventArgs e)
        {
            contacten.Clear();
            ContactenUpdate();
            listBoxZenders.Items.Refresh();
            //listBoxOntvangers.Items.Refresh();
        }

        private void BoodschapOpenen_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            //openFileDialog1.Filter = "txt files (*.txt)|*.txt";
            openFileDialog1.Multiselect = false;
             
            if (openFileDialog1.ShowDialog() == true)
            {
                filepath = openFileDialog1.FileName;
                textBoxBoodschap.Text = filepath;
                textBoxBoodschap.IsEnabled = false;
            }
        }

        private void BoodschapOpslaan_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Text file (*.txt)|*.txt";
            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (saveFileDialog.ShowDialog() == true)
                File.WriteAllText(saveFileDialog.FileName, textBoxBoodschap.Text);
        }

        private void Afsluiten_Click(object sender, RoutedEventArgs e)
        {
            
            this.Close();
        }

        private void ContactToevoegen_Click(object sender, RoutedEventArgs e)
        {
            ContactenToevoegen nieuwContact = new ContactenToevoegen();
            nieuwContact.Show();
            nieuwContact.Closed += new EventHandler(ContactenUpdaten);
        }

        private void ContactVerwijderen_Click(object sender, RoutedEventArgs e)
        {
            if (contacten.Count > 0)
            {
                ContactVerwijderen wegContact = new ContactVerwijderen();
                wegContact.Show();
                wegContact.Closed += new EventHandler(ContactenUpdaten);
            }
            else MessageBox.Show("Maak eerst contacten aan");
        }

        private void MetroWindow_Closed(object sender, EventArgs e)
        {
            NaarServerSturen("EXIT");
            Application.Current.Shutdown();
            Environment.Exit(0);
        }
    }
}
