示例#1
0
        /// <summary>
        /// Создание пакетов файла и отправка пакета на сервер
        /// </summary>
        /// <param name="bytesSend">Количество отправленных байтов</param>
        private static void ContinueSendFile(ref int bytesSend)
        {
            if (fileSend != null && fileSend.fileByte.Length != 0)
            {
                uint lengthFile     = (uint)fileSend.fileByte.Length;
                int  nextPacketSize = (int)((lengthFile - bytesSend > FileSend.bufferSize) ? FileSend.bufferSize : lengthFile - bytesSend);

                if (bytesSend < lengthFile && fileSend != null && nextPacketSize != 0)
                {
                    MemoryStream packet = new MemoryStream(new byte[nextPacketSize + 8], 0, nextPacketSize + 8, true, true);

                    SendFile(520, 1002, bytesSend, packet, nextPacketSize);
                    bytesSend += nextPacketSize;
                }
                else
                {
                    fileSend = null;
                    SendMsgClient(16, 1003);
                }

                //if (fileSend != null)
                //    bytesSend += nextPacketSize;

                ///Отображение прогресса отправки
                if (YourProject.loadUIPB != null)
                {
                    double percent = ((double)bytesSend / lengthFile) * 100;
                    YourProject.SetValueProgressLoad((int)percent, false);
                }
            }
        }
示例#2
0
        /// <summary>
        /// Установка информации о проекте
        /// </summary>
        /// <param name="thisWindow">Текущее окно</param>
        /// <param name="nameProject">Имя проекта</param>
        /// <param name="datePub">Дата публикации</param>
        /// <param name="rating">Рейтинг</param>
        /// <param name="countVote">Количество голосов</param>
        /// <param name="note">Описание</param>
        /// <param name="hrefImage">Ссылка на картинку</param>
        /// <param name="viewApp">Категория проекта</param>
        public static void SetInfoForSettingsPanel(YourProject thisWindow, string nameProject, string datePub,
                                                   double rating, int countVote, string note, string hrefImage, int viewApp)
        {
            #region Анимация панели

            thisWindow.settingsPanel.BeginAnimation(MarginProperty,
                                                    StyleUIE.AnimationObject(thisWindow.settingsPanel,
                                                                             TimeSpan.FromSeconds(0.33),
                                                                             new Thickness(0, thisWindow.settingsPanel.Margin.Top, 0, 0)));

            #endregion

            string[] exp = nameProject.Split('.');

            thisWindow.nameProjTB.Text      = nameProject.Replace("." + exp[exp.Length - 1], string.Empty);
            thisWindow.nameProjTB.Tag       = nameProject;
            thisWindow.nameProjTB.MaxLength = 45 - (exp[exp.Length - 1].Length + 1);
            thisWindow.expasionText.Text    = "." + exp[exp.Length - 1];

            thisWindow.dateProjLB.Content      = $"Date : {datePub}";
            thisWindow.ratingProjLB.Content    = $"Rating : {rating}";
            thisWindow.countVoteProjLB.Content = $"Count Vote : {countVote}";

            if (!hrefImage.Equals(string.Empty) || hrefImage != null)
            {
                thisWindow.hrefImageTb.Text = hrefImage;
                try
                {
                    thisWindow.imageProj.Fill = new ImageBrush(new BitmapImage(new Uri(hrefImage, UriKind.Absolute)));
                }
                catch { }
            }

            thisWindow.noteTextBox.Document.Blocks.Clear();
            if (!note.Equals(string.Empty) || note != null)
            {
                thisWindow.noteTextBox.AppendText(note);
            }

            if (viewApp > 0)
            {
                thisWindow.comboBoxTypeProj.SelectedIndex = viewApp - 1;
            }

            #region Устанавливаем новый рейтинг у проекта
            double oldRating = (thisWindow.listViewProjects.SelectedItem as MyItemProject).ratingProject;

            if (rating != oldRating)
            {
                int        index     = thisWindow.listViewProjects.SelectedIndex;
                StackPanel panelStar = listPanelStars[index];

                DrawStarsForProject(panelStar, rating);
            }

            #endregion
        }
