/// <summary>
        /// Write the news rows to the database as specified in <param name="rows">.
        /// </summary>
        /// <param name="rows">
        /// The new rows to write to the database.
        /// </param>
        public void WriteNewRows(List <Row> rows)
        {
            // A dictionary for the new values that need to be written to the index file.
            Dictionary <int, int> toAddToIndex = new Dictionary <int, int> ();

            DataBaseStream.Position = (RowCount * ROW_BYTE_SIZE) + HEADER_BYTE_SIZE;
            foreach (Row r in rows)
            {
                // Write the row with the next primary key.
                WriteRow(r, NextPrimaryKey, WriteType.NewRowWrite);
                // Bump up the row count.
                RowCount++;
                // Add the new index file data to dictionary.
                toAddToIndex.Add(NextPrimaryKey, RowCount);
                // Add the new index data to the dictionary that references the index file.
                Index.Add(NextPrimaryKey, RowCount);
                // Bump up the primary key.
                NextPrimaryKey++;
            }
            // Set the database stream position to the header and update the header with the next primary key and the new row count.
            DataBaseStream.Position = HEADER_INFO_NEXT_PRIMARY_KEY;
            DataBaseWriter.Write(NextPrimaryKey);
            DataBaseWriter.Write(RowCount);

            //Set the index stream to the end of the file and write the new index values to tthe index file.
            IndexStream.Position = (RowCount - toAddToIndex.Count) * INDEX_ROW_BYTE_SIZE;
            foreach (KeyValuePair <int, int> primaryKeyRowLocation in toAddToIndex)
            {
                WriteIndexRow(primaryKeyRowLocation.Key, primaryKeyRowLocation.Value, WriteType.IndexNewRowWrite);
            }
        }
 /// <summary>
 /// Write the header details for the database file if it has just been created.
 /// </summary>
 private void WriteNewFileHeader()
 {
     DataBaseStream.Position = 0;
     DataBaseWriter.Write("rubbishtable________".ToCharArray());
     DataBaseWriter.Write(0);
     DataBaseWriter.Write(0);
     DataBaseWriter.Write(0);
 }
 /// <summary>
 /// Write the rows as specified in <param name="rows"> as deleted.
 /// </summary>
 /// <param name="rows">
 /// The rows that are to be marked as deleted.
 /// </param>
 public void MarkRowsDeleted(List <Row> rows)
 {
     foreach (Row row in rows)
     {
         // Write the row's status to false (deleted) and bump up the number of rows deleted.
         WriteRow(row, row.PrimaryKey, WriteType.RowDelete);
         DeletedRowCount++;
     }
     // Update the header information with the new number of rows deleted.
     DataBaseStream.Position = HEADER_INFO_NUM_ROWS_DELETED;
     DataBaseWriter.Write(DeletedRowCount);
 }
        public void UploadData(string name, string author, string creationYear, string style, string epoch, string medium, int width,
                               int height, string plot, string cost)
        {
            Picture addedPic = new Picture()
            {
                Name         = name,
                CreationYear = int.Parse(creationYear),
                Style        = style,
                Epoch        = epoch,
                Medium       = medium,
                Width        = width,
                Height       = height,
                Plot         = plot,
                Cost         = long.Parse(cost)
            };

            DataBaseWriter.Write(addedPic);
        }
 /// <summary>
 /// Reorder the database and index rows with the dictionary of row - location in <param name="rowsToMove">.
 /// </summary>
 /// <param name="rowsToMove">
 /// Dictionary of row - location.
 /// </param>
 private void RearrangeRowsAndIndex(Dictionary <Row, int> rowsToMove)
 {
     // Set the new sizes of both the index and database file.
     DataBaseStream.SetLength(((RowCount - DeletedRowCount) * ROW_BYTE_SIZE) + HEADER_BYTE_SIZE);
     IndexStream.SetLength((RowCount - DeletedRowCount) * INDEX_ROW_BYTE_SIZE);
     // Write each row to it's new location. Write each index keyvalue pair of primary key location to the index file.
     // Update the object index.
     foreach (KeyValuePair <Row, int> data in rowsToMove)
     {
         Index [data.Key.PrimaryKey] = data.Value;
         WriteRow(data.Key, data.Key.PrimaryKey, WriteType.RowMove);
         WriteIndexRow(data.Key.PrimaryKey, data.Value, WriteType.IndexRowMove);
     }
     // Update the row count accordingly and reassign deleted rows the value of 0. We've just compacted!
     RowCount               -= DeletedRowCount;
     DeletedRowCount         = 0;
     DataBaseStream.Position = HEADER_INFO_NUM_ROWS;
     // Write that to the database header.
     DataBaseWriter.Write(RowCount);
     DataBaseWriter.Write(DeletedRowCount);
 }
 /// <summary>
 /// Write the row <param name="row"> with primary key <param name="primaryKey"> using the WriteType <param name="type">.
 /// </summary>
 /// <param name="row">
 /// Row to write.
 /// </param>
 /// <param name="primaryKey">
 /// Primary key of row to write.
 /// </param>
 /// <param name="type">
 /// The kind of row write to perform.
 /// </param>
 private void WriteRow(Row row, int primaryKey, WriteType type)
 {
     // If we're not udating an existing row. I.e. moving a row, writing a new row or deleting a row.
     if (type != WriteType.RowUpdate)
     {
         if (type != WriteType.NewRowWrite)
         {
             // Set the database stream to the location of the row
             DataBaseStream.Position = (Index [row.PrimaryKey] - 1) * ROW_BYTE_SIZE + HEADER_BYTE_SIZE;
         }
         // If the row is deleted, only write to it's status and leave the method.
         if (type == WriteType.RowDelete)
         {
             DataBaseWriter.Write(row.Status);
             return;
         }
         // Write the row's status and primary key.
         DataBaseWriter.Write(row.Status);
         DataBaseWriter.Write(primaryKey);
         // If it's a new row, write the new row's data and return from the method.
         if (type == WriteType.NewRowWrite)
         {
             DataBaseWriter.Write(row.NewTextData.PadRight(20, (char)0).ToCharArray());
             DataBaseWriter.Write(row.NewNumberData);
             return;
         }
     }
     // If the row is being updated, set the database stream to the rows data locaton
     if (type == WriteType.RowUpdate)
     {
         DataBaseStream.Position = (Index [row.PrimaryKey] - 1) * ROW_BYTE_SIZE + HEADER_BYTE_SIZE + ROW_DATA_LOCATION;
     }
     // Write the row data. This will happen for rows being moved or updated.
     DataBaseWriter.Write(row.TextData.PadRight(20, (char)0).ToCharArray());
     DataBaseWriter.Write(row.NumberData);
 }
Example #7
0
        static void Main(string[] args)
        {
            StreamWriter sw;
            // A string which I needed to use a lot, so I declared it here in order to use it more down
            string anyKey = "Press any Key to continue";

firstCheck:
            Console.Clear();
            Console.ResetColor();
            Console.WriteLine("Welcome to the Habit Tracker App");



            Console.WriteLine("Press 1 to create a new Account");
            Console.WriteLine("Pres 2 to Log in to the already existing account");
            string firstChoosing = Console.ReadLine();

            #region CreateUser
            while (true)
            {
                //If the User Decides to create a user
                if (UsernameServices.firstChoosingCheck(firstChoosing) == 1)
                {
                    User User1 = new User();
                    Console.WriteLine("Please Choose Your UserName");
                    string UserName = Console.ReadLine();

                    if (UsernameServices.CheckUserNameLength(UserName) == false && UsernameServices.firstNumCheck(UserName) == false)
                    {
                        while (true)
                        {
                            User1.UserName = UserName;
                            //Creating our Database
                            while (true)
                            {
                                try

                                {
                                    if (File.Exists($"{User1.UserName}.txt"))
                                    {
                                        Console.ForegroundColor = ConsoleColor.Red;
                                        throw new System.ArgumentException("That username already Exists please choose a different one");
                                    }
                                    sw = File.CreateText($"{User1.UserName}.txt");

                                    sw.WriteLine(User1.UserName);
                                    sw.Close();
                                    ConsoleMethods.GreenColor("UserName", anyKey);

                                    break;
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e.Message);

                                    Console.ReadLine();
                                    goto firstCheck;
                                }
                            }

                            Console.WriteLine("Please Enter your Name?");
                            string firstName = Console.ReadLine();
                            if (FirstName_Services.firstNameLengthCheck(firstName) == false)
                            {
                                if (FirstName_Services.IsDigit(firstName) == false)
                                {
                                    Console.Clear();
                                    User1.FirstName = firstName;


                                    ConsoleMethods.GreenColor("Name", anyKey);
                                    break;
                                }
                            }
                            if (FirstName_Services.firstNameLengthCheck(firstName) == true)
                            {
                                string nameError = "The Name must be longer than two characters";
                                if (File.Exists($"{User1.UserName}.txt"))
                                {
                                    File.Delete($"{User1.UserName}.txt");
                                    sw.Close();
                                }
                                ConsoleMethods.RedColor(nameError, anyKey);
                                continue;
                            }
                            if (FirstName_Services.IsDigit(firstName) == true)
                            {
                                string isNumDigit = "The name shouldn't include a number";
                                ConsoleMethods.RedColor(isNumDigit, anyKey);
                                if (File.Exists($"{User1.UserName}.txt"))
                                {
                                    File.Delete($"{User1.UserName}.txt");
                                    sw.Close();
                                }
                                continue;
                            }
                        }
                        while (true)
                        {
                            Console.WriteLine("Please Enter your Last Name?");
                            string lastName = Console.ReadLine();
                            if (FirstName_Services.firstNameLengthCheck(lastName) == false)
                            {
                                if (FirstName_Services.IsDigit(lastName) == false)
                                {
                                    Console.Clear();
                                    User1.LastName = lastName;
                                    ConsoleMethods.GreenColor("LastName", anyKey);
                                    break;
                                }
                            }
                            if (FirstName_Services.firstNameLengthCheck(lastName) == true)
                            {
                                string lastNameLenghtError = "The  Last Name must be longer than two characters";
                                ConsoleMethods.RedColor(lastNameLenghtError, anyKey);
                                if (File.Exists($"{User1.UserName}.txt"))
                                {
                                    File.Delete($"{User1.UserName}.txt");
                                    sw.Close();
                                }
                                continue;
                            }
                            if (FirstName_Services.IsDigit(lastName) == true)
                            {
                                string lastNameNumError = "The name shouldn't include a number";
                                ConsoleMethods.RedColor(lastNameNumError, anyKey);
                                if (File.Exists($"{User1.UserName}.txt"))
                                {
                                    File.Delete($"{User1.UserName}.txt");
                                    sw.Close();
                                }
                                continue;
                            }
                        }
                        while (true)
                        {
                            Console.WriteLine("Please Enter your Password");
                            string userPassword = Console.ReadLine();
                            if (Password_Services.PasswordLength(userPassword) == true && Password_Services.PasswordDigit(userPassword) == true)
                            {
                                Console.Clear();
                                User1.Password = userPassword;
                                ConsoleMethods.GreenColor("Password", anyKey);
                                break;
                            }
                            if (Password_Services.PasswordLength(userPassword) == false || Password_Services.PasswordDigit(userPassword) == false)
                            {
                                string passwordError = "Password Should be at least 6 characters long, and include one number";
                                ConsoleMethods.RedColor(passwordError, anyKey);
                                continue;
                            }
                        }

                        while (true)
                        {
                            Console.WriteLine("Please enter your Birthday in MM/DD/YYYY format");
                            string birthday = Console.ReadLine();


                            if (BirthdayServices.CalculAgeFormat(birthday) == false)
                            {
                                string birthDayError = "Please Follow the MM/DD/YYYY Format";
                                ConsoleMethods.RedColor(birthDayError, anyKey);
                                continue;
                            }
                            else
                            {
                                if (BirthdayServices.RealAge(birthday) < 5 || BirthdayServices.RealAge(birthday) > 120)
                                {
                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine($"Your Age is {BirthdayServices.RealAge(birthday)} and you are not allowed to use this app");

                                    Console.ResetColor();
                                    Environment.Exit(0);
                                }

                                else
                                {
                                    Console.Clear();
                                    DateTime userBirthday = DateTime.Parse(birthday);
                                    User1.DateOfBirth = userBirthday;
                                    ConsoleMethods.GreenColor("BirthDay", anyKey);
                                }



                                break;
                            }
                        }

                        Console.Clear();
                        Console.ForegroundColor = ConsoleColor.Green;
                        DataBaseWriter.DataBaseWriting(User1.UserName, User1.Password, User1.DateOfBirth, User1.FirstName, User1.LastName);
                        Console.WriteLine("The Username with these information has been created:");
                        Console.WriteLine($"Name: {User1.FirstName}");
                        Console.WriteLine($"Last Name: {User1.LastName}");
                        Console.WriteLine($"UserName:  {User1.UserName}");
                        Console.WriteLine($"Date of Birth:  {User1.DateOfBirth:MM/dd/yyyy}");
                        Console.ResetColor();
                        Console.WriteLine(anyKey);
                        Console.ReadLine();
                        goto firstCheck;
                    }


                    if (UsernameServices.CheckUserNameLength(UserName) == true || UsernameServices.firstNumCheck(UserName) == true)
                    {
                        string UsernameError = "The Username must be at least 6 characters Long and the First Character Shouldn't include a number.";
                        ConsoleMethods.RedColor(UsernameError, anyKey);
                        continue;
                    }
                }
                if (UsernameServices.firstChoosingCheck(firstChoosing) == 2)
                {
                    break;
                }
                if (UsernameServices.firstChoosingCheck(firstChoosing) == -1)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Please choose Either 1 or 2 ");
                    Console.ResetColor();
                    Console.WriteLine("Press Any Key to Continue");
                    Console.ReadLine();
                    Console.Clear();
                    Console.WriteLine("Press 1 to create a new Account");
                    Console.WriteLine("Pres 2 to Log in to the already existing account");
                    firstChoosing = Console.ReadLine();
                }
            }

            #endregion


GetUserAndPassword:
            Console.Clear();
            Console.WriteLine("Please Enter your Username");

            string getUser = Console.ReadLine();
            Console.WriteLine("Please Enter your Password?");
            string password = Console.ReadLine();

            while (true)
            {
                if (FindUserService.FindUserinDatabaseCheckPassword(getUser, password) == true)
                {
                    break;
                }

                if (FindUserService.FindUserinDatabaseCheckPassword(getUser, password) == false)
                {
                    goto GetUserAndPassword;
                }
            }
        }
        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            bool sellerIsSelected =
                (comboSeller.SelectedItem != null &&
                 !comboSeller.SelectedItem.ToString().Equals("Выберите покупателя")) ? true : false;

            bool tableIsFiled = moovingList.Count > 0 ? true : false;

            if (!sellerIsSelected)
            {
                MessageBox.Show("Выберите продавца из списка или создайте нового",
                                "Продавец не выбран", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            else if (!tableIsFiled)
            {
                ErrorMessages.MoovingTableIsEmpty();
            }

            else if (sellerIsSelected && tableIsFiled)
            {
                DataBaseReader dbReader = new DataBaseReader(this.sqlConnect);

                string sellerID;
                string sellerName = comboSeller.SelectedItem.ToString();

                string command = "SELECT [Buyers].[BuyerID] FROM [Buyers] " +
                                 "WHERE [Buyers].[BuyerName] = '" + sellerName + "'";

                sellerID = dbReader.GetString(command);

                string lastUpdate = Convert.ToDateTime(DateTime.Now).ToString("yyyyMMdd");

                List <Warehouses> listWarehouses = GetWarehousesList();

                for (int i = 0; i < moovingList.Count; i++)
                {
                    string goodsID;
                    string goodsName = moovingList[i].GoodsName;

                    command = "SELECT [Goods].[GoodsID] FROM [Goods] " +
                              "WHERE [Goods].[GoodsName] = '" + goodsName + "'";

                    goodsID = dbReader.GetString(command);

                    string goodsQuantity = moovingList[i].GoodsQuantity;
                    string goodsPrice    = moovingList[i].GoodsPrice;

                    //ID склада
                    string warehouseSourse = moovingList[i].WarehouseSourse;
                    int    index           = listWarehouses.FindIndex(
                        indx => string.Equals(indx.WarehouseName, warehouseSourse, StringComparison.CurrentCultureIgnoreCase));
                    string warehouseSourceID = listWarehouses[index].RowNumber;

                    command = "SELECT [GoodsInSale].[GoodsName] FROM [GoodsInSale] " +
                              "WHERE [GoodsInSale].[BuyerName] = '" + sellerID + "' " +
                              "AND [GoodsInSale].[GoodsName] = '" + goodsID + "'";
                    bool rowIsFinded = dbReader.SearchMatch(command);

                    DataBaseWriter dbWriter = new DataBaseWriter(this.sqlConnect);

                    if (rowIsFinded)
                    {
                        command = "SELECT [GoodsInSale].[GoodsQuantity] FROM [GoodsInSale] " +
                                  "WHERE [GoodsInSale].[BuyerName] = '" + sellerID + "' " +
                                  "AND [GoodsInSale].[GoodsName] = '" + goodsID + "'";
                        float oldQuantityFromSeller = float.Parse(dbReader.GetString(command));
                        float newQuantityFromSeller = oldQuantityFromSeller + float.Parse(goodsQuantity);

                        command = "UPDATE [GoodsInSale] " +
                                  "SET [GoodsQuantity] = '" + TextHandler.FloatToString(newQuantityFromSeller) + "', " +
                                  "[GoodsPrice] = '" + goodsPrice + "', " +
                                  "[LastUpdate] = '" + lastUpdate + "' " +
                                  "WHERE [GoodsInSale].[BuyerName] = '" + sellerID + "' " +
                                  "AND [GoodsInSale].[GoodsName] = '" + goodsID + "'";
                        dbWriter.WriteData(command);
                    }
                    else
                    {
                        //Продавец
                        dbWriter.InsDataRow.Add(new InsertDataToRow {
                            ColumnName = "BuyerName", Data = sellerID
                        });

                        //Товар
                        dbWriter.InsDataRow.Add(new InsertDataToRow {
                            ColumnName = "GoodsName", Data = goodsID
                        });

                        //Количество
                        dbWriter.InsDataRow.Add(new InsertDataToRow {
                            ColumnName = "GoodsQuantity", Data = goodsQuantity
                        });

                        //Цена
                        dbWriter.InsDataRow.Add(new InsertDataToRow {
                            ColumnName = "GoodsPrice", Data = goodsPrice
                        });

                        //Дата последней поставки
                        dbWriter.InsDataRow.Add(new InsertDataToRow {
                            ColumnName = "LastUpdate", Data = lastUpdate
                        });

                        command = "INSERT INTO [GoodsInSale] (BuyerName, GoodsName, GoodsQuantity, GoodsPrice, LastUpdate) " +
                                  "VALUES (@BuyerName, @GoodsName, @GoodsQuantity, @GoodsPrice, @LastUpdate)";

                        dbWriter.WriteData(command);
                    }

                    //Обновления количества товара на складе поставщике
                    command = "SELECT [GoodsInWarehouses].[GoodsBalance] FROM [GoodsInWarehouses] " +
                              "WHERE [GoodsInWarehouses].[WarehouseName] = '" + warehouseSourceID + "' " +
                              "AND [GoodsInWarehouses].[GoodsName] = '" + goodsID + "'";

                    float oldQuantity = float.Parse(dbReader.GetString(command));
                    float newQuantity = oldQuantity - float.Parse(goodsQuantity);

                    DataBaseWriter updateData = new DataBaseWriter(this.sqlConnect);
                    command = "UPDATE [GoodsInWarehouses]" +
                              "SET [GoodsBalance] = " + TextHandler.FloatToString(newQuantity) + " " +
                              "WHERE [GoodsName] = '" + goodsID + "'" +
                              "AND [WarehouseName] = '" + warehouseSourceID + "'";
                    updateData.WriteData(command);
                }

                GoodsMoved?.Invoke(sender, e);

                MessageBox.Show(string.Format("Перемещение {0} продавцу {1} успешно завершено",
                                              moovingList.Count > 1 ? "товаров" : "товара", sellerName), "Выполнено",
                                MessageBoxButton.OK, MessageBoxImage.Information);

                this.Close();
            }
        }