public void Show()
        {
            var authenticationData = new UserAuthenticationData();

            Console.WriteLine("Введите почтовый адрес:");
            authenticationData.Email = Console.ReadLine();

            Console.WriteLine("Введите пароль:");
            authenticationData.Password = Console.ReadLine();

            try
            {
                var user = this.userService.Authenticate(authenticationData);

                SuccessMessage.Show("Вы успешно вошли в социальную сеть!");
                SuccessMessage.Show("Добро пожаловать " + user.FirstName);

                Program.userMenuView.Show(user);
            }

            catch (WrongPasswordException)
            {
                AlertMessage.Show("Пароль не корректный!");
            }

            catch (UserNotFoundException)
            {
                AlertMessage.Show("Пользователь не найден!");
            }
        }
Exemple #2
0
        /// <summary>
        /// Invokes the current action based on the provided message.
        /// </summary>
        /// <param name="message">The message upon which the action acts.</param>
        public void Invoke(ICommunicationMessage message)
        {
            var msg = message as DataDownloadRequestMessage;

            if (msg == null)
            {
                Debug.Assert(false, "The message is of the incorrect type.");
                return;
            }

            if (!m_Uploads.HasRegistration(msg.Token))
            {
                m_Diagnostics.Log(
                    LevelToLog.Warn,
                    CommunicationConstants.DefaultLogTextPrefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "No file was registered for uploading with token {0}",
                        msg.Token));

                SendMessage(msg, new FailureMessage(m_Layer.Id, msg.Id));
                return;
            }

            var filePath    = m_Uploads.Deregister(msg.Token);
            var tokenSource = new CancellationTokenSource();

            m_Diagnostics.Log(
                LevelToLog.Debug,
                CommunicationConstants.DefaultLogTextPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    "Transferring file: {0}",
                    filePath));
            var task = m_Layer.UploadData(msg.Sender, filePath, tokenSource.Token, m_Scheduler);

            ICommunicationMessage returnMsg;

            try
            {
                task.Wait();
                returnMsg = new SuccessMessage(m_Layer.Id, msg.Id);
            }
            catch (AggregateException e)
            {
                m_Diagnostics.Log(
                    LevelToLog.Error,
                    CommunicationConstants.DefaultLogTextPrefix,
                    string.Format(
                        CultureInfo.InvariantCulture,
                        "An error occurred during the transfer of the file {0}. Exception was: {1}",
                        filePath,
                        e));

                returnMsg = new FailureMessage(m_Layer.Id, msg.Id);
                m_Uploads.Reregister(msg.Token, filePath);
            }

            SendMessage(msg, returnMsg);
        }
Exemple #3
0
        public void Show(User user)
        {
            var messageSendingData = new MessageSendingData();

            Console.WriteLine("Введите почтовый адрес получателя: ");
            messageSendingData.RecipientEmail = Console.ReadLine();

            Console.WriteLine("Введите сообщение (не более 5000 символов)");
            messageSendingData.Content = Console.ReadLine();

            messageSendingData.SenderId = user.Id;

            try
            {
                messageService.SendMessage(messageSendingData);
                SuccessMessage.Show("Сообщение успешно отправлено!");
            }
            catch (UserNotFoundException)
            {
                AlertMessage.Show("Пользователь не найден!");
            }
            catch (ArgumentNullException)
            {
                AlertMessage.Show("Введите корректное значение!");
            }
            catch (Exception)
            {
                AlertMessage.Show("Произошла ошибка при отправке сообщения!");
            }
        }
Exemple #4
0
        public void ForwardResponse()
        {
            var store = new Mock <IStoreInformationAboutEndpoints>();
            {
                store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny <EndpointId>()))
                .Returns(false);
            }

            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
            var handler           = new MessageHandler(store.Object, systemDiagnostics);

            var endpoint  = new EndpointId("sendingEndpoint");
            var messageId = new MessageId();
            var timeout   = TimeSpan.FromSeconds(30);
            var task      = handler.ForwardResponse(endpoint, messageId, timeout);

            Assert.IsFalse(task.IsCompleted);

            var msg = new SuccessMessage(endpoint, messageId);

            handler.ProcessMessage(msg);

            task.Wait();
            Assert.IsTrue(task.IsCompleted);
            Assert.AreSame(msg, task.Result);
        }
Exemple #5
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            StudentSubject studentSubject = new StudentSubject();

            studentSubject.SubjectID      = Convert.ToInt64(txtSubjectName.Tag);
            studentSubject.SubjectName    = txtSubjectName.Text;
            studentSubject.InsertByID     = Convert.ToInt32(this.Tag);
            studentSubject.InsertDataTime = System.DateTime.Now;
            studentSubject.LastUpdateID   = Convert.ToInt32(this.Tag);
            studentSubject.LastUpdateTime = System.DateTime.Now;
            studentSubject.IsEnabeled     = chkIsEnabled.Checked;
            studentSubject.Remarks        = txtRemarks.Text;

            Int64 subjec_id = StudentSubjectController.InsertUpdateStudentSubject(studentSubject);

            txtSubjectName.Tag = subjec_id;
            if (subjec_id > 0)
            {
                SuccessMessage.SHowDialog("Record Entered Successfully");
            }

            else
            {
                ErrorMessage.SHowDialog("Degree Not Added Successfully");
            }
        }