示例#3
0
        /// <summary>
        /// Установка панели с загрузкой файла
        /// </summary>
        /// <param name="thisWindow">Текущее окно</param>
        /// <param name="nameProject">Имя файла</param>
        /// <param name="isSend">Состояние отправки</param>
        public static void SetSettingsPanelLoad(YourProject thisWindow, string nameProject = "Error", bool isSend = true)
        {
            thisWindow.Dispatcher.Invoke(new ThreadStart(() =>
            {
                panelLoading = thisWindow.panelLoad;
                thisWindow.panelLoad.Visibility = Visibility.Visible;
                thisWindow.loadNameProj.Text    = nameProject;
                thisWindow.loadProgressPB.Value = 0;
                thisWindow.loadProgressTB.Text  = thisWindow.loadProgressPB.Value + "%";

                if (!isSend)
                {
                    thisWindow.nameLoadTB.Text = "Загрузка : ";
                }
                else
                {
                    thisWindow.nameLoadTB.Text = "Отправка : ";
                }

                nameProjectLoadUI = thisWindow.loadNameProj;
                loadUIPB          = thisWindow.loadProgressPB;
                loadUITB          = thisWindow.loadProgressTB;
            }));
        }
示例#4
0
        /// <summary>
        /// Создает панель для проекта
        /// </summary>
        /// <param name="project">Проект</param>
        /// <returns>Панель</returns>
        private static Grid CreatePanelProject(Project project)
        {
            Grid panel = new Grid
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top,
                Margin = new Thickness(10)
            };

            Rectangle rec = new Rectangle
            {
                Height = 58,
                Width  = 60,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top,
            };

            try { rec.Fill = new ImageBrush(new BitmapImage(new Uri(project.image, UriKind.Absolute))); }
            catch { rec.Fill = new ImageBrush(new BitmapImage(new Uri(" https://api.icons8.com/download/6f772b46170bd7987130f8a01dbfc2368b95877f/office/PNG/512/Very_Basic/open_folder-512.png", UriKind.Absolute))); }

            Label nameP = new Label
            {
                Content             = project.projectSettings.nameProject,
                Margin              = new Thickness(65, 0, 0, 0),
                Width               = 177,
                FontWeight          = FontWeights.Bold,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top
            };

            StackPanel rating = new StackPanel
            {
                Orientation         = Orientation.Horizontal,
                Margin              = new Thickness(65, 26, 0, 0),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top
            };

            //Рисуем звёзды
            for (int i = 0; i < 5; i++)
            {
                List <Point> points = new List <Point>();
                points.Add(new Point(1, 12));
                points.Add(new Point(6.4, 0));
                points.Add(new Point(11, 12));
                points.Add(new Point(0, 5));
                points.Add(new Point(13, 5));

                rating.Children.Add(new Polygon
                {
                    StrokeThickness = 1,
                    FillRule        = FillRule.Nonzero,
                    Points          = new PointCollection(points),
                    Fill            = Brushes.Gray
                });
            }
            YourProject.DrawStarsForProject(rating, project.projectSettings.ratingProject);

            TextBlock countVoteP = new TextBlock
            {
                Margin              = new Thickness(0, 63, 0, 0),
                TextWrapping        = TextWrapping.Wrap,
                Width               = 60,
                Text                = $"Кол-во голосов: {project.countVote}",
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top
            };

            StackPanel spKat = new StackPanel
            {
                Orientation         = Orientation.Horizontal,
                Margin              = new Thickness(65, 58, 0, 0),
                Width               = 179,
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top
            };

            spKat.Children.Add(new TextBlock {
                Text = "Категория : "
            });
            spKat.Children.Add(new TextBlock
            {
                Text       = project.viewApplication,
                FontWeight = FontWeights.Bold,
                Margin     = new Thickness(5, 0, 0, 0)
            });

            ScrollViewer noteP = new ScrollViewer
            {
                Margin = new Thickness(65, 79, 0, 0),
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top
            };

            noteP.Content = new TextBlock
            {
                Text         = project.note,
                TextWrapping = TextWrapping.Wrap,
                Width        = 163,
                MinHeight    = 50
            };

            StackPanel spRatingPanel = CreatePanelRating(thisWindow);

            Button buttLoad = new Button
            {
                BorderThickness     = new Thickness(1),
                Width               = 32,
                Height              = 25,
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment   = VerticalAlignment.Bottom,
                Margin              = new Thickness(0, 0, 10, 5),
                Background          = new ImageBrush(new BitmapImage(new Uri("https://image.flaticon.com/icons/png/512/12/12196.png", UriKind.Absolute)))
            };

            panel.Children.Add(rec);
            panel.Children.Add(nameP);
            panel.Children.Add(rating);
            panel.Children.Add(countVoteP);
            panel.Children.Add(spKat);
            panel.Children.Add(noteP);
            panel.Children.Add(spRatingPanel);
            panel.Children.Add(buttLoad);
            return(panel);
        }
示例#5
0
        }                                                  // Файл, который скачивается из сервера;

        /// <summary>
        /// Получение ответа от сервера
        /// </summary>
        /// <param name="soketClient">Сокет клиента</param>
        private static void GettingAnswerServer(object soketClient)
        {
            Socket soket = (Socket)soketClient;

            MemoryStream ms     = new MemoryStream(new byte[2048], 0, 2048, true, true);
            BinaryReader reader = new BinaryReader(ms);

            try
            {
                while (true)
                {
                    // Если файл пользователь отправлял файл, продолжить отправку файла в другом окне;
                    if (fileSend != null)
                    {
                        ContinueSendFile(ref fileSend.bytesSend);
                    }

                    soket.Receive(ms.GetBuffer());
                    ms.Position = 0;

                    int idOperation = reader.ReadInt32();
                    switch (idOperation)
                    {
                    case 1:
                        #region Проверка данных на валидность (Connect 1)

                        switch (reader.ReadBoolean())
                        {
                        case true:
                            Authorization.GoToPersonalArea();
                            break;

                        case false:
                            Authorization.thisWindow.Dispatcher.BeginInvoke(new ThreadStart(() => {
                                Authorization.thisWindow.signIn.IsEnabled = true;
                                MessageBox.Show("Неверный логин или пароль!");
                            }));
                            break;
                        }
                        #endregion
                        break;

                    case 2:
                        #region Проверка на повторяющийся логин (CheckDataUser 2)

                        switch (reader.ReadBoolean())
                        {
                        case true:
                            MessageBox.Show("Регистрация прошла успешно!");
                            Authorization.CreateNewPerson();
                            break;

                        case false:
                            MessageBox.Show("Такой логин\\email уже существует!");
                            break;
                        }
                        #endregion
                        break;

                    case 3:
                        #region Получение ответа от сервера насчёт данных о данном пользователе (CheckFullInfoOfPerson 3)

                        if (reader.ReadBoolean())
                        {
                            Person.thisUser.name         = reader.ReadString();
                            Person.thisUser.lastname     = reader.ReadString();
                            Person.thisUser.level        = reader.ReadInt32();
                            Person.thisUser.likes        = reader.ReadInt32();
                            Person.thisUser.image        = reader.ReadString();
                            Person.thisUser.email        = reader.ReadString();
                            Person.thisUser.countProject = Int32.Parse(reader.ReadString());
                            Person.thisUser.note         = reader.ReadString();
                            Person.thisUser.countSub     = Int32.Parse(reader.ReadString());

                            PersonalArea.SetPersonalInfo();
                        }
                        else
                        {
                            Profile.profileUser.name         = reader.ReadString();
                            Profile.profileUser.lastname     = reader.ReadString();
                            Profile.profileUser.level        = reader.ReadInt32();
                            Profile.profileUser.likes        = reader.ReadInt32();
                            Profile.profileUser.image        = reader.ReadString();
                            Profile.profileUser.email        = reader.ReadString();
                            Profile.profileUser.countProject = Int32.Parse(reader.ReadString());
                            Profile.profileUser.note         = reader.ReadString();
                            Profile.profileUser.countSub     = Int32.Parse(reader.ReadString());

                            Profile.SetPanels(Profile.thisWindow, Profile.profileUser);
                        }
                        #endregion
                        break;

                    case 4:
                        #region Проверка на наличие введенной почты в базе (CheckUnique 4)
                        SendMailPass.thisWindow.ShowPanelCode(!reader.ReadBoolean());
                        #endregion
                        break;

                    case 5:
                        #region Получение в изменении количества лайков на профиле пользователя от сервера

                        MessageBox.Show("321");

                        #endregion
                        break;

                    case 6:
                        #region Получение ответ от сервера по поводу отправки кода восстановления;
                        SendMailPass.codeU = reader.ReadInt32();
                        #endregion
                        break;

                    case 7:
                        #region Получение списка с категориями проекта
                        YourProject.thisWindow.Dispatcher.BeginInvoke(new ThreadStart(() => {
                            foreach (string item in reader.ReadString().Split('#').ToList())
                            {
                                YourProject.thisWindow.comboBoxTypeProj.Items.Add(item);
                            }

                            YourProject.thisWindow.comboBoxTypeProj.Items.RemoveAt(YourProject.thisWindow.comboBoxTypeProj.Items.Count - 1);
                            SendMsgClient(256, 9, Person.thisUser.login, (YourProject.thisWindow.listViewProjects.SelectedValue as Project.MyItemProject).nameProject);
                        }));
                        #endregion
                        break;

                    case 8:
                        #region Получение информации о проекте (YouProject)
                        YourProject.thisWindow.Dispatcher.BeginInvoke(new ThreadStart(() =>
                        {
                            string nameProj = reader.ReadString();
                            string dateU    = reader.ReadString();
                            double ratingU  = double.Parse(reader.ReadString().Replace('.', ','));
                            int countVoteU  = Int32.Parse(reader.ReadString());
                            string noteU    = reader.ReadString();
                            string imageU   = reader.ReadString();
                            YourProject.SetInfoForSettingsPanel(YourProject.thisWindow, nameProj, dateU,
                                                                ratingU, countVoteU, noteU, imageU, Int32.Parse(reader.ReadString()));
                            //YourProject.SetInfoForSettingsPanel(YourProject.thisWindow, reader.ReadString(), reader.ReadString(),
                            //        double.Parse(reader.ReadString().Replace('.', ',')), Int32.Parse(reader.ReadString()),
                            //        reader.ReadString(), reader.ReadString(), Int32.Parse(reader.ReadString()));

                            YourProject.thisWindow.settingsPanel.Visibility = Visibility.Visible;
                        }));
                        #endregion
                        break;

                        #region  абота с файлами (1000 - 2000)

                    case 1001:
                        #region Отправка файла серверу

                        if (fileSend != null)
                        {
                            ContinueSendFile(ref fileSend.bytesSend);
                        }

                        #endregion
                        break;

                    case 1002:
                        #region  Получение списка проектов сохраненные на сервере;

                        bool isThisUser = reader.ReadBoolean();

                        int    idProject       = reader.ReadInt32();
                        string name            = reader.ReadString();
                        int    countVote       = reader.ReadInt32();
                        double rating          = reader.ReadDouble();
                        string date            = reader.ReadString();
                        string note            = reader.ReadString();
                        string image           = reader.ReadString();
                        string viewApplication = reader.ReadString();

                        if (isThisUser)
                        {
                            Person.thisUser.listProject.Add(new Project(idProject, name, countVote, rating, date, viewApplication, note, image));
                        }
                        else
                        {
                            Profile.profileUser.listProject.Add(new Project(idProject, name, countVote, rating, date, viewApplication, note, image));
                        }
                        #endregion
                        break;

                    case 1003:
                        #region Получение свойств файла который будет отправлятся от сервера;
                        fileReceiving = new FileSend(reader.ReadInt32(), reader.ReadString());
                        SendMsgClient(16, 1007);

                        YourProject.IsEnabledForm(false);
                        YourProject.SetSettingsPanelLoad(YourProject.thisWindow, fileReceiving.nameFile, false);
                        #endregion
                        break;

                    case 1004:
                        #region Получение пакетов файла;

                        int    countRecByte = reader.ReadInt32();
                        byte[] byteFile     = reader.ReadBytes(countRecByte);

                        ReceivedFile(fileReceiving, byteFile, countRecByte);
                        fileReceiving.bytesSend += countRecByte;

                        ///Отображение прогресса отправки
                        if (YourProject.loadUIPB != null)
                        {
                            double percent = ((double)fileReceiving.bytesSend / fileReceiving.fileByte.Length) * 100;
                            YourProject.SetValueProgressLoad((int)percent, true);
                        }
                        #endregion
                        break;

                    case 1005:
                        #region Создание файла по полученным байтам;
                        string nameFile = $"Project File\\{fileReceiving.nameFile}";
                        File.WriteAllBytes(nameFile, fileReceiving.fileByte);
                        fileReceiving = null;
                        #endregion
                        break;

                    case 1006:
                        #region Добавление проекта в лист;
                        YourProject.thisWindow.Dispatcher.BeginInvoke(new ThreadStart(() =>
                        {
                            YourProject.AddProjectToList(Int32.Parse(reader.ReadString()));
                        }));
                        #endregion
                        break;

                    case 1007:
                        #region Изменение имени у проекта
                        YourProject.thisWindow.Dispatcher.BeginInvoke(new ThreadStart(() =>
                        {
                            YourProject.RenameProject(reader.ReadString());
                        }));
                        #endregion
                        break;
                        #endregion

                        #region Новостная лента(2000-3000)
                    case 2000:
                        #region Поиск людей по введеной строке
                        string loginUser = reader.ReadString();

                        if (!loginUser.Equals("###ThisNull###"))
                        {
                            string imageU       = reader.ReadString();
                            int    level        = Int32.Parse(reader.ReadString());
                            int    countProject = Int32.Parse(reader.ReadString());

                            FeedPublic.listSearchPeople.Add(new Person(loginUser, imageU, level, countProject));
                        }
                        else
                        {
                            FeedPublic.thisWindow.Dispatcher.BeginInvoke(new ThreadStart(() => {
                                FeedPublic.SetFindsPeople(FeedPublic.listSearchPeople);
                            }));
                        }
                        #endregion
                        break;

                    case 2001:
                        #region Получение списока проектов с лучшим рейтингом;
                        loginUser = reader.ReadString();

                        if (!loginUser.Equals("###ThisNull###"))
                        {
                            string nameProj = reader.ReadString();
                            string imageU   = reader.ReadString();
                            double ratingU  = double.Parse(reader.ReadString().Replace('.', ','));
                            string noteU    = reader.ReadString();

                            FeedPublic.listTopProject.Add(new Person(loginUser, new Project(new MyItemProject(nameProj, ratingU), imageU, noteU)));
                        }
                        else
                        {
                            FeedPublic.thisWindow.Dispatcher.BeginInvoke(new ThreadStart(() => {
                                FeedPublic.SetTopProject(FeedPublic.listTopProject);
                                SendMsgClient(128, 2002, Person.thisUser.login);
                            }));
                        }
                        #endregion
                        break;

                    case 2002:
                        #region Получение рандомных людей;
                        loginUser = reader.ReadString();

                        if (!loginUser.Equals("###ThisNull###"))
                        {
                            int    level  = Int32.Parse(reader.ReadString());
                            string imageU = reader.ReadString();

                            FeedPublic.listInterestingPeople.Add(new Person(loginUser, imageU, level, -1));
                        }
                        else
                        {
                            FeedPublic.thisWindow.Dispatcher.BeginInvoke(new ThreadStart(() => {
                                FeedPublic.PanelRandomPeople(FeedPublic.listInterestingPeople);
                            }));
                        }
                        #endregion
                        break;
                        #endregion

                    case 2003:
                        #region Провка на подпику у профиля другого пользователя;
                        Profile.thisWindow.Dispatcher.BeginInvoke(new ThreadStart(() =>
                        {
                            int a = reader.ReadInt32();
                            Profile.IsSubscribe(Profile.thisWindow.subButton, (a == 1) ? false : true);
                        }));
                        #endregion
                        break;
                    }

                    if (!soket.Connected)
                    {
                        break;
                    }
                }
            }
            //catch(Exception ex)
            //{
            //    MessageBox.Show("GettingAnswerServer  :  " + ex.Message);

            //    try
            //    {
            //        Application.Current.Dispatcher.Invoke(new ThreadStart(()=>
            //        {
            //            Application.Current.Shutdown();

            //        }));
            //    }
            //    catch { }
            //}
            finally
            {
                Thread.CurrentThread.Abort();
                soket.Close();
            }
        }