Exemple #1
0
        private async void btnLogin_Click(object sender, EventArgs e)
        {
            await MyLogger.Log("log in clicked, checking user and password on DB ");

            if (txtUserName.Text.Trim() == "" && txtPassword.Text.Trim() == "")
            {
                MessageBox.Show("Empty Fields");
            }
            else
            {
                if (myConnection.checkAdmin(txtUserName.Text, txtPassword.Text) > 0)
                {
                    MyLogger.Log($"the user is authenticated ith the {txtUserName.Text} and passord {txtPassword.Text}");
                    await MyLogger.Log("logged in as admin - admin flag in query");

                    button1.Enabled         = true;
                    newUserPwdLbl.Visible   = true;
                    NewUserNameLbl.Visible  = true;
                    NewUserTxt.Visible      = true;
                    NewUserPwdTxt.Visible   = true;
                    NewUserPathLbl.Visible  = true;
                    NewUserPathTxt.Visible  = true;
                    AddNewUser.Visible      = true;
                    DeleteUserBtn.Visible   = true;
                    UpdatePwdBtn.Visible    = true;
                    SendToServerTxt.Visible = true;
                    SendToClientBtn.Visible = true;
                }
                else
                {
                    await MyLogger.Log("wrong username and password for admin ");
                }
            }
        }
        public async void CreateTable()
        {
            await MyLogger.Log("creating table if not exist");

            // CREATE NEW TABLE
            query = @"CREATE TABLE IF NOT EXISTS
                             [users] (
                             [id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                             [name] TEXT,
                             [password] TEXT,
                             [pathToDir] TEXT)";
            try
            {
                using (SQLiteCommand myCommand = new SQLiteCommand(query, MyConnection()))
                {
                    OpenConnection();
                    myCommand.CommandText = query;
                    myCommand.ExecuteNonQuery();
                    CloseConnection();
                }
                MyLogger.Log("Table Created ");
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
        }
        public async void updatePwd(string userName, string newPass)// update user password
        {
            await MyLogger.Log($"updating PWD by username : {userName} and PWD {newPass}");

            query = "UPDATE users SET password = @password WHERE name = @name";
            try
            {
                using (SQLiteCommand myCommand = new SQLiteCommand(query, MyConnection()))
                {
                    OpenConnection();
                    myCommand.Parameters.AddWithValue("@password", newPass);
                    myCommand.Parameters.AddWithValue("@name", userName);
                    try
                    {
                        returnValue = myCommand.ExecuteNonQuery();
                    }
                    catch (SQLiteException exc)
                    {
                        SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                    }

                    MyLogger.Log("pwd updated");
                    CloseConnection();
                }
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
        }
        public SQLiteConnection MyConnection()
        {
            if (!File.Exists("./database.sqlite3"))
            {
                try
                {
                    MyLogger.Log("trying to create DB ");
                    SQLiteConnection.CreateFile("database.sqlite3"); //creating the DB
                    MyLogger.Log("trying to create table ");
                    CreateTable();                                   // creating the table ''
                }
                catch (SQLiteException exc)
                {
                    SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                    MyLogger.Log(exc.ToString());
                }

                MyLogger.Log("DB created ! ");
            }

            try
            {
                MyLogger.Log("trying connect to DB ");
                myConnection = new SQLiteConnection("Data Source=database.sqlite3");
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
            return(myConnection);
        }
Exemple #5
0
        private void StopServerBtn_Click(object sender, EventArgs e)
        {
            serverConfig.StopServer();
            MyLogger.Log("server stopped by request from user");

            ActiveForm.Close();
        }
        public void InsertNewUsers(string name, string password, string path)
        {
            MyLogger.Log($"inserting new user name : {name} password : {password} path : {path}");
            // INSERT INTO DATABASE
            query = "INSERT INTO users (name, password, pathToDir) VALUES (@name, @password, @path)";

            try
            {
                using (SQLiteCommand myCommand = new SQLiteCommand(query, MyConnection()))
                {
                    OpenConnection();
                    myCommand.Parameters.AddWithValue("@name", name);
                    myCommand.Parameters.AddWithValue("@password", password);
                    myCommand.Parameters.AddWithValue("@path", path);
                    returnValue = myCommand.ExecuteNonQuery();
                    CloseConnection();
                    Console.WriteLine("Rows Added : {0}", returnValue);
                }
                MyLogger.Log($"Inserting of {name} and {password} and {path} is completed");
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
        }
Exemple #7
0
 private void RemoveClient(TcpClient paramClient) // remove client if couple of them are connected - testing for multiple connections
 {
     if (mClients.Contains(paramClient))
     {
         mClients.Remove(paramClient);
         MyLogger.Log(String.Format("Client removed, count: {0}", mClients.Count));
     }
 }
 public void OpenConnection()
 {
     MyLogger.Log("checking if connection open");
     if (myConnection.State != ConnectionState.Open)
     {
         MyLogger.Log("opening connection");
         myConnection.Open();
     }
 }
Exemple #9
0
        public Form1()
        {
            InitializeComponent();
            MyLogger m = new MyLogger();

            MyLogger.Log("initialize FORM1");
            serverConfig = new ServerConfig();
            myConnection = new DbConnection();
        }
 public void CloseConnection()
 {
     MyLogger.Log("checking if connection closed");
     if (myConnection.State != ConnectionState.Closed)
     {
         MyLogger.Log("closing connection");
         myConnection.Close();
     }
 }
Exemple #11
0
 private void listAllStoredFiles()
 {
     Debug.WriteLine("trying to send list back to client");
     MyLogger.Log("sending data back to client");
     string[] fileArray = Directory.GetFiles(pathToDirectory);
     foreach (var item in fileArray)
     {
         Array.Clear(buffMessage, 0, buffMessage.Length);
         sendToClient(item.ToString(), returnedByAccept);
     }
 }
Exemple #12
0
        private async Task delteFileAsync(string fileName)
        {
            Debug.WriteLine("comand=delete");
            MyLogger.Log("comand=delete");
            var      filePath = pathToDirectory + @"\" + fileName;
            FileInfo fi       = new FileInfo(filePath);
            await fi.DeleteAsync();

            MyLogger.Log($"File {fileName} deleted");
            sendToClient($"file {fileName} deleted", returnedByAccept);
        }
Exemple #13
0
 public void sendToClient(string message, TcpClient c) // send string to client
 {
     try
     {
         buffMessage = Encoding.ASCII.GetBytes(message + "\n");
         c.GetStream().WriteAsync(buffMessage, 0, buffMessage.Length);
         Array.Clear(buffMessage, 0, buffMessage.Length);
     }
     catch (Exception excp)
     {
         MyLogger.Log(excp.ToString());
     }
 }
Exemple #14
0
 private bool checkAuthorization(string username, string passwordFromClient)
 {
     //check if use authorozied
     pathToDirectory = myConnection.findUserForAuth(username, passwordFromClient);
     if (pathToDirectory.Length >= 1)
     {
         MyLogger.Log($"user {username} with password {password} is authorozied ");
         return(isAuthorized = true);
     }
     MyLogger.Log("the user have no rights to access the server");
     StopServer();
     return(false);
 }
Exemple #15
0
        public async void StartListeningForIncomingConnection(IPAddress ip = null, int port = 23000)
        {
            await MyLogger.Log("started listening to connections ");

            if (ip == null)
            {
                ip = IPAddress.Any;
            }

            if (port <= 0)
            {
                port = 23000;
            }
            ipAddr  = ip;
            portNum = port;
            MyLogger.Log(string.Format("IP Address: {0} - Port: {1}", ipAddr.ToString(), portNum));

            listener = new TcpListener(ipAddr, portNum);

            try
            {
                MyLogger.Log("starting server LIstener");
                listener.Start();
                running = true;

                while (running)
                {
                    MyLogger.Log("accepting  connections");
                    returnedByAccept = await listener.AcceptTcpClientAsync();

                    MyLogger.Log($"connection accepted from {returnedByAccept}");
                    mClients.Add(returnedByAccept);

                    MyLogger.Log(string.Format($"Client connected successfully, count: {mClients.Count} - {returnedByAccept.Client.RemoteEndPoint}"));

                    TakeCareOfTCPClient(returnedByAccept);
                }
            }
            catch (Exception excp)
            {
                MyLogger.Log(excp.ToString());
            }
        }
Exemple #16
0
        public async void SendToAll(string leMessage)// send data to couple of clients - test - barely works
        {
            if (string.IsNullOrEmpty(leMessage))
            {
                return;
            }
            try
            {
                buffMessage = Encoding.ASCII.GetBytes(leMessage);

                foreach (TcpClient c in mClients)
                {
                    c.GetStream().WriteAsync(buffMessage, 0, buffMessage.Length);
                }
            }
            catch (Exception excp)
            {
                MyLogger.Log(excp.ToString());
            }
        }
        public async void DeleteByUserName(string userName) // delete user by provided user name
        {
            await MyLogger.Log("Deleting from table by username");

            query = "DELETE FROM users Where name = @name";
            try
            {
                using (SQLiteCommand myCommand = new SQLiteCommand(query, MyConnection()))
                {
                    OpenConnection();
                    myCommand.Parameters.AddWithValue("@name", userName);
                    myCommand.ExecuteNonQuery();
                    Debug.WriteLine("user deleted");
                    CloseConnection();
                }
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
        }
Exemple #18
0
        public void StopServer()
        {
            try
            {
                MyLogger.Log("Stopping server");
                if (listener != null)
                {
                    listener.Stop();
                }

                foreach (TcpClient c in mClients)
                {
                    MyLogger.Log($"Closing connection to : {c.Client.RemoteEndPoint.ToString()}");
                    c.Close();
                }

                mClients.Clear();
            }
            catch (Exception excp)
            {
                MyLogger.Log(excp.ToString());
            }
        }
        public int checkAdmin(string name, string password) // check if use is admin
        {
            int    result = 0;
            string query  = "select count(*) from users where name =@name and password =@password and isAdmin='yes'";

            try
            {
                using (SQLiteCommand myCommand = new SQLiteCommand(query, MyConnection()))
                {
                    OpenConnection();
                    myCommand.Parameters.AddWithValue("@name", name);
                    myCommand.Parameters.AddWithValue("@password", password);
                    result = Convert.ToInt32(myCommand.ExecuteScalar());
                    return(result);
                }
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
            return(result);
        }
        public string findUserForAuth(string username, string password)//check if the user exissts  and retrive his path to directory
        {
            MyLogger.Log($"qeuring by user name and password for authorization");
            string result = null;

            query = "SELECT pathToDir FROM users WHERE name = @name and password=@password";
            try
            {
                using (SQLiteCommand myCommand = new SQLiteCommand(query, MyConnection()))
                {
                    OpenConnection();
                    myCommand.Parameters.AddWithValue("@name", username);
                    myCommand.Parameters.AddWithValue("@password", password);
                    result = myCommand.ExecuteScalar().ToString();
                    return(result);
                }
            }
            catch (SQLiteException exc)
            {
                SQLiteErrorCode sqliteError = (SQLiteErrorCode)exc.ErrorCode;
                MyLogger.Log(exc.ToString());
            }
            return(result);
        }
Exemple #21
0
 private async void AddNewUser_Click(object sender, EventArgs e)
 {
     myConnection.InsertNewUsers(NewUserTxt.Text, NewUserPwdTxt.Text, NewUserPathTxt.Text);
     await MyLogger.Log($"new user added with those params name : {NewUserTxt.Text} and password : {NewUserPwdTxt.Text} and filepath:  {NewUserPathTxt.Text}");
 }
Exemple #22
0
 private async void SendToClientBtn_Click(object sender, EventArgs e)
 {
     serverConfig.SendToAll(SendToServerTxt.Text);
     await MyLogger.Log(@"Sent the data  : {SendToServerTxt.Text}");
 }
Exemple #23
0
 private void button1_Click(object sender, EventArgs e)
 {
     serverConfig.StartListeningForIncomingConnection();
     MyLogger.Log("server started listening");
 }
Exemple #24
0
        private async void TakeCareOfTCPClient(TcpClient paramClient)
        {
            reader = null;
            try
            {
                MyLogger.Log("Preparing to read and write Data");
                stream = paramClient.GetStream();
                reader = new StreamReader(stream);

                while (running)
                {
                    sendToClient("provide UserName", paramClient);


                    Debug.WriteLine("*** Ready to read ");
                    MyLogger.Log("ready to read data");


                    size = await stream.ReadAsync(buffMessage, 0, buffMessage.Length); //start reading data and get the size

                    username = Encoding.ASCII.GetString(buffMessage, 0, size);         //decode the data in the buffer to a string
                    MyLogger.Log($"username provided is {username}");


                    Array.Clear(buffMessage, 0, buffMessage.Length);
                    sendToClient("Provide Password", paramClient);


                    size = await stream.ReadAsync(buffMessage, 0, buffMessage.Length); //start reading data and get the size

                    password = Encoding.ASCII.GetString(buffMessage, 0, size);         //decode the data in the buffer to a string
                    MyLogger.Log($"password provided is {password}");


                    if (size == 0)
                    {
                        MyLogger.Log("data to read  is null");
                        RemoveClient(paramClient);

                        Debug.WriteLine("Socket disconnected");
                        MyLogger.Log("Socket disconnected");
                        break;
                    }

                    checkAuthorization(username, password);
                    // if the user is authorozied, startlistening to commands.  "user inside the server"
                    if (isAuthorized == true)
                    {
                        Array.Clear(buffMessage, 0, buffMessage.Length);

                        sendToClient("your options are : '1 for list'  ' 2 for delete'  '3 for upload'  '4 for download'", paramClient);

                        MyLogger.Log($"the path to directory is {pathToDirectory} ");
                        Debug.WriteLine($"the path to directory is {pathToDirectory}");

                        size = await stream.ReadAsync(buffMessage, 0, buffMessage.Length);//start reading data and get the size

                        string   getvalue  = Encoding.ASCII.GetString(buffMessage, 0, size);
                        commands comandNum = (commands)int.Parse(getvalue);// cust the comand integer to enum

                        switch (comandNum)
                        {
                        case commands.list:
                            listAllStoredFiles();
                            break;

                        case commands.delete:
                            sendToClient("provide file name", returnedByAccept);
                            size = await stream.ReadAsync(buffMessage, 0, buffMessage.Length); //start reading data and get the size

                            fileName = Encoding.ASCII.GetString(buffMessage, 0, size);         //decode the data in the buffer to a string
                            await delteFileAsync(fileName);

                            break;

                        case commands.download:
                            break;

                        case commands.upload:

                            break;

                        default:
                            break;
                        }
                    }
                    //clear the buffer
                    Array.Clear(buffMessage, 0, buffMessage.Length);
                }
            }
            catch (Exception excp)
            {
                MyLogger.Log($"will remove client- error accured {paramClient}");
                RemoveClient(paramClient);
                MyLogger.Log(excp.ToString());
            }
        }
Exemple #25
0
 private async void DeleteUserBtn_Click(object sender, EventArgs e)
 {
     myConnection.DeleteByUserName(NewUserTxt.Text);
     await MyLogger.Log($"User with this UserName is delted : {NewUserTxt.Text}");
 }
Exemple #26
0
 private async void UpdatePwdBtn_Click(object sender, EventArgs e)
 {
     myConnection.updatePwd(NewUserTxt.Text, NewUserPwdTxt.Text);
     await MyLogger.Log($"User with those Params Updated {NewUserTxt.Text} and {NewUserPwdTxt.Text} ");
 }