Exemple #6
0
        public void Show(User user)
        {
            var friendshipOffer = new FriendshipOffer();

            Console.WriteLine("Введите почтовый адрес пользователя которого хотите добавить в друзья: ");
            friendshipOffer.FriendEmail = Console.ReadLine();
            friendshipOffer.HostId      = user.Id;

            try
            {
                userService.BeMyFriend(friendshipOffer);
                SuccessMessage.Show("Друг добавлен в список!");
            }
            catch (UserNotFoundException)
            {
                AlertMessage.Show("Пользователь не найден!");
            }
            catch (ArgumentNullException)
            {
                AlertMessage.Show("Введите корректное значение!");
            }
            catch (Exception)
            {
                AlertMessage.Show("Произошла ошибка при добавлении в друзья!");
            }
        }
Exemple #7
0
        public Mission(MissionPrefab prefab, Location[] locations)
        {
            System.Diagnostics.Debug.Assert(locations.Length == 2);

            this.prefab = prefab;

            Description    = prefab.Description;
            SuccessMessage = prefab.SuccessMessage;
            FailureMessage = prefab.FailureMessage;
            Headers        = new List <string>(prefab.Headers);
            Messages       = new List <string>(prefab.Messages);

            for (int n = 0; n < 2; n++)
            {
                if (Description != null)
                {
                    Description = Description.Replace("[location" + (n + 1) + "]", locations[n].Name);
                }
                if (SuccessMessage != null)
                {
                    SuccessMessage = SuccessMessage.Replace("[location" + (n + 1) + "]", locations[n].Name);
                }
                if (FailureMessage != null)
                {
                    FailureMessage = FailureMessage.Replace("[location" + (n + 1) + "]", locations[n].Name);
                }
                for (int m = 0; m < Messages.Count; m++)
                {
                    Messages[m] = Messages[m].Replace("[location" + (n + 1) + "]", locations[n].Name);
                }
            }
        }
Exemple #8
0
        public void Show(User user)
        {
            string friendEmail;

            Console.Write("Для добавления друга введите его E-Mail: ");
            friendEmail = Console.ReadLine();

            try
            {
                var newFriend = friendService.Create(friendEmail, user);
                SuccessMessage.Show($"Новый друг {newFriend.FirstName} {newFriend.LastName} успешно добавлен:");
            }
            catch (UserNotFoundException)
            {
                AlertMessage.Show("Пользователя с таким E-Mail не существует.");
            }
            catch (WrongFriendException)
            {
                AlertMessage.Show("Нельзя добавить в друзья самого себя.");
            }
            catch (Exception)
            {
                AlertMessage.Show("Произошла ошибка при добавлении друга.");
            }
        }
        protected async override Task OnHandleMessageAsync(Message message, NetworkSession session)
        {
            SuccessMessage successMessage = (SuccessMessage)message;
            AuthSession    authSession    = (AuthSession)session;

            await authSession.AuthSuccessAsync(successMessage.SessionId).ConfigureAwait(false);
        }
Exemple #10
0
        public override async Task <FileSystemInfo> DownloadAsync(DirectoryInfo folder = null)
        {
            // Find the package URI
            await PopulatePackageUri();

            if (!Status.IsAtLeast(SDK.PackageStatus.DownloadReady))
            {
                return(null);
            }

            // Download package
            await StorageHelper.BackgroundDownloadPackage(this, PackageUri, folder);

            if (!Status.IsAtLeast(SDK.PackageStatus.Downloaded))
            {
                return(null);
            }

            // Set the proper file name
            DownloadItem = ((FileInfo)DownloadItem).CopyRename($"{Model.Id}.{Model.Version}.nupkg");

            WeakReferenceMessenger.Default.Send(SuccessMessage.CreateForPackageDownloadCompleted(this));
            Status = SDK.PackageStatus.Downloaded;
            return(DownloadItem);
        }
        public void Show()
        {
            var userRegistrationData = new UserRegistrationData();

            Console.WriteLine("Для создания нового профиля введите ваше имя:");
            userRegistrationData.FirstName = Console.ReadLine();

            Console.Write("Ваша фамилия:");
            userRegistrationData.LastName = Console.ReadLine();

            Console.Write("Пароль:");
            userRegistrationData.Password = Console.ReadLine();

            Console.Write("Почтовый адрес:");
            userRegistrationData.Email = Console.ReadLine();

            try
            {
                this.userService.Register(userRegistrationData);

                SuccessMessage.Show("Ваш профиль успешно создан. Теперь Вы можете войти в систему под своими учетными данными.");
            }

            catch (ArgumentNullException)
            {
                AlertMessage.Show("Введите корректное значение.");
            }

            catch (Exception)
            {
                AlertMessage.Show("Произошла ошибка при регистрации.");
            }
        }
Exemple #12
0
        public static void HandlePackageInstallCompletedToast(SuccessMessage m, ToastNotification progressToast)
        {
            if (!OperatingSystem.IsWindowsVersionAtLeast(10, 0, 18362))
            {
                return;
            }

            PackageBase package = (PackageBase)m.Context;

            var builder = new ToastContentBuilder().SetToastScenario(ToastScenario.Reminder)
                          .AddToastActivationInfo($"package/{package.Urn}", ToastActivationType.Foreground)
                          .AddText(package.ShortTitle)
                          .AddText(package.Title + " just got installed.");

            try
            {
                if (package.GetAppIcon().Result is SDK.Images.FileImage image && !image.Uri.IsFile)
                {
                    builder.AddAppLogoOverride(image.Uri, addImageQuery: false);
                }
            }
            finally { }

            var notif = new ToastNotification(builder.GetXml());

            // Hide progress notification
            Hide(progressToast);
            // Show the final notification
            ToastNotificationManager.GetDefault().CreateToastNotifier().Show(notif);
        }
Exemple #13
0
        public override async Task <bool> InstallAsync()
        {
            // Make sure installer is downloaded
            Guard.IsTrue(Status.IsAtLeast(SDK.PackageStatus.Downloaded), nameof(Status));
            bool isSuccess = false;

            try
            {
                // Extract nupkg and locate PowerShell install script
                var      dir       = StorageHelper.ExtractArchiveToDirectory((FileInfo)DownloadItem, true);
                FileInfo installer = new(Path.Combine(dir.FullName, "tools", "chocolateyInstall.ps1"));
                DownloadItem = installer;

                // Run install script
                // Cannot find a provider with the name '$ErrorActionPreference = 'Stop';
                using PowerShell ps = PowerShell.Create();
                var results = await ps.AddScript(File.ReadAllText(installer.FullName))
                              .InvokeAsync();
            }
            catch (Exception ex)
            {
                WeakReferenceMessenger.Default.Send(new ErrorMessage(ex, this, ErrorType.PackageInstallFailed));
                return(false);
            }

            if (isSuccess)
            {
                WeakReferenceMessenger.Default.Send(SuccessMessage.CreateForPackageInstallCompleted(this));
                Status = SDK.PackageStatus.Installed;
            }
            return(isSuccess);
        }
Exemple #14
0
        public void ActOnArrivalWithMessageFromBlockedSender()
        {
            ICommunicationMessage storedMessage = null;
            var processAction = new Mock <IMessageProcessAction>();
            {
                processAction.Setup(p => p.Invoke(It.IsAny <ICommunicationMessage>()))
                .Callback <ICommunicationMessage>(m => { storedMessage = m; });
            }

            var store = new Mock <IStoreInformationAboutEndpoints>();
            {
                store.Setup(s => s.CanCommunicateWithEndpoint(It.IsAny <EndpointId>()))
                .Returns(false);
            }

            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);
            var handler           = new MessageHandler(store.Object, systemDiagnostics);

            handler.ActOnArrival(new MessageKindFilter(typeof(SuccessMessage)), processAction.Object);

            var endpoint = new EndpointId("sendingEndpoint");
            var msg      = new SuccessMessage(endpoint, new MessageId());

            handler.ProcessMessage(msg);

            Assert.IsNull(storedMessage);
        }
Exemple #15
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                StudentSections studentSections = new StudentSections();
                studentSections.SectionID          = Convert.ToInt32(txtSectionName.Tag);
                studentSections.SectionName        = txtSectionName.Text;
                studentSections.SessionID          = Convert.ToInt64(cmbStudentSession.SelectedValue);
                studentSections.CreatedDateTime    = System.DateTime.Now;
                studentSections.CreatedByID        = Convert.ToInt32(this.Tag);
                studentSections.LastUpdateByID     = Convert.ToInt32(this.Tag);
                studentSections.LastUpdateDateTime = System.DateTime.Now;
                studentSections.IsEnabled          = chkIsEnabled.Checked;
                studentSections.Remarks            = txtSectionRemarks.Text;

                long section_id = StudentSectionsController.InsertUpdateStudentSections(studentSections);
                txtSectionName.Tag = section_id;
                if (section_id > 0)
                {
                    SuccessMessage.SHowDialog("Record Entered Successfully ");
                    StudentSectionDataGridView.DataSource = sections;
                }

                else
                {
                    WarningMessage.SHowDialog("Error: Section Not Added");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Convert.ToString(ex));
            }
        }
Exemple #16
0
    // Update is called once per frame
    void Update()
    {
        if (score >= winScore && score != 0)
        {
            Debug.Log("Level Complete");

            SuccessMessage successMessage = new SuccessMessage();

            successMessage.nextLevel         = nextLevel;
            successMessage.nextLevelWinScore = nextLevelWinScore;

            Debug.Log("Publishing Success Message");
            AudioManager.instance.Play("Win");
            PubSubServerInstance.Publish(successMessage);

            score    = 0;
            winScore = nextLevelWinScore;
        }

        if (Input.GetKeyDown(KeyCode.Escape))
        {
            Debug.Log("Level Failed");
            FailureMessage failureMessage = new FailureMessage();

            Debug.Log("Publishing Failure Message");
            PubSubServerInstance.Publish(failureMessage);

            AudioManager.instance.Play("Fail");
        }
    }
Exemple #17
0
        public void Show(User user)
        {
            try
            {
                var userAddingFriendData = new UserFriendData();

                Console.WriteLine("Введите почтовый адрес пользователя которого хотите добавить в друзья: ");

                userAddingFriendData.FriendEmail = Console.ReadLine();
                userAddingFriendData.UserId      = user.Id;

                this.userService.AddFriend(userAddingFriendData);

                SuccessMessage.Show("Вы успешно добавили пользователя в друзья!");
            }

            catch (UserNotFoundException)
            {
                AlertMessage.Show("Пользователя с указанным почтовым адресом не существует!");
            }

            catch (Exception)
            {
                AlertMessage.Show("Произоша ошибка при добавлении пользотваеля в друзья!");
            }
        }
        /// <summary>
        /// Calculates sum of all SoldBook objects based on SoldBook.Price
        /// User object as parameter for handling session timer and ping function
        /// </summary>
        /// <param name="admin"></param>
        public static void SumOfSoldBooks(User admin)
        {
            bool isSumCalculated = false;

            do
            {
                if (SessionTimer.CheckSessionTimer(admin.SessionTimer) == true || admin.SessionTimer == DateTime.MinValue)
                {
                    Console.Clear();
                    GeneralMessage.AdminNotLoggedIn();
                    break;
                }

                Console.Clear();
                var api = new API();

                var result = api.MoneyEarned(admin.Id);
                if (result == null)
                {
                    ErrorMessage.ErrorNoAbort("calculating the sum of all purchases", "the database is corrupt/empty");
                }
                else
                {
                    SuccessMessage.SuccessWithInt("The sum of all purchases is", result.Value);
                    UserController.SendPing(admin.Id);
                    isSumCalculated = true;
                }
            } while (isSumCalculated == false);
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            StudentProgram studentProgram = new StudentProgram();

            studentProgram.ProgramID          = Convert.ToInt32(txtProgramName.Tag);
            studentProgram.ProgramName        = txtProgramName.Text;
            studentProgram.DegreeID           = Convert.ToInt64(cmbStudentDegree.SelectedValue);
            studentProgram.CreatedByID        = Convert.ToInt32(this.Tag);
            studentProgram.CreatedDateTime    = System.DateTime.Now;
            studentProgram.LastUpdateID       = Convert.ToInt32(this.Tag);
            studentProgram.LastUpdateDateTime = System.DateTime.Now;
            studentProgram.IsEnabled          = chkIsEnabled.Checked;
            studentProgram.Remarks            = txtProgramRemarks.Text;

            long degree_id = StudentProgramController.InsertUpdateStudentProgram(studentProgram);

            txtProgramName.Tag = degree_id;
            if (degree_id > 0)
            {
                SuccessMessage.SHowDialog("Record Entered Successfully");
                StudentProgramDataGridView.DataSource = studentPrograms;
            }
            else
            {
                ErrorMessage.SHowDialog("Record Not Entered Successfully Error!");
            }
        }
Exemple #20
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (subName.Text == String.Empty)
            {
                subName.Focus();
                errorTag.SetError(subName, " Enter Subject Name");
            }
            else if (subCode.Text == String.Empty)
            {
                subCode.Focus();
                errorTag.SetError(subCode, " Enter Subject Code");
            }
            else if (comboBoxRelatedTag.SelectedIndex == -1)
            {
                comboBoxRelatedTag.Focus();
                errorTag.SetError(comboBoxRelatedTag, " Select Related Tag");
            }
            else
            {
                Tag         tag        = new Tag();
                ITagService tagService = new TagService();

                // Set Data
                tag.SubjectName = subName.Text.Trim();
                tag.SubjectCode = subCode.Text.Trim();
                switch (comboBoxRelatedTag.SelectedIndex)
                {
                case 0:
                    tag.RelatedTag = "Lecture";
                    break;

                case 1:
                    tag.RelatedTag = "Tutorial";
                    break;

                case 2:
                    tag.RelatedTag = "Lab";
                    break;
                }
                //Insert Data
                if (tagService.addTag(tag))
                {
                    //MessageBox.Show(tag.Tag);
                    SuccessMessage sc = new SuccessMessage("Tags Added Successfully !");
                    sc.Show();
                    subName.Text = "";
                    subCode.Text = "";
                    comboBoxRelatedTag.SelectedIndex = -1;
                }
                else
                {
                    ErrorMessage ec = new ErrorMessage("there is somethin wrong when tags adding");
                    ec.Show();
                    subName.Text = "";
                    subCode.Text = "";
                    comboBoxRelatedTag.SelectedIndex = -1;
                }
            }
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            SuccessMessage sm = new SuccessMessage("Working Days deleted Sucessfully");

            sm.Show();
            btnDaysCount.Text = String.Empty;
            clear();
        }
Exemple #22
0
        //SqlConnection conloacal = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Ayubo_Leisure.mdf;Integrated Security=True;");

        #endregion

        protected void OPTSend_btn_Click(object sender, EventArgs e)
        {
            String from;
            String pass;
            String messageBody;
            bool   AlredyExists;

            if (String.IsNullOrEmpty(ForgotEmail_txt.Text))
            {
                ErrorMessage.SetError(ForgotEmail_txt, "Enter Email First.");
                return;
            }
            #region Editor S
            from = "*****@*****.**";
            pass = "******";
            #endregion
            // Check exists
            using (SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [Login] WHERE Email = @Email", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("Email", ForgotEmail_txt.Text);
                AlredyExists = (int)cmd.ExecuteScalar() > 0;
                con.Close();
            }
            if (AlredyExists)
            {
                ErrorMessage.SetError(Verify_btn, "Email not found.");
                return;
            }
            Random random = new Random();
            OTPCode = (random.Next(999999)).ToString();

            MailMessage message = new MailMessage();
            to = (ForgotEmail_txt.Text).ToString();

            messageBody = "Your Reset OTP code is " + OTPCode;
            message.To.Add(to);
            message.From    = new MailAddress(from);
            message.Body    = messageBody;
            message.Subject = "No Reply";

            SmtpClient smtp = new SmtpClient("smtp.gmail.com");
            smtp.EnableSsl      = true;
            smtp.Port           = 587;
            smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            smtp.Credentials    = new NetworkCredential(from, pass);

            try
            {
                smtp.Send(message);
                SuccessMessage.SetError(Verify_btn, "Code Send Successfully.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #23
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (comboBoxBuildingName.Text == String.Empty)
            {
                comboBoxBuildingName.Focus();
                errorLocation.SetError(comboBoxBuildingName, " Select Building");
            }
            else if (textBoxRoomName.Text == String.Empty)
            {
                textBoxRoomName.Focus();
                errorLocation.SetError(textBoxRoomName, " Enter Subject Code");
            }

            else if (radioButtonLectureHall.Checked == false & radioButtonLaboratory.Checked == false)
            {
                errorLocation.SetError(radioButtonLectureHall, " Select Room Type");
            }
            else if (textBoxCapacity.Text == String.Empty)
            {
                textBoxCapacity.Focus();
                errorLocation.SetError(textBoxCapacity, " Enter Capacity");
            }
            else
            {
                Location         location        = new Location();
                ILocationService locationService = new LocationService();

                // Set Data

                location.BuildingName = comboBoxBuildingName.Text.Trim();
                location.RoomName     = textBoxRoomName.Text.Trim();

                if (radioButtonLectureHall.Checked == true)
                {
                    location.RoomType = "Lecture Hall";
                }
                else
                {
                    location.RoomType = "Laboratory";
                }

                location.Capacity = textBoxCapacity.Text.Trim();

                //Insert Data
                if (locationService.addLocation(location))
                {
                    //MessageBox.Show(tag.Tag);
                    SuccessMessage sc = new SuccessMessage("Locations Added Successfully !");
                    sc.Show();
                }
                else
                {
                    ErrorMessage ec = new ErrorMessage("there is somethin wrong when  Locations adding");
                    ec.Show();
                }
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            if (comboBoxLec.SelectedIndex == -1)
            {
                comboBoxLec.Focus();
            }
            else if (comboBoxGroup.SelectedIndex == -1)
            {
                comboBoxGroup.Focus();
            }
            else if (comboBoxSub.SelectedIndex == -1)
            {
                comboBoxSub.Focus();
            }
            else if (comboBoxSid.SelectedIndex == -1)
            {
                comboBoxSid.Focus();
            }
            else if (textBox1.Text == String.Empty)
            {
                textBox1.Focus();
                errorNot.SetError(textBox1, "Please Enter Time");
            }
            else
            {
                Notavailable         notavailable        = new Notavailable();
                INotavailableService notavailableService = new NotavailableService();
                // Set Data
                notavailable.Duration      = textBox1.Text.Trim();
                notavailable.Lec_name      = comboBoxLec.Text;
                notavailable.Group_code    = comboBoxGroup.Text;
                notavailable.Subgroup_code = comboBoxSub.Text;
                notavailable.Session_Id    = int.Parse(comboBoxSid.Text);

                //Insert Data
                if (notavailableService.addNotavailable(notavailable))
                {
                    SuccessMessage sc = new SuccessMessage("Not Available Time Added Successfully !");
                    sc.Show();
                    textBox1.Text               = "";
                    comboBoxLec.SelectedIndex   = -1;
                    comboBoxGroup.SelectedIndex = -1;
                    comboBoxSub.SelectedIndex   = -1;
                    comboBoxSid.SelectedIndex   = -1;
                }
                else
                {
                    ErrorMessage ec = new ErrorMessage("Oops, Somthing went wrong!");
                    ec.Show();
                    textBox1.Text               = "";
                    comboBoxLec.SelectedIndex   = -1;
                    comboBoxGroup.SelectedIndex = -1;
                    comboBoxSub.SelectedIndex   = -1;
                    comboBoxSid.SelectedIndex   = -1;
                }
            }
        }
Exemple #25
0
    private void OnSuccess(BaseMessage m)
    {
        SuccessMessage successMessage = m as SuccessMessage;

        if (loadSceneCoroutine == null)
        {
            IEnumerator coroutine = FadeAndLoadScene(successMessage.nextLevel, string.Empty, 2, false);
            loadSceneCoroutine = StartCoroutine(coroutine);
        }
    }
        public void SendMessageToWithOpenChannel()
        {
            var remoteEndpoint = new EndpointId("b");
            var endpointInfo   = new EndpointInformation(
                remoteEndpoint,
                new DiscoveryInformation(new Uri("net.pipe://localhost/discovery")),
                new ProtocolInformation(
                    ProtocolVersions.V1,
                    new Uri("net.pipe://localhost/messages"),
                    new Uri("net.pipe://localhost/data")));
            var endpoints = new Mock <IStoreInformationAboutEndpoints>();
            {
                endpoints.Setup(e => e.CanCommunicateWithEndpoint(It.IsAny <EndpointId>()))
                .Returns(true);
                endpoints.Setup(e => e.TryGetConnectionFor(It.IsAny <EndpointId>(), out endpointInfo))
                .Returns(true);
            }

            var msg     = new SuccessMessage(new EndpointId("B"), new MessageId());
            var channel = new Mock <IProtocolChannel>();
            {
                channel.Setup(c => c.OpenChannel())
                .Verifiable();
                channel.Setup(c => c.LocalConnectionPointForVersion(It.IsAny <Version>()))
                .Returns(endpointInfo.ProtocolInformation);
                channel.Setup(c => c.Send(It.IsAny <ProtocolInformation>(), It.IsAny <ICommunicationMessage>(), It.IsAny <int>()))
                .Callback <ProtocolInformation, ICommunicationMessage, int>(
                    (e, m, r) =>
                {
                    Assert.AreSame(endpointInfo.ProtocolInformation, e);
                    Assert.AreSame(msg, m);
                })
                .Verifiable();
            }

            var pipe = new Mock <IDirectIncomingMessages>();
            Func <ChannelTemplate, EndpointId, Tuple <IProtocolChannel, IDirectIncomingMessages> > channelBuilder =
                (template, id) => new Tuple <IProtocolChannel, IDirectIncomingMessages>(channel.Object, pipe.Object);
            var diagnostics = new SystemDiagnostics((log, s) => { }, null);
            var layer       = new ProtocolLayer(
                endpoints.Object,
                channelBuilder,
                new[]
            {
                ChannelTemplate.NamedPipe,
            },
                diagnostics);

            layer.SignIn();

            layer.SendMessageTo(remoteEndpoint, msg, 1);
            channel.Verify(c => c.OpenChannel(), Times.Once());
            channel.Verify(c => c.Send(It.IsAny <ProtocolInformation>(), It.IsAny <ICommunicationMessage>(), It.IsAny <int>()), Times.Once());
        }
Exemple #27
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (textBoxAcYear.Text == String.Empty)
            {
                textBoxAcYear.Focus();
                errorManageStudent.SetError(textBoxAcYear, " Enter Academic Year an Sem");
            }
            else if (comboBoxProgramme.SelectedIndex == -1)
            {
                comboBoxProgramme.Focus();
                errorManageStudent.SetError(comboBoxProgramme, " Select Programme");
            }
            else if (numericGroupno.Value < 0)
            {
                numericGroupno.Focus();
                errorManageStudent.SetError(numericGroupno, " Enter Valid Group Number");
            }
            else if (numericSubGroup.Value < 0)
            {
                numericSubGroup.Focus();
                errorManageStudent.SetError(numericGroupno, " Enter Valid Sub Group Number");
            }
            else
            {
                Student student = new Student();

                #region Set Data to Object
                // Set Data to model
                student.AcademicYear   = textBoxAcYear.Text.Trim();
                student.Programme      = comboBoxProgramme.SelectedItem.ToString();
                student.GroupNumber    = int.Parse(numericGroupno.Value.ToString());
                student.SubGroupNumber = int.Parse(numericSubGroup.Value.ToString());
                student.GroupId        = textBoxSubGroup.Text.Trim();
                student.SubGroupId     = textBoxSubGroup.Text.Trim();


                #endregion

                //Insert Data
                if (studentService.updateStudent(selectedStu.Id, student))
                {
                    SuccessMessage sc = new SuccessMessage("Student Group Updated Successfully !");
                    sc.Show();
                    dataGridView1.Rows.Clear();
                    populateData();
                    clear();
                }
                else
                {
                    ErrorMessage ec = new ErrorMessage("there is somethin wrong when student- group  updating");
                    ec.Show();
                }
            }
        }
Exemple #28
0
        private void ReportBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Mahiber = _context.Abouts.FirstOrDefault();
                long   SelMemId  = Convert.ToInt64(MemId.Text);
                long   SelRuleId = 0;
                double First     = Mahiber.FirstFin;
                double Second    = Mahiber.SecondFin;
                double Debit     = 0;
                double Last      = Mahiber.LastFin;
                if (!Fundamental.IsChecked.GetValueOrDefault())
                {
                    var  SelectedRule = ViolatedRuleId.SelectedItem;
                    Rule SelRule      = ((Rule)SelectedRule);
                    SelRuleId = SelRule.Id;
                    rule      = _context.Rules.FirstOrDefault(r => r.Id == SelRuleId);
                    First     = Convert.ToDouble(rule.FirstFin);
                    Second    = Convert.ToDouble(rule.SecondFin);
                    Last      = Convert.ToDouble(rule.LastFin);
                }
                int PreRec = _context.Violations.Where(v => v.MemberId == SelMemId).Count();
                if (PreRec < 2)
                {
                    Debit = First;
                }
                else if (PreRec < 3)
                {
                    Debit = Second;
                }
                else if (PreRec < 4)
                {
                    Debit = Last;
                }
                Member Mem = ((Member)_context.Members.FirstOrDefault(m => m.Id == SelMemId));
                Mem.Debit            += Debit;
                violation.Description = Description.Text.Trim();
                violation.MemberId    = SelMemId;
                violation.RuleId      = SelRuleId;

                _context.Entry(Mem).State = System.Data.Entity.EntityState.Modified;
                _context.Violations.Add(violation);
                _context.SaveChanges();
                SuccessMessage sm = new SuccessMessage();
                sm.MessageText.Text = "Reported Successfully";
                sm.Show();
            }
            catch (Exception)
            {
                ErrorMessage er = new ErrorMessage();
                er.MessageText.Text = "report not sent. try again";
                er.Show();
            }
        }
        public void FromMessageWithNonMatchingMessageType()
        {
            var translator = new EndpointDisconnectConverter();

            var msg  = new SuccessMessage(new EndpointId("a"), new MessageId());
            var data = translator.FromMessage(msg);

            Assert.IsInstanceOf(typeof(UnknownMessageTypeData), data);
            Assert.AreSame(msg.Id, data.Id);
            Assert.AreSame(msg.Sender, data.Sender);
            Assert.AreSame(msg.InResponseTo, data.InResponseTo);
        }
 public Schema()
     : base()
 {
     InstanceType = typeof(__Callback__);
     ClassName    = "CallbackPage";
     Properties.ClearExposed();
     Html = Add <__TString__>("Html");
     Html.DefaultValue = "/KitchenSink/CallbackPage.html";
     Html.SetCustomAccessors((_p_) => { return(((__Callback__)_p_).__bf__Html__); }, (_p_, _v_) => { ((__Callback__)_p_).__bf__Html__ = (System.String)_v_; }, false);
     SaveClick = Add <__TLong__>("SaveClick$");
     SaveClick.DefaultValue = 0L;
     SaveClick.Editable     = true;
     SaveClick.SetCustomAccessors((_p_) => { return(((__Callback__)_p_).__bf__SaveClick__); }, (_p_, _v_) => { ((__Callback__)_p_).__bf__SaveClick__ = (System.Int64)_v_; }, false);
     SaveClick.AddHandler((Json pup, Property <Int64> prop, Int64 value) => { return(new Input.SaveClick()
         {
             App = (CallbackPage)pup, Template = (TLong)prop, Value = value
         }); }, (Json pup, Starcounter.Input <Int64> input) => { ((CallbackPage)pup).Handle((Input.SaveClick)input); });
     SaveAndSpinClick = Add <__TLong__>("SaveAndSpinClick$");
     SaveAndSpinClick.DefaultValue = 0L;
     SaveAndSpinClick.Editable     = true;
     SaveAndSpinClick.SetCustomAccessors((_p_) => { return(((__Callback__)_p_).__bf__SaveAndSpinClick__); }, (_p_, _v_) => { ((__Callback__)_p_).__bf__SaveAndSpinClick__ = (System.Int64)_v_; }, false);
     SaveAndSpinClick.AddHandler((Json pup, Property <Int64> prop, Int64 value) => { return(new Input.SaveAndSpinClick()
         {
             App = (CallbackPage)pup, Template = (TLong)prop, Value = value
         }); }, (Json pup, Starcounter.Input <Int64> input) => { ((CallbackPage)pup).Handle((Input.SaveAndSpinClick)input); });
     SaveAndMessageClick = Add <__TLong__>("SaveAndMessageClick$");
     SaveAndMessageClick.DefaultValue = 0L;
     SaveAndMessageClick.Editable     = true;
     SaveAndMessageClick.SetCustomAccessors((_p_) => { return(((__Callback__)_p_).__bf__SaveAndMessageClick__); }, (_p_, _v_) => { ((__Callback__)_p_).__bf__SaveAndMessageClick__ = (System.Int64)_v_; }, false);
     SaveAndMessageClick.AddHandler((Json pup, Property <Int64> prop, Int64 value) => { return(new Input.SaveAndMessageClick()
         {
             App = (CallbackPage)pup, Template = (TLong)prop, Value = value
         }); }, (Json pup, Starcounter.Input <Int64> input) => { ((CallbackPage)pup).Handle((Input.SaveAndMessageClick)input); });
     SuccessMessage = Add <__TString__>("SuccessMessage$");
     SuccessMessage.DefaultValue = "";
     SuccessMessage.Editable     = true;
     SuccessMessage.SetCustomAccessors((_p_) => { return(((__Callback__)_p_).__bf__SuccessMessage__); }, (_p_, _v_) => { ((__Callback__)_p_).__bf__SuccessMessage__ = (System.String)_v_; }, false);
     ErrorMessage = Add <__TString__>("ErrorMessage$");
     ErrorMessage.DefaultValue = "";
     ErrorMessage.Editable     = true;
     ErrorMessage.SetCustomAccessors((_p_) => { return(((__Callback__)_p_).__bf__ErrorMessage__); }, (_p_, _v_) => { ((__Callback__)_p_).__bf__ErrorMessage__ = (System.String)_v_; }, false);
     SaveAndClientMessageClick = Add <__TLong__>("SaveAndClientMessageClick$");
     SaveAndClientMessageClick.DefaultValue = 0L;
     SaveAndClientMessageClick.Editable     = true;
     SaveAndClientMessageClick.SetCustomAccessors((_p_) => { return(((__Callback__)_p_).__bf__SaveAndClientMessageClick__); }, (_p_, _v_) => { ((__Callback__)_p_).__bf__SaveAndClientMessageClick__ = (System.Int64)_v_; }, false);
     SaveAndClientMessageClick.AddHandler((Json pup, Property <Int64> prop, Int64 value) => { return(new Input.SaveAndClientMessageClick()
         {
             App = (CallbackPage)pup, Template = (TLong)prop, Value = value
         }); }, (Json pup, Starcounter.Input <Int64> input) => { ((CallbackPage)pup).Handle((Input.SaveAndClientMessageClick)input); });
     Items = Add <__TArray__>("Items");
     Items.SetCustomGetElementType((arr) => { return(__CaCallback__.DefaultTemplate); });
     Items.SetCustomAccessors((_p_) => { return(((__Callback__)_p_).__bf__Items__); }, (_p_, _v_) => { ((__Callback__)_p_).__bf__Items__ = (__Arr__)_v_; }, false);
 }
//	void Update() {
//		if (Input.GetKeyDown(KeyCode.Alpha1)) {
//			ShowMessage(SuccessMessage.GreatJob);
//		} else if (Input.GetKeyDown(KeyCode.Alpha2)) {
//			ShowMessage(SuccessMessage.Success);
//		}
//	}

	public void ShowMessage(SuccessMessage message, Action toCallOnFadeOut) {
		RectTransform rectTransform = null;
		for (int i = 0; i < successImages.Length; i++) {
			if (successImages[i].message == message) {
				rectTransform = successImages[i].image.rectTransform;
			}
		}

		rectTransform.localScale = Vector3.zero;
		rectTransform.gameObject.SetActive(true);
		LeanTween.scale(rectTransform, Vector3.one, 0.25f).setEase(LeanTweenType.easeOutQuad);
		LeanTween.scale(rectTransform, Vector3.zero, 0.25f).setEase(LeanTweenType.easeInQuad).setDelay(0.25f + 0.5f).setOnComplete(toCallOnFadeOut);
	}