public void EnableButton(ref Button button, DialogResult r1)
 {
     button.Text = "&" + r1.ToString();
     button.DialogResult = r1;
     button.Visible = true;
     button.Click += Button_Click;
 }
 public void EnableButtons(DialogResult r1)
 {
     EnableButton(ref Button1, r1);
     AcceptButton = Button1;
     CancelButton = Button1;
     Button1.Location = Button3.Location;
 }
Esempio n. 3
0
 private void exitToolStripMenuItem_Click(object sender, EventArgs e)
 {
     DialogResult dialogResult = new DialogResult();
     if (!opened) dialogResult = MessageBox.Show("Are you sure you want to exit this application?", "EXIT", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
     else if (opened) dialogResult = MessageBox.Show("A file is currently loaded. Are you sure you want to exit this application?\n\nAll unsaved changes will be lost.", "EXIT", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
     if (dialogResult == DialogResult.Yes) Environment.Exit(2);
 }
Esempio n. 4
0
 private void Abort_Btn_Click(object sender, EventArgs e)
 {
     DialogResult answer = new DialogResult();
     answer = MessageBox.Show("Are you sure you want to quit now? The temperature coefficient will NOT be stored.", "Abort Now?", MessageBoxButtons.YesNo,
         MessageBoxIcon.Question);
     if (answer == DialogResult.Yes) Application.Exit();
 }
        /// <summary>
        /// Runs custom wizard logic at the beginning of a template wizard run.
        /// </summary>
        protected override void OnRunStarted()
        {
            TraceService.WriteLine("WebRequestServiceWizard::OnRunStarted");

            WebRequestServiceView view = new WebRequestServiceView();
            view.ShowDialog();

            this.dialogResult = view.DialogResult;

            if (this.dialogResult == DialogResult.OK)
            {
                this.entityName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(view.EntityName);

                this.ReplacementsDictionary.Add("$webRequestEntityName$", this.entityName);

                this.AddGlobal("MockWebRequestService", "mock" + this.entityName + "WebRequestService");
                this.AddGlobal("InterfaceWebRequest", "I" + this.entityName + "WebRequestService");
                this.AddGlobal("webRequestInstance", this.entityName.LowerCaseFirstCharacter() + "WebRequestService");
                this.AddGlobal("WebRequestService", this.entityName + "WebRequestService");

                this.AddGlobal("SampleWebRequestService", this.entityName + "WebRequestService");

                this.AddGlobal("SampleWebRequestData", this.entityName);
                this.AddGlobal("WebRequestSampleData", this.entityName);

                this.AddGlobal("SampleWebRequestDataInstance", this.entityName.LowerCaseFirstCharacter());
                this.AddGlobal("SampleWebRequestTranslator", this.entityName + "Translator");
            }
        }
Esempio n. 6
0
        public void CommonExport()
        {
            DialogResult result = new DialogResult();
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.RestoreDirectory = false;
            dialog.Filter = "PNG Image (*.png) [Recommended]|*.png|JPEG Image (*.jpeg) [Bad Idea]|*.jpg|BMP Image (*.bmp)|*.bmp";
            dialog.FileName = Path.ChangeExtension(filename, null);
            dialog.AddExtension = true;
            result = dialog.ShowDialog();
            if (dialog.FileName != "" && result == DialogResult.OK)
            {
                System.IO.FileStream fs = (System.IO.FileStream)dialog.OpenFile();
                switch (dialog.FilterIndex)
                {
                    case 1:
                        bitmap.Save(fs,
                        System.Drawing.Imaging.ImageFormat.Png);
                        break;

                    case 2:
                        bitmap.Save(fs,
                        System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;

                    case 3:
                        bitmap.Save(fs,
                        System.Drawing.Imaging.ImageFormat.Bmp);
                        break;
                }
                fs.Close();
            }
        }
				void CloseThis(DialogResult result= System.Windows.Forms.DialogResult.OK)
				{
					if (Loading)
						return;
					this.DialogResult = result;
					this.Close();
				}
Esempio n. 8
0
 public void CreatePerson(Packet templatePacket = null)
 {
     FormMode = Mode.Create;
     saveDialogResult = DialogResult.None;
     btnClose.Visible = true;
     _templatePacket = templatePacket;
 }
Esempio n. 9
0
    public void AddAction(string text, DialogResult result, Image image = null, bool isDefault = false)
    {
      int width = this.ClientSize.Width-20;
      var button = new SimpleButton();
      button.Text = text;
      button.Appearance.TextOptions.HAlignment = HorzAlignment.Near;
      button.Image = image;
      button.Width = width;
      button.Left = 10;
      button.Height = ButtonHeight;
      button.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
      button.Tag = result;
      button.Click += button_Click;
      
      this.Controls.Add(button);

      if (isDefault)
        this.AcceptButton = button;

      button.DialogResult = result;
      if (result == DialogResult.Cancel)
      {
        this.CancelButton = button;
        this.ControlBox = true;
        this.SelectedAction = result;
      }
    }
        /// <summary>
        /// <para>If DPAPI settings change, this saves the key algorithm out with the new settings.</para>
        /// </summary>
        /// <param name="dialogResult">
        /// <para>One of the <see cref="DialogResult"/> values.</para>
        /// </param>
        /// <param name="originalSettings">
        /// <para>The original <see cref="DpapiSettings"/> before editing.</para>
        /// </param>
        /// <param name="newSettingsData">
        /// <para>The new <see cref="DpapiSettingsData"/> from the editor.</para>
        /// </param>
        /// <returns>
        /// <para>If accepted, the new <see cref="DpapiSettings"/>; otherwise the <paramref name="originalSettings"/>.</para>
        /// </returns>
        protected override object HandleResult(DialogResult dialogResult, DpapiSettings originalSettings, DpapiSettingsData newSettingsData)
        {
            bool returnBaseResult = true;

            if (dialogResult == DialogResult.OK)
            {
                DpapiSettings newDpapiSettings = null;
                if (newSettingsData != null)
                {
                    newDpapiSettings = new DpapiSettings(newSettingsData);
                }

                if (newDpapiSettings != originalSettings)
                {
                    returnBaseResult = SaveKeyAlgorithmPairWithNewDapiSettings(newDpapiSettings, originalSettings);
                }
            }

            if (returnBaseResult)
            {
                return base.HandleResult(dialogResult, originalSettings, newSettingsData);
            }
            else
            {
                return originalSettings;
            }
        }
Esempio n. 11
0
 /// <summary>
 /// Ввод значения из модального диалога
 /// </summary>
 /// <param name="caption">заголовок окна диалога</param>
 /// <param name="label">надпись в окне слева от поля ввода</param>
 /// <param name="enableCancel">видимость кнопки "Отмена"</param>
 /// <param name="inputText">начальное значение</param>
 /// <param name="rst">DialogResult.OK - нажата кнопка "Принять", DialogResult.Cancel - нажата кнопка "Отмена"</param>
 /// <returns></returns>
 public static string ShowInputDialog(string caption, string label,
     bool enableCancel, string inputText, out DialogResult rst)
 {
     var dlg = new SimpleDialog(caption, label, enableCancel, inputText);
     rst = dlg.ShowDialog();
     return dlg.InputValue;
 }
Esempio n. 12
0
        private void btnAddProfile_Click(object sender, EventArgs e)
        {
            // Make sure the email is valid
            if (SGGlobals.IsEmailValid(txtDefaultAddress.Text) == false)
            {
                MessageBox.Show("Email address does not appear to be valid!", "Error creating profile", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Make sure the profile doesn't exist
            try
            {
                UserProfiles.GetProfileByName(txtProfileName.Text);

                // Profile exists!
                MessageBox.Show("Profile name already exists!", "Error creating profile", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            catch (ProfileNotFoundException)
            {
                // Profile does not exist, create it
                Profile objNewProfile = new Profile();
                objNewProfile.Name = txtProfileName.Text;
                objNewProfile.ToAddresses.Add(txtDefaultAddress.Text);
                objNewProfile.Save();
                this._objDialogStatus = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("An unknown error occured creating the new profile:"
                    + Environment.NewLine + ex.Message, "Error creating profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 13
0
 private void button1_Click(object sender, EventArgs e)
 {
     SaveFileDialog sfd = new SaveFileDialog();
        sfd.AddExtension = true;
        sfd.DefaultExt = ".h";
        sfd.FileName = "os_cfg";
        DialogResult dr = new DialogResult();
        dr=sfd.ShowDialog();
        if (dr == DialogResult.OK)
        {
         String directory = @sfd.FileName;
         String text = textBox1.Text;
         if (File.Exists(directory))
         {
             StreamWriter swWriter = new StreamWriter(directory);
             swWriter.WriteLine(text);
             swWriter.Flush();
             swWriter.Close();
         }
         else
         {
             FileStream fs = File.Create(directory);
             fs.Flush();
             fs.Close();
             StreamWriter swWriter = new StreamWriter(directory);
             swWriter.WriteLine(text);
             swWriter.Flush();
             swWriter.Close();
         }
        }
 }
Esempio n. 14
0
        private void FillValues()
        {
            m_Result = DialogResult.OK;
            
            m_HAlignment = string.Empty;
            if (HorizontalAlignmentcomboBox.SelectedIndex > 0)
                m_HAlignment = HorizontalAlignmentcomboBox.Items[HorizontalAlignmentcomboBox.SelectedIndex].ToString();
            
            m_VAlignment = string.Empty;
            if (VerticalAlignmentcomboBox.SelectedIndex > 0)
                m_VAlignment = VerticalAlignmentcomboBox.Items[VerticalAlignmentcomboBox.SelectedIndex].ToString();

            m_BackColor = (backgoundcolorcomboBox.SelectedColor == Color.Empty) ? 
                string.Empty : backgoundcolorcomboBox.SelectedColor.Name;
            
            m_BorderColor = (bordercolorcomboBox.SelectedColor == Color.Empty) ? 
                string.Empty : bordercolorcomboBox.SelectedColor.Name;

            m_LightBorderColor = (borderlightcolorcomboBox.SelectedColor == Color.Empty) ?
                string.Empty : borderlightcolorcomboBox.SelectedColor.Name;

            m_DarkBorderColor = (borderdarkcolorcomboBox.SelectedColor == Color.Empty) ?
                string.Empty : borderdarkcolorcomboBox.SelectedColor.Name;

            m_NoWrap = chkNoWrap.Checked;
            
        }
Esempio n. 15
0
 private void Abort_Btn_Click(object sender, EventArgs e)
 {
     DialogResult answer = new DialogResult();
     answer = MessageBox.Show("Are you sure you want to quit now? Your start point data will not be saved.", "Abort Now?", MessageBoxButtons.YesNo,
         MessageBoxIcon.Question);
     if (answer == DialogResult.Yes) Application.Exit();
 }
Esempio n. 16
0
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            if(!String.IsNullOrEmpty(textBox.Text))
            {
                DialogResult dr = new DialogResult();
                ConfirmDialogView confirm = new ConfirmDialogView();
                confirm.getLabelConfirm().Text = "U heeft een andere naam ingevuld, weet u zeker dat u wilt annuleren?";
                dr = confirm.ShowDialog();

                if(dr == DialogResult.Yes)
                {
                    confirm.Close();
                    this.Close();
                }
                else
                {
                    confirm.Close();
                }

            }
            else
            {
                this.Close();
            }
        }
 private void btnAllEmployees_Click(object sender, EventArgs e)
 {
     this.Hide();
     DialogResult dr = new DialogResult();
     SalaryReportofEmployee esa = new SalaryReportofEmployee();
     dr = esa.ShowDialog();
 }
Esempio n. 18
0
 public void OpenDialog(bool multipleFiles, params FileTypes[] fileTypes)
 {
     ofd = new OpenFileDialog();
     ofd.Multiselect = multipleFiles;
     ofd.Filter = Utils.FileTypesToWinFormFilter(fileTypes);
     result = ofd.ShowDialog();
 }
 private void btnSlipOrReport_Click(object sender, EventArgs e)
 {
     this.Hide();
     DialogResult dr = new DialogResult();
     SalarySlip ss = new SalarySlip();
     dr = ss.ShowDialog();
 }
Esempio n. 20
0
        /// <summary>
        /// Close all files.
        /// </summary>
        /// <param name="projectFiles">If this is <c>true</c> it will close all files from the project.</param>
        /// <returns>Returns <c>true</c> if cancel button is not pressed, <c>false</c> otherwise.</returns>
        public static bool CloseAll(bool projectFiles)
        {
            bool saveAll = false;

            foreach (Editor editor in editorList.Values)
            {
                if (((projectFiles == true && editor.IsProjectFile == true) || (projectFiles == false && editor.IsProjectFile == false)) && editor.IsModified == true)
                {
                    if (saveAll == false)
                    {
                        DialogResult dialogResult = new DialogResult();

                        dialogResult = MessageBox.Show("Do you want to save all changes?", "Save changes", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);

                        if (dialogResult == DialogResult.Yes)
                        {
                            saveAll = true;
                        }
                        else if (dialogResult == DialogResult.Cancel)
                        {
                            return true;
                        }
                    }

                    if (saveAll == true)
                    {
                        editor.Save();
                    }
                }
            }

            return false;
        }
        private void DGProduct_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (countDeleting == 1)
            {
                dialogResult = MessageBox.Show("Esta seguro que desea eliminar los productos seleccionados?\r\n" + DGProduct.SelectedRows.Count + " productos seran eliminados!", "Eliminar productos", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                countSelectedRows = DGProduct.SelectedRows.Count;
            }

            if (countDeleting == countSelectedRows)
            {
                countDeleting = 1;
                countSelectedRows = 0;
            }
            else
                countDeleting++;

            if (dialogResult == DialogResult.Cancel)
                e.Cancel = true;
            else
            {
                try {
                    int id = Int32.Parse(e.Row.Cells["Id"].Value.ToString());
                    Product prod = stock.Product.First(i => i.id == id);
                    prod.deleted_at = DateTime.Now;
                    stock.SaveChanges();

                }catch(Exception exc)
                {
                    Console.WriteLine(exc);
                }
                finally {
                    e.Cancel = false;
                }
            }
        }
Esempio n. 22
0
 public OverrideInformation(bool a, bool b, bool c, DialogResult d)
 {
     PointChecked = a;
     PolylineChecked = b;
     PolygonChecked = c;
     dialogResult = d;
 }
Esempio n. 23
0
        private void brisiDioNekretnineButton_Click(object sender, EventArgs e)
        {
            try
            {
                DAO dao = new DAO("localhost", "ikzavrsni", "root", "root");

                for (int i = 0; i < dijeloviNekretnineListView.Items.Count; i++)
                    if (dijeloviNekretnineListView.Items[i].Selected == true)
                    {
                        foreach (DioNekretnine dn in dijeloviNekretnina)
                            if (dn.Naziv == dijeloviNekretnineListView.Items[i].Text)
                            {
                                DialogResult dr = new DialogResult();
                                dr = MessageBox.Show("Da li ste sigurni da želite izbrisati odabrani dio nekretnine iz baze podataka?", "Upozorenje", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                                if (dr == System.Windows.Forms.DialogResult.Yes)
                                {
                                    dao.IzbrisiDioNekretnine(dn.Sifra);
                                    dijeloviNekretnineListView.Items.Clear();
                                    statusStrip1.BackColor = Color.White;
                                    toolStripStatusLabel1.ForeColor = Color.Green;
                                    toolStripStatusLabel1.Text = "Uspješno izbrisani podaci.";
                                    return;
                                }
                            }
                    }
            }
            catch (Exception)
            {
                statusStrip1.BackColor = Color.White;
                toolStripStatusLabel1.ForeColor = Color.Red;
                toolStripStatusLabel1.Text = "Podaci nisu obrisani!";
            }
        }
Esempio n. 24
0
        private void btn_resize_Click(object sender, EventArgs e)
        {
            if ( GLB_Data.MapSize.Depth > updwn_depth.Value ||
                 GLB_Data.MapSize.Width > updwn_width.Value ||
                 GLB_Data.MapSize.Height > updwn_height.Value)
            {
                dialog_result = MessageBox.Show("New new size is smaller than current map dimensions, " +
                                                             "some tiles will be lost\n Proceed?", "Warning",
                                                             MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);

                if (dialog_result == DialogResult.No)
                {
                    return;
                }
            }

            dialog_result = MessageBox.Show("Warning, the resize operation cannot be undone.\nProceed?", "Warning",
                                                         MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (dialog_result == DialogResult.No)
            {
                return;
            }

            ResizeMap(Convert.ToInt32(updwn_depth.Value), Convert.ToInt32(updwn_width.Value), Convert.ToInt32(updwn_height.Value));

            this.Dispose(true);

            main_form.ResetCamera();
            main_form.ClearUndoRedo();
            main_form.CheckUndoRedo();
            main_form.InitScrollBars();
        }
    public const string DIALOG_RESULT = "DialogResult"; // Type: DialogResult

    public static void SendDialogManagerMessage(Guid dialogHandle, DialogResult result)
    {
      SystemMessage msg = new SystemMessage(MessageType.DialogClosed);
      msg.MessageData[DIALOG_HANDLE] = dialogHandle;
      msg.MessageData[DIALOG_RESULT] = result;
      ServiceRegistration.Get<IMessageBroker>().Send(CHANNEL, msg);
    }
Esempio n. 26
0
        private void m_cmd_xoa_Click(object sender, EventArgs e)
        {
            try
            {
                //lay ra du lieu cua dong muon xoa bang thay da bam vao
                DataRow v_dr = m_grv.GetDataRow(m_grv.FocusedRowHandle);
                // lay ra id cua dong du lieu vua chon gan vao v_id duoi dang chuoi
                decimal v_id = CIPConvert.ToDecimal(v_dr["ID"].ToString());

                US_DM_CAU_HOI v_us = new US_DM_CAU_HOI(v_id);

                DialogResult result = new DialogResult();
                result = MessageBox.Show("Bạn chắc chắn muốn xóa?","Xác nhận", MessageBoxButtons.YesNo,MessageBoxIcon.Question,MessageBoxDefaultButton.Button2);

                if (result == DialogResult.Yes)
                {
                    v_us.Delete();
                    MessageBox.Show("Bạn vừa xóa thành công");
                    load_data_2_grid();
                }
            }
            catch (Exception v_ex)
            {
                CSystemLog_301.ExceptionHandle(v_ex);
            }
        }
 public void SetInfomation(DialogResult _result, int _textId, Vector3 _location)
 {
     tranformBtn.gameObject.SetActive(true);
     result = _result;
     //text.text = AvLocalizationManager.GetString(_textId);
     tranformBtn.localPosition = _location;
 }
Esempio n. 28
0
        public static DialogResult Mostrar(Exception ex, string tipoMensaje)
        {
            var resultado = new DialogResult();

            switch (tipoMensaje)
            {
                case Tipo.Informacion:
                    resultado = MessageBox.Show(ex.InnerException == null ? ex.Message : ex.InnerException.Message, Tipo.Informacion, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
                case Tipo.Error:
                    resultado = MessageBox.Show(ex.InnerException == null ? ex.Message : ex.InnerException.Message, Tipo.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                case Tipo.Pregunta:
                    resultado = MessageBox.Show(ex.InnerException == null ? ex.Message : ex.InnerException.Message, Tipo.Pregunta, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    break;
                case Tipo.Advertencia:
                    resultado = MessageBox.Show(ex.InnerException == null ? ex.Message : ex.InnerException.Message, Tipo.Advertencia, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    break;
                case Tipo.Stop:
                    resultado = MessageBox.Show(ex.InnerException == null ? ex.Message : ex.InnerException.Message, Tipo.Stop, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    break;
            }

            return resultado;
        }
Esempio n. 29
0
        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(textBox.Text))
            {
                DialogResult dr = new DialogResult();
                ConfirmDialogView confirm = new ConfirmDialogView();
                confirm.getLabelConfirm().Text = "Weet u zeker dat u de naam van de vragenlijst wilt wijzigen?";
                dr = confirm.ShowDialog();

                if (dr == DialogResult.Yes)
                {
                    Model.QuestionList questionList = new Model.QuestionList();
                    questionList.Id = QuestionListId;
                    questionList.Name = textBox.Text;
                    Controller.UpdateQuestionList(questionList);

                    this.QuestionListNameChanged = true;
                    confirm.Close();
                }
            }
            else
            {
                MessageBox.Show("U heeft niks ingevuld, vul alstublieft de nieuwe naam in");
            }
        }
Esempio n. 30
0
        private void SettingsDlg_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (uidBox.Focused && uidBox.Text != HatHConfig.UserID)
            {
                HatHConfig.UserID = uidBox.Text;
                exitWith = DialogResult.OK;
            }

            if (passBox.Focused && passBox.Text != HatHConfig.PassHash)
            {
                HatHConfig.PassHash = passBox.Text;
                exitWith = DialogResult.OK;
            }

            if (hathrootBox.Focused && hathrootBox.Text != HatHConfig.HatHRoot)
            {
                HatHConfig.HatHRoot = hathrootBox.Text;
                exitWith = DialogResult.OK;
            }

            if (outdirBox.Focused && outdirBox.Text != HatHConfig.OutputDirectory)
            {
                HatHConfig.OutputDirectory = outdirBox.Text;
                exitWith = DialogResult.OK;
            }

            DialogResult = exitWith;
        }
        private void LaunchSpeedOMeter_Click(object sender, EventArgs e)
        {
            if (Process.GetProcessesByName("MirrorsEdgeCatalyst").Length > 0)
            {
                if (!FullScreenMode)
                { // Display speed using overlay (Window/Borderless compatible only)
                    FormCollection fc = Application.OpenForms;
                    if (fc.Count < 2)
                    {
                        if (UpdateRateMenu.SelectedItem == null)
                        {
                            UpdateRateMenu.SelectedItem = 50;
                        }
                        SpeedOMeter = new SpeedOMeter((int)DecimalsNumericBox.Value, ColorPickerColor, (int)UpdateRateMenu.SelectedItem);
                        new Thread(() => Application.Run(SpeedOMeter)).Start();

                        LaunchSpeedOMeter.ForeColor = Color.Green;
                    }
                }
                else
                {
                    // Display Speed using IG Overlay Hijacking method
                    // All work done in FPSHijacker.cs
                    if (UpdateRateMenu.SelectedItem == null)
                    {
                        UpdateRateMenu.SelectedItem = 50;
                    }
                    fpsHijacker = new FpsHijacker((int)UpdateRateMenu.SelectedItem,
                                                  (int)DecimalsNumericBox.Value,
                                                  (float)ScaleFontUIValue.Value,
                                                  (int)XOffsetUIValue.Value,
                                                  (int)YOffsetUIValue.Value,
                                                  (byte)AlphaFontScaleBar.Value
                                                  );
                    LaunchSpeedOMeter.ForeColor = Color.Green;
                }
            }
            else
            {
                // Mirror's edge catalyst isn't running => ask user if he wants to run it
                DialogResult dr = MessageBox.Show("It appears that Mirror's Edge : Catalyst isn't running.\n Shall I run it for you ?", "ME:C is not running", MessageBoxButtons.YesNo);
                if (dr == DialogResult.Yes)
                {
                    try
                    {
                        // get mexExecPath
                        RegistryKey mecRegKey   = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\EA Games\\Mirrors Edge Catalyst");
                        string      mecExecPath = (string)mecRegKey.GetValue("Install Dir") + "MirrorsEdgeCatalyst.exe";

                        // Launch Mirror's Edge Catalyst
                        Process mecProcess = new Process();
                        mecProcess.StartInfo.FileName = mecExecPath;
                        mecProcess.Start();
                    }
                    catch
                    {
                        MessageBox.Show("Sorry I couldn't locate MirrorsEdgeCatalyst.exe");
                    }
                }
            }
        }
Esempio n. 32
0
 //Create and Format printable REPORT based on results requested by admin
 private void printReportButton_Click(object sender, EventArgs e)
 {
     searchButton_Click(sender, e);
     if (reportTable.Rows.Count > 0)
     {
         using (StreamWriter rsw = new StreamWriter("../../PrintableReport.txt"))
         {
             rsw.WriteLine("------------------------------");
             rsw.WriteLine("Report Details");
             rsw.WriteLine("------------------------------");
             rsw.WriteLine("\nDates Selected: " + datesSelected.Text);
             rsw.WriteLine("\nCities Selected: " + cityReportBox.Text + "\n");
             rsw.Write(string.Format("{0,-24}", "--------------------"));
             rsw.Write(string.Format("{0,-24}", "--------------------"));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Lowest"));
             rsw.Write(string.Format("{0,-24}", "Highest"));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "--------------------"));
             rsw.Write(string.Format("{0,-24}", "--------------------"));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Min Temp: " + lowestMinTemp.Text));
             rsw.Write(string.Format("{0,-24}", "Min Temp: " + highestMinTemp.Text));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Max Temp: " + lowestMaxTemp.Text));
             rsw.Write(string.Format("{0,-24}", "Max Temp: " + highestMaxTemp.Text));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Precipitation: " + lowestPrecip.Text));
             rsw.Write(string.Format("{0,-24}", "Precipitation: " + highestPrecip.Text));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Humidity: " + lowestHumid.Text));
             rsw.Write(string.Format("{0,-24}", "Humidity: " + highestHumid.Text));
             rsw.WriteLine();
             rsw.Write(string.Format("{0,-24}", "Wind Speed: " + lowestHumid.Text));
             rsw.Write(string.Format("{0,-24}", "Wind Speed: " + highestHumid.Text));
             rsw.WriteLine("\n");
             rsw.WriteLine("------------------------------");
             rsw.WriteLine("All Results");
             rsw.WriteLine("------------------------------");
             rsw.Write(string.Format("{0,-18}", "City"));
             rsw.Write(string.Format("{0,-13}", "Date"));
             rsw.Write(string.Format("{0,-10}", "Min Temp"));
             rsw.Write(string.Format("{0,-10}", "Max Temp"));
             rsw.Write(string.Format("{0,-15}", "Precipitation"));
             rsw.Write(string.Format("{0,-10}", "Humidity"));
             rsw.Write(string.Format("{0,-12}", "Wind Speed"));
             rsw.WriteLine();
             rsw.WriteLine();
             for (int i = 0; i < reportTable.Rows.Count; i++)
             {
                 rsw.Write(string.Format("{0,-18}", $"{reportTable.Rows[i].Cells[0].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-13:d}", $"{reportTable.Rows[i].Cells[1].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-10}", $"{reportTable.Rows[i].Cells[2].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-10}", $"{reportTable.Rows[i].Cells[3].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-15}", $"{reportTable.Rows[i].Cells[4].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-10}", $"{reportTable.Rows[i].Cells[5].Value.ToString()}"));
                 rsw.Write(string.Format("{0,-12}", $"{reportTable.Rows[i].Cells[6].Value.ToString()}"));
                 rsw.WriteLine();
             }
         }
         DialogResult result = MessageBox.Show("Report successfully created with " + reportTable.Rows.Count + " results.\n\nThis report can be found at: \n\n" + Path.GetFullPath("../../PrintableReport.txt") + "\n\nWould you like to open the report now?", "Report Created", MessageBoxButtons.YesNo);
         if (result == DialogResult.Yes)
         {
             Process.Start(@Path.GetFullPath("../../PrintableReport.txt"));
         }
         else
         {
         }
     }
     else
     {
         MessageBox.Show("Report not created! There are no results found in the report table. Please search for existing results and try again.");
     }
 }
Esempio n. 33
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public Boolean ExecuteStructSample()
        {
            Document     rvtDoc  = m_app.ActiveUIDocument.Document;
            FamilySymbol colType = null;

            List <Wall> walls = new List <Wall>();

            //  iterate through a selection set, and collect walls which are constrained at the top and the bottom.
            //
            foreach (ElementId id in m_ids)
            {
                Element elem = rvtDoc.GetElement(id);

                if (elem.GetType() == typeof(Autodesk.Revit.DB.Wall))
                {
                    if (elem.get_Parameter(BuiltInParameter.WALL_HEIGHT_TYPE) != null && elem.get_Parameter(BuiltInParameter.WALL_BASE_CONSTRAINT) != null)
                    {
                        walls.Add(elem as Wall);
                    }
                }
            }

            //  how many did we get?
            MessageBox.Show("Number of constrained walls in the selection set is " + walls.Count);

            if (walls.Count == 0)
            {
                DialogResult dlgRes = MessageBox.Show("You must select some walls that are constrained top or bottom", "Structural Sample", MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (dlgRes == System.Windows.Forms.DialogResult.OK)
                {
                    return(false);
                }
            }

            //  we have some # of walls now.

            // Load the required family

            FilteredElementCollector collect         = new FilteredElementCollector(rvtDoc);
            ElementClassFilter       familyAreWanted = new ElementClassFilter(typeof(Family));

            collect.WherePasses(familyAreWanted);
            List <Element> elements = collect.ToElements() as List <Element>;

            foreach (Element e in elements)
            {
                Family fam = e as Family;
                if (fam != null)
                {
                    if (fam.Name == "M_Wood Timber Column")
                    {
                        colType = Utils.FamilyUtil.GetFamilySymbol(fam, "191 x 292mm");
                    }
                }
            }


            String fileName = "../Data/Platform/Metric/Library/Architectural/Columns/M_Wood Timber Column.rfa";
            Family columnFamily;

            if (colType == null)
            {
                m_app.ActiveUIDocument.Document.LoadFamily(fileName, out columnFamily);
                colType = Utils.FamilyUtil.GetFamilySymbol(columnFamily, "191 x 292mm");
            }

            if (colType == null)
            {
                MessageBox.Show("Please load the M_Wood Timber Column : 191 x 292mm family");
                Utils.UserInput.LoadFamily(null, m_app.ActiveUIDocument.Document);
            }

            //
            //  place columns.
            //
            double spacing = 5; //  Spacing in feet hard coded. Note: Revit's internal length unit is feet.

            foreach (Autodesk.Revit.DB.Wall wall in walls)
            {
                FrameWall(m_app.Application, wall, spacing, colType);
            }

            return(true);
        }
Esempio n. 34
0
        private void menuItem2_Click(object sender, System.EventArgs e)
        {
            SaveFileDialog sf = new SaveFileDialog();

            sf.Filter = "Formatted text|*.txt|Comma-Separated Values|*.csv";
            DialogResult r = sf.ShowDialog();

            if (r == DialogResult.OK)
            {
                try
                {
                    if (File.Exists(sf.FileName))
                    {
                        File.Delete(sf.FileName);
                    }
                }
                catch
                {
                    MessageBox.Show(this, "Cannot delete existing file " + sf.FileName, "Failure");
                    return;
                }

                bool formatNicely = !sf.FileName.ToLower().EndsWith(".csv");

                int i, j, columns = list.Columns.Count;
                try
                {
                    StreamWriter s       = new StreamWriter(sf.FileName);
                    string[]     formats = new string[columns];
                    if (formatNicely)
                    {
                        // figure out widths of the columns
                        int[] widths = new int[columns];
                        for (i = 0; i < columns; i++)
                        {
                            widths[i] = list.Columns[i].Text.Length;
                        }
                        for (i = 0; i < list.Items.Count; i++)
                        {
                            ListViewItem m = list.Items[i];
                            for (j = 0; j < columns; j++)
                            {
                                int l = m.SubItems[j].Text.Length;
                                if (l > widths[j])
                                {
                                    widths[j] = l;
                                }
                            }
                        }

                        // create formats
                        for (i = 0; i < columns; i++)
                        {
                            formats[i] = "{0," + (i == 0 ? "-" : "") + widths[i] + '}' + (i == columns - 1 ? '\n' : ' ');
                        }
                    }
                    else
                    {
                        for (i = 0; i < columns - 1; i++)
                        {
                            formats[i] = "{0},";
                        }
                        formats[columns - 1] = "{0}\n";
                    }

                    for (i = 0; i < columns; i++)
                    {
                        s.Write(formats[i], list.Columns[i].Text);
                    }
                    if (formatNicely)
                    {
                        s.Write('\n');
                    }
                    for (i = 0; i < list.Items.Count; i++)
                    {
                        ListViewItem m = list.Items[i];
                        for (j = 0; j < columns; j++)
                        {
                            s.Write(formats[j], m.SubItems[j].Text);
                        }
                    }
                    s.Close();
                }
                catch
                {
                    MessageBox.Show(this, "Error saving table to a file named " + sf.FileName, "Failure");
                    return;
                }
            }
        }
        void OutPutSummary()
        {
            BackgroundWorker worker   = new BackgroundWorker();
            string           filename = string.Empty;
            SaveFileDialog   sf       = new SaveFileDialog();

            sf.Title      = "save data";
            sf.Filter     = "Excel|*.xlsx";
            sf.DefaultExt = ".xlsx";
            sf.FileName   = "Unified" + "_StnSummary_" + DateTime.Now.ToShortDateString().Replace(@"/", "");
            DialogResult result = sf.ShowDialog();

            if (result == DialogResult.Cancel)
            {
                return;
            }

            if (sf.FileName != "")
            {
                filename = sf.FileName;
            }
            else
            {
                return;
            }



            worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                SummaryIsProcessing = false;
            };
            worker.DoWork += delegate(object s, DoWorkEventArgs args)
            {
                XbyYShearStationSummary summary = null;

                try
                {
                    SummaryIsProcessing = true;

                    //create the DataTable
                    if (_unifiedData != null)
                    {
                        _unifiedData.Clear();
                    }
                    BuildDataTable();
                    //create column collection
                    ColumnCollection = new SessionColumnCollection(_unifiedData);


                    //add column def and add configs

                    ISessionColumn hubws = ColumnCollection[HubHeight.ToString() + "m"];
                    hubws.ColumnType   = SessionColumnType.WSAvgShear;
                    hubws.IsCalculated = true;
                    hubws.IsComposite  = true;
                    SensorConfig config = new SensorConfig()
                    {
                        StartDate = _startDate, EndDate = _endDate, Height = HubHeight
                    };
                    hubws.Configs.Add(config);

                    ISessionColumn upperws = ColumnCollection[UpperHeight.ToString() + "m"];
                    upperws.ColumnType  = SessionColumnType.WSAvg;
                    upperws.IsComposite = true;
                    config = new SensorConfig()
                    {
                        StartDate = _startDate, EndDate = _endDate, Height = UpperHeight
                    };
                    upperws.Configs.Add(config);

                    ISessionColumn lowerws = ColumnCollection[LowerHeight.ToString() + "m"];
                    lowerws.ColumnType  = SessionColumnType.WSAvg;
                    lowerws.IsComposite = true;
                    config = new SensorConfig()
                    {
                        StartDate = _startDate, EndDate = _endDate, Height = LowerHeight
                    };
                    lowerws.Configs.Add(config);

                    ISessionColumn wd = ColumnCollection["WD"];
                    wd.ColumnType  = SessionColumnType.WDAvg;
                    wd.IsComposite = true;
                    config         = new SensorConfig()
                    {
                        StartDate = _startDate, EndDate = _endDate
                    };
                    wd.Configs.Add(config);


                    //get axis selections from UI
                    IAxis Xaxis = GetAxis(_xShearAxis, _xBinWidth);
                    IAxis Yaxis = GetAxis(_yShearAxis, _yBinWidth);

                    //calculate alpha
                    AlphaFactory afactory = new AlphaFactory();
                    Alpha        alpha    = (Alpha)afactory.CreateAlpha(_unifiedData, AlphaFilterMethod.Coincident, upperws, lowerws, Xaxis, Yaxis);
                    alpha.SourceDataSet = this.DisplayName;
                    alpha.CalculateAlpha();

                    string xBin = string.Empty;
                    string yBin = string.Empty;

                    if (Xaxis.AxisType == AxisType.WD)
                    {
                        var wdaxis = (WindDirectionAxis)Xaxis;
                        xBin = " " + wdaxis.BinWidth.ToString() + " deg";
                    }
                    if (Xaxis.AxisType == AxisType.WS)
                    {
                        var wsaxis = (WindSpeedAxis)Xaxis;
                        xBin = " " + wsaxis.BinWidth.ToString() + " m/s";
                    }
                    if (Yaxis.AxisType == AxisType.WD)
                    {
                        var wdaxis = (WindDirectionAxis)Yaxis;
                        yBin = " " + wdaxis.BinWidth.ToString() + " deg";
                    }
                    if (Yaxis.AxisType == AxisType.WS)
                    {
                        var wsaxis = (WindSpeedAxis)Yaxis;
                        yBin = " " + wsaxis.BinWidth.ToString() + " m/s";
                    }

                    //Set up column metadata for the summary run
                    summary = new XbyYShearStationSummary(ColumnCollection, _unifiedData.AsDataView(), 30, 10, 2, alpha);

                    summary.CreateReport(filename);
                    SummaryIsProcessing = false;
                }
                catch (ApplicationException e)
                {
                    MessageBox.Show("Error calculating station summary: " + e.Message + " " + e.Source);
                    StreamWriter fs = new StreamWriter(Path.GetDirectoryName(filename) + @"\LOG_" + Path.GetFileNameWithoutExtension(filename) + ".txt", false);
                    summary.log.ForEach(c => fs.WriteLine(c));
                    fs.Close();
                }
                finally
                {
                    SummaryIsProcessing = false;
                }
            };
            worker.RunWorkerAsync();
        }
Esempio n. 36
0
        private void buttonSubmit_Click(object sender, EventArgs e)
        {
            //bankUserDB.Remove(bankUserM); //remove the data from file to rewrite latest changes on file

            if (radioButtonDeposit.Checked) //deposit
            {
                bankUserM.Deposit = true;
                depositForm       = new Deposit_Withdraw(bankUserM);
                depositForm.Text  = "Deposit";
                this.Visible      = false;

                bankUserM    = depositForm.getDep_WidthData(); //calls Deposit Form and after is done, it returns Class
                this.Visible = true;
            }
            else if (radioButtonWithdrawl.Checked)  //withdraw
            {
                bankUserM.Deposit = false;
                depositForm       = new Deposit_Withdraw(bankUserM);
                depositForm.Text  = "Withdraw";
                this.Visible      = false;

                bankUserM    = depositForm.getDep_WidthData(); //calls Deposit Form and after is done, it returns Class
                this.Visible = true;
            }
            else if (radioButtonBalance.Checked) //balance
            {
                Balance balanceForm = new Balance(bankUserM);
                this.Visible = false;
                balanceForm.ShowDialog();
                this.Visible = true;
            }
            else if (radioButtonTransfer.Checked)  //transfer
            {
                transferForm = new TransferForm(bankUserM);
                this.Visible = false;

                bankUserM    = transferForm.getTransferData(); //this calls method in transfer form which calls the showdialog form
                this.Visible = true;
            }
            else
            {
                string       message = "Are you sure you want to Logg Off? ";
                DialogResult button  =
                    MessageBox.Show(message, "Logg Off!",
                                    MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

                if (button == DialogResult.Yes)
                {
                    for (int x = 0; x < bankUserDB.Count; x++)  //Loop will save changes to list which will update the text file
                    {
                        if (bankUserM.AccountNumber == bankUserDB[x].AccountNumber)
                        {
                            bankUserDB[x].CheckingBalance = bankUserM.CheckingBalance;
                            bankUserDB[x].SavingBalance   = bankUserM.SavingBalance;

                            Console.WriteLine("Main loop.. " + bankUserDB[x].UserID + "  " + bankUserDB[x].SavingBalance + " " + bankUserDB[x].CheckingBalance);
                            break;
                        }
                    }

                    BankUserDB.SaveProducts(bankUserDB);

                    this.Visible = false;
                    logInForm.Show();
                }
            }
        }
        public FrmAnaliselookaHead(string idir, ExternalCommandData irevit, DataTable dtDownload)
        {
            revit = irevit;
            InitializeComponent();
            ConstruirQtdePSA();
            dtpInicio.Value = DateTime.Today.AddDays(-30);
            dtpTermino.Value = DateTime.Today;
            manipulacao = new Plan_servico_amoNegocio(idir);
            dtGrid.Columns.Add("INSUMO_ID", typeof(int));
            dtGrid.Columns.Add("INSUMO", typeof(string));
            dtGrid.Columns.Add("UNID", typeof(string));
            dtGrid.Columns.Add("QTDE_TOTAL_ENTRADA", typeof(double));
            dtGrid.Columns.Add("QTDE_CONSUMIDA", typeof(double));
            dtGrid.Columns.Add("QTDE_SOLICITADA_LOOK_A_HEAD", typeof(double));
            dtGrid.Columns.Add("SALDO", typeof(double));
            dtGrid.Columns["SALDO"].Expression = "QTDE_TOTAL_ENTRADA - QTDE_CONSUMIDA - QTDE_SOLICITADA_LOOK_A_HEAD";

            dtGrid.Columns.Add("SERVICO_ID", typeof(string));

            dtGrid.Columns.Add("CONSUMO_INSUMO", typeof(double));
            dtGrid.Columns.Add("ORIGEM", typeof(int));

            DataGridViewCellStyle formatoNumerico = new DataGridViewCellStyle();
            formatoNumerico.Format = "N2";
            ds.Tables.Add(dtGrid);
            bs.DataSource = ds;
            bs.DataMember = dtGrid.TableName;
            dataGridView1.DataSource = bs;
            dataGridView1.Columns["INSUMO_ID"].Width = 90;
            dataGridView1.Columns["INSUMO_ID"].HeaderText = "Insumo";
            dataGridView1.Columns["INSUMO"].Width = 200;
            dataGridView1.Columns["INSUMO"].HeaderText = "Desc. Inusmo";

            dataGridView1.Columns["QTDE_TOTAL_ENTRADA"].Width = 120;
            dataGridView1.Columns["QTDE_TOTAL_ENTRADA"].HeaderText = "Entrada";
            dataGridView1.Columns["QTDE_TOTAL_ENTRADA"].DefaultCellStyle = formatoNumerico;

            dataGridView1.Columns["QTDE_CONSUMIDA"].Width = 120;
            dataGridView1.Columns["QTDE_CONSUMIDA"].HeaderText = "Saída";
            dataGridView1.Columns["QTDE_CONSUMIDA"].DefaultCellStyle = formatoNumerico;

            dataGridView1.Columns["QTDE_SOLICITADA_LOOK_A_HEAD"].Width = 120;
            dataGridView1.Columns["QTDE_SOLICITADA_LOOK_A_HEAD"].HeaderText = "Lookahead";
            dataGridView1.Columns["QTDE_SOLICITADA_LOOK_A_HEAD"].DefaultCellStyle = formatoNumerico;

            dataGridView1.Columns["SALDO"].Width = 120;
            dataGridView1.Columns["SALDO"].HeaderText = "Saldo";
            dataGridView1.Columns["SALDO"].DefaultCellStyle = formatoNumerico;


            FrmProcurar procurar = new FrmProcurar();
            StringBuilder sb = new StringBuilder();

            sb.Append("    select ");
            sb.Append("   obra_id,  ");
            sb.Append("   obra  ");
            sb.Append("   ");
            sb.Append(" from obra ");
            ResultadoProcura rp = new ResultadoProcura();
            rp = procurar.Pesquisar(idir, "Escolher Obra",
                                      sb.ToString(), "Obra;Desc. Obra;",
                                                    "80;250;");



            EscolherData escolherData1 = new EscolherData();
            DialogResult resultado1 = escolherData1.inputar(ref mesAnalise, "Escolha o mes de análise", ref continuar);


            EscolherData escolherData = new EscolherData();
            DialogResult resultado = escolherData.inputar(ref diaAnalise, "Escolha o dia", ref continuar);

            if (continuar)
            {
                if (procurar.resultadoProcura.fResultadoProcura)
                {
                    atualizando = true;
                    cmbServico.SelectedItem = 0;
                    foreach (DataRow dr2 in dtDownload.Rows)
                    {
                        cmbServico.Items.Add(dr2["UAU_COMP"].ToString());
                    }
                    atualizando = false;
                    BuscarInsumoLookAHead(dtDownload, diaAnalise, Convert.ToInt32( rp.vCampo));
                    BuscarQtdePSA(dtDownload);                  
                }
            }
            escolherData.Dispose();
            uiApp = revit.Application;
            uiDoc = uiApp.ActiveUIDocument.Document;
            Selection sel = uiApp.ActiveUIDocument.Selection;
            Util.uiDoc = uiDoc;
            selecao = new revitDB.FilteredElementCollector(uiDoc).OfClass(typeof(Autodesk.Revit.DB.View));

            foreach (revitDB.View view in selecao)
            {
                try
                {
                    if (view.AreGraphicsOverridesAllowed())
                        if (view.LookupParameter("tocVistaAvanco").AsValueString() == "Sim")
                            vistasDeAvanco.Add(view);
                }
                catch
                {

                }

            }

            preenchimentoId = (Util.FindElementByName(typeof(revitDB.Material), "Previsto") as revitDB.Material).SurfacePatternId;
            /* orgRestricao= Util.GetOverrideGraphicSettings(Util.GetColorRevit(CorLinhaResticao),
                                                          Util.GetColorRevit(CorSuperficieRestricao),
                                                          preenchimentoId, 0);*/
        }
        private void btnPost_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalFunctions.checkRights("tsmSalesOrder", "Post"))
                {
                    return;
                }

                foreach (DataRow _drStatus in loSalesOrder.getSalesOrderStatus(dgvList.CurrentRow.Cells[0].Value.ToString()).Rows)
                {
                    if (_drStatus["Final"].ToString() == "N")
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("Sales Order must be FINALIZED!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    else if (_drStatus["Cancel"].ToString() == "Y")
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("You cannot post a CANCELLED Sales Order!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    else if (_drStatus["Post"].ToString() == "Y")
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("Sales Order is already POSTED!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    else if (decimal.Parse(_drStatus["TotalQtyOut"].ToString()) <= 0)
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("Total Qty OUT must be greater than or equal to zero(0)!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    /*
                    if (_drStatus[4].ToString() == GlobalVariables.Username)
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("You cannot FINALIZE a Sales Order you preprared!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    */
                    /*
                    if (_drStatus["SWId"].ToString() == "")
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("Stocks Withdrawal must precedes finalization!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    */
                }

                if (dgvList.Rows.Count > 0)
                {
                    DialogResult _dr = new DialogResult();
                    MessageBoxUI _mb = new MessageBoxUI("Are sure you want to continue posting this Sales Order record?", GlobalVariables.Icons.QuestionMark, GlobalVariables.Buttons.YesNo);
                    _mb.ShowDialog();
                    _dr = _mb.Operation;
                    if (_dr == DialogResult.Yes)
                    {
                        if (loSalesOrder.post(dgvList.CurrentRow.Cells[0].Value.ToString()))
                        {
                            foreach (DataRow _drSO in loSalesOrder.getAllData("", dgvList.CurrentRow.Cells[0].Value.ToString(), "").Rows)
                            {
                                insertJournalEntry(dgvList.CurrentRow.Cells[0].Value.ToString(), decimal.Parse(_drSO["Total Amount"].ToString()),
                                    _drSO["CustomerId"].ToString(), _drSO["Customer"].ToString(), "Sales from Sales Order (SOId:" + _drSO["Id"].ToString() + ").");
                            }
           
                            MessageBoxUI _mb1 = new MessageBoxUI("Sales Order record has been successfully posted!", GlobalVariables.Icons.Information, GlobalVariables.Buttons.OK);
                            _mb1.ShowDialog();
                            //previewSalesOrderDetail(dgvList.CurrentRow.Cells[0].Value.ToString());
                            //sendEmailToCreator();
                            refresh();
                        }
                        else
                        {

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessageUI em = new ErrorMessageUI(ex.Message, this.Name, "btnPost_Click");
                em.ShowDialog();
                return;
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalFunctions.checkRights("tsmSalesOrder", "Cancel"))
                {
                    return;
                }
                
                foreach (DataRow _drStatus in loSalesOrder.getSalesOrderStatus(dgvList.CurrentRow.Cells[0].Value.ToString()).Rows)
                {
                    if (_drStatus["Final"].ToString() == "N")
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("Sales Order must be FINALIZED to be cancelled!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    if (_drStatus["Cancel"].ToString() == "Y")
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("Sales Order is already cancelled!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    if (_drStatus["Post"].ToString() == "Y")
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("You cannot cancel a POSTED Sales Order!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    /*
                    if (_drStatus[1].ToString() == GlobalVariables.Username || _drStatus[4].ToString() == GlobalVariables.Username)
                    {
                        MessageBoxUI _mbStatus = new MessageBoxUI("You cannot CANCEL a Sales Order you preprared/finalized!", GlobalVariables.Icons.Warning, GlobalVariables.Buttons.OK);
                        _mbStatus.ShowDialog();
                        return;
                    }
                    */
                }
                if (dgvList.Rows.Count > 0)
                {
                    DialogResult _dr = new DialogResult();
                    MessageBoxUI _mb = new MessageBoxUI("Are sure you want to continue cancelling this Sales Order record?", GlobalVariables.Icons.QuestionMark, GlobalVariables.Buttons.YesNo);
                    _mb.ShowDialog();
                    _dr = _mb.Operation;
                    if (_dr == DialogResult.Yes)
                    {
                        SalesCancelReasonUI loSalesCancelReason = new SalesCancelReasonUI();
                        loSalesCancelReason.ShowDialog();
                        if (loSalesCancelReason.lReason == "")
                        {
                            MessageBoxUI _mb1 = new MessageBoxUI("You must have a reason in cancelling entry!", GlobalVariables.Icons.Error, GlobalVariables.Buttons.OK);
                            _mb1.ShowDialog();
                            return;
                        }
                        else
                        {
                            if (loSalesOrder.cancel(dgvList.CurrentRow.Cells[0].Value.ToString(), loSalesCancelReason.lReason))
                            {
                                foreach (DataRow _drSO in loJournalEntry.getJournalEntryBySOId(dgvList.CurrentRow.Cells[0].Value.ToString()).Rows)
                                {
                                    loJournalEntry.cancel(_drSO[0].ToString(), loSalesCancelReason.lReason);
                                }

                                MessageBoxUI _mb1 = new MessageBoxUI("Sales Order record has been successfully cancelled!", GlobalVariables.Icons.Information, GlobalVariables.Buttons.OK);
                                _mb1.ShowDialog();
                                refresh();
                            }
                            else
                            {

                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMessageUI em = new ErrorMessageUI(ex.Message, this.Name, "btnCancel_Click");
                em.ShowDialog();
                return;
            }
        }
Esempio n. 40
0
        private void calculateButton_Click(object sender, EventArgs e)
        {
            if (FreeClass.body == null) {
                MessageBox.Show("Тело не было задано. Невозможно произвести вычисления");
                return;
            }

            if (singleBuildRadioButton.Checked)
            {
                cells = new NandMRectangleCells(FreeClass.body);
                cells.SetAccuracy(Convert.ToInt16(textBox4.Text));
                cells.SetCellsV(FreeClass.body.GetV() * Convert.ToDouble(textBox3.Text.Replace('.', ',')) / 100);
                if (TwoInNRadioButton.Checked)
                {
                    double buff = Convert.ToInt16(textBox1.Text);
                    if (buff % 2 == 0)
                    {
                        buff = Math.Sqrt(Math.Pow(2, buff));
                        cells.SetColumnsNumber(Convert.ToInt16(buff));
                        cells.SetRowsNumber(Convert.ToInt16(buff));
                    }
                    else
                    {
                        buff = Math.Sqrt(Math.Pow(2, buff - 1));
                        cells.SetColumnsNumber(Convert.ToInt16(buff) * 2);
                        cells.SetRowsNumber(Convert.ToInt16(buff));
                    }
                }
                else if (SquareMatrixRadioButton.Checked)
                {
                    cells.SetColumnsNumber(Convert.ToInt16(textBox1.Text));
                    cells.SetRowsNumber(Convert.ToInt16(textBox1.Text));
                }
                else
                {
                    cells.SetColumnsNumber(Convert.ToInt16(textBox1.Text));
                    cells.SetRowsNumber(Convert.ToInt16(textBox2.Text));
                }

                cells.Calculation();

                if (!cells.isAvailable()) { MessageBox.Show("Решение не было найдено"); return; }

                resultBox.Clear();
                resultBox.Text += "Обьём цельного тела" + FreeClass.body.GetV(); resultBox.Text += Environment.NewLine;
                textResultsCellsRectangelNaM(resultBox);

            }
            else if (loopBuildRadioButton.Checked)
            {
                resultBox.Clear();
                resultBox.Text += "Обьём цельного тела" + FreeClass.body.GetV(); resultBox.Text += Environment.NewLine;
                if (SquareMatrixRadioButton.Checked)
                {
                    matrixLoopCalculation();
                }
                else if (TwoInNRadioButton.Checked)
                {
                    int start, end, step;
                    start = Convert.ToInt16(GetStartPoint());
                    end = Convert.ToInt16(GetEndPoint());
                    step = Convert.ToInt16(GetStep());
                    double partOfVolume = Convert.ToDouble(GetVolume());

                    for (int i = start, j = 1; i <= end; i = i + step, j++)
                    {
                        cells = new NandMRectangleCells(FreeClass.body);
                        cells.SetAccuracy(Convert.ToInt16(GetAccuracy()));
                        cells.SetCellsV(FreeClass.body.GetV() * partOfVolume / 100);

                        if (i % 2 == 0)
                        {
                            double buff = Math.Sqrt(Math.Pow(2, i));
                            cells.SetColumnsNumber(Convert.ToInt16(buff));
                            cells.SetRowsNumber(Convert.ToInt16(buff));
                        }
                        else
                        {
                            double buff = Math.Sqrt(Math.Pow(2, i - 1));
                            cells.SetColumnsNumber(Convert.ToInt16(buff) * 2);
                            cells.SetRowsNumber(Convert.ToInt16(buff));
                        }

                        cells.Calculation();
                        if (!cells.isAvailable())
                        {
                            DialogResult dialogResult = MessageBox.Show("Не удалось решить структуру при определённых условиях." +
                                " запустить следующий набор данных?",
                             "Предупреждение", MessageBoxButtons.YesNo);
                            if (dialogResult == DialogResult.Yes) { continue; }
                            else if (dialogResult == DialogResult.No) { return; }
                        }

                        textResultsCellsRectangelNaM(resultBox);

                    }

                }
                else
                {
                    int start1, start2, end, step;
                    start1 = Convert.ToInt16(GetStartPoint());
                    start2 = Convert.ToInt16(GetEndPoint());
                    end = Convert.ToInt16(GetMiddlePoint());
                    step = Convert.ToInt16(GetStep());
                    double partOfVolume = Convert.ToDouble(GetVolume());

                    //withoutIterationResearch();

                    for (int i = start1, j = 1; i <= end; i = i + step, j++, start2 = start2 + step)
                    {
                        cells = new NandMRectangleCells(FreeClass.body);

                        cells.SetAccuracy(Convert.ToInt16(GetAccuracy()));
                        cells.SetCellsV(FreeClass.body.GetV() * partOfVolume / 100);

                        cells.SetColumnsNumber(i); cells.SetRowsNumber(start2);

                        cells.Calculation();
                        if (!cells.isAvailable())
                        {
                            DialogResult dialogResult = MessageBox.Show("Не удалось решить структуру при определённых условиях." +
                                " запустить следующий набор данных?",
                             "Предупреждение", MessageBoxButtons.YesNo);
                            if (dialogResult == DialogResult.Yes) { continue; }
                            else if (dialogResult == DialogResult.No) { return; }
                        }

                        textResultsCellsRectangelNaM(resultBox);
                    }

                }
            }
        }
Esempio n. 41
0
        private void dgvInProgressCurriculumEnquiries_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            Data.Models.Enquiry CurrentEnquiry = (Data.Models.Enquiry)enquiryInprogressBindingSource.Current;
            CurriculumEnquiry CE = (CurriculumEnquiry)dgvInProgressCurriculumEnquiries.Rows[e.RowIndex].DataBoundItem;
            switch (e.ColumnIndex)
            {
                case 1:
                    if (CE.EnquiryStatusID != (int)EnumEnquiryStatuses.Enquiry_Closed)
                    {
                        DialogResult Rtn = MessageBox.Show("Are you sure that you wish to Close this Enquiry Item?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (Rtn == DialogResult.Yes)
                        {
                            using (var Dbconnection = new MCDEntities())
                            {
                                Dbconnection.CurriculumEnquiries.Attach(CE);
                                CE.EnquiryStatusID = (int)EnumEnquiryStatuses.Enquiry_Closed;
                                CE.LastUpdated = DateTime.Now;
                                Dbconnection.Entry<CurriculumEnquiry>(CE).State = System.Data.Entity.EntityState.Modified;
                                Dbconnection.SaveChanges();
                                EquiryHistory hist = new EquiryHistory
                                {
                                    EnquiryID = CurrentEnquiry.EnquiryID,
                                    EmployeeID = this.CurrentEmployeeLoggedIn.EmployeeID,
                                    LookupEquiyHistoryTypeID = (int)EnumEquiryHistoryTypes.Curriculum_Enquiry_Item_Closed,
                                    DateEnquiryUpdated = DateTime.Now,
                                    EnquiryNotes = "Curriculum Enquiry Line Item Closed, Item Removed - " + CE.Curriculum.CurriculumName + "- For Enquiry Ref: " + CurrentEnquiry.EnquiryID
                                };

                                Dbconnection.EquiryHistories.Add(hist);
                                int IsSaved = Dbconnection.SaveChanges();

                                refreshInProgressEnquiry(CurrentSelectedEnquiryID);
                            };
                        }
                    }
                    else
                    {
                        DialogResult Rtn = MessageBox.Show("Are you sure that you wish to Close this Enquiry Item?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (Rtn == DialogResult.Yes)
                        {
                            using (var Dbconnection = new MCDEntities())
                            {
                                Dbconnection.CurriculumEnquiries.Attach(CE);
                                CE.EnquiryStatusID = (int)EnumEnquiryStatuses.Enrollment_In_Progress;
                                CE.LastUpdated = DateTime.Now;
                                Dbconnection.Entry<CurriculumEnquiry>(CE).State = System.Data.Entity.EntityState.Modified;
                                Dbconnection.SaveChanges();
                                EquiryHistory hist = new EquiryHistory
                                {
                                    EnquiryID = CurrentEnquiry.EnquiryID,
                                    EmployeeID = this.CurrentEmployeeLoggedIn.EmployeeID,
                                    LookupEquiyHistoryTypeID = (int)EnumEquiryHistoryTypes.Curriculum_Enquiry_Item_Reinstated,
                                    DateEnquiryUpdated = DateTime.Now,
                                    EnquiryNotes = "Curriculum Enquiry Line Item Reinstated, Item Reinstated - " + CE.Curriculum.CurriculumName + "- For Enquiry Ref: " + CurrentEnquiry.EnquiryID
                                };

                                Dbconnection.EquiryHistories.Add(hist);
                                int IsSaved = Dbconnection.SaveChanges();

                                refreshInProgressEnquiry(CurrentSelectedEnquiryID);
                            };
                        }
                    }


                    break;
                case 6:
                    //if (CE.Curriculum.DepartmentID == (int)EnumDepartments.Apprenticeship)
                    //{
                    if (((Data.Models.Enquiry)enquiryInprogressBindingSource.Current).InitialConsultationComplete)
                    {
                        //gbInProgressEnquiryEnrrolmentQueries.Enabled = true;
                        DialogResult Rtn = MessageBox.Show("Do you have a copy of the individuals ID document or relevant details, These details are rquired to process initial enrollment! Else Select No and send an email Notification to the contact requesting these details.", "ID Document Requirement", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (Rtn == DialogResult.Yes)
                        {
                            using (var Dbconnection = new MCDEntities())
                            {
                                Dbconnection.CurriculumEnquiries.Attach(CE);
                                if (!(Dbconnection.Entry(CE).Collection(a => a.Enrollments).IsLoaded))
                                {
                                    Dbconnection.Entry(CE).Collection(a => a.Enrollments).Load();
                                }
                            };
                            if (CE.EnrollmentQuanity > CE.Enrollments.Count)
                            {
                                using (frmApprenticeshipEnrollmentFormV2 frm = new frmApprenticeshipEnrollmentFormV2())
                                {
                                    frm.CurrentCurriculumEnquiry = CE;
                                    frm.ShowDialog();
                                    curriculumEnquiryInprogressBindingSource.ResetCurrentItem();
                                    //this.refreshInProgressEnquiry(CurrentSelectedEnquiryID);

                                    if (frm.IsSuccessfullySaved)
                                    {
                                        DialogResult Rtn1 = MessageBox.Show("Do you wish to process this new enrollment now?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                                        if (Rtn1 == DialogResult.Yes)
                                        {
                                            using (frmEnrollmentInProgressV2 innerFrm = new frmEnrollmentInProgressV2())
                                            {
                                                innerFrm.CurrentEmployeeLoggedIn = this.CurrentEmployeeLoggedIn;
                                                innerFrm.CurrentEquiryID = this.CurrentSelectedEnquiryID;
                                                innerFrm.CurrentSelectedDepartment = (Common.Enum.EnumDepartments)CE.Curriculum.DepartmentID;
                                                innerFrm.CurrentEnrollmentID = frm.CurrentEnrollments.EnrollmentID;
                                                innerFrm.ShowDialog();
                                            }
                                            //using (frmEnrolmmentInprogress frmInner = new frmEnrolmmentInprogress())
                                            //{
                                            //    frmInner.CurrentEmployeeLoggedIn = this.CurrentEmployeeLoggedIn;
                                            //    frmInner.CurrentSelectedDepartment = (Common.Enum.EnumDepartments)CE.Curriculum.DepartmentID;
                                            //    // frmStudentCourseEnrollmentV2 frm7 = new frmStudentCourseEnrollmentV2();
                                            //    frmInner.ShowDialog();

                                                
                                            //}
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("Initial Consultation Is Not Yet Completed, Please complete before proceeding with the enrollment!", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        //gbInProgressEnquiryEnrrolmentQueries.Enabled = false;
                    }

                    //}
                    break;
                case 7:
                    //ensure that the Enrollments are refershed
                    using (var Dbconnection = new MCDEntities())
                    {
                        Dbconnection.CurriculumEnquiries.Attach(CE);
                        if (!(Dbconnection.Entry(CE).Collection(a => a.Enrollments).IsLoaded))
                        {
                            Dbconnection.Entry(CE).Collection(a => a.Enrollments).Load();
                        }
                    };
                    //IF any enrollments exists then open Selection list else Do Nothing.
                    if (CE.Enrollments.Count > 0)
                    {
                        //Open thje list of linked Enrollments that are in progress
                        using (frmEnrollmentSelectionForEquiry frm = new frmEnrollmentSelectionForEquiry())
                        {
                            frm.SelectedCurriculumEnquiryID = CE.CurriculumEnquiryID;
                            frm.ShowDialog();
                            if (frm.SelectedEnrollmentID != 0)
                            {
                                using (frmEnrollmentInProgressV2 innerFrm = new frmEnrollmentInProgressV2())
                                {
                                    innerFrm.CurrentEmployeeLoggedIn = this.CurrentEmployeeLoggedIn;
                                    innerFrm.CurrentEquiryID = this.CurrentSelectedEnquiryID;
                                    innerFrm.CurrentSelectedDepartment = (Common.Enum.EnumDepartments)CE.Curriculum.DepartmentID;
                                    innerFrm.CurrentEnrollmentID = frm.SelectedEnrollmentID;
                                    innerFrm.ShowDialog();
                                }
                            }
                        }
                    }
                    else
                    {
                        MessageBox.Show("There are currently no enrollments for this enquiry.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    break;
            }
        }
Esempio n. 42
0
        private void btnsubmit()
        {
            try
            {
                //if (cmbCustName.Text == "")
                //{
                //    MessageBox.Show("Select Party Name");
                //    cmbCustName.Focus();
                //}
                //else if (cmbPurchaseType.Text == "")
                //{
                //    MessageBox.Show("Select Sale type");
                //    cmbPurchaseType.Focus();
                //}
                //else if (LVFO.Items.Count == 0)
                //{
                //    MessageBox.Show("Please Enter atleast one item to generate sale return");
                //    txtItemName.Focus();
                //}
                //else
                //{
                DataTable dtpid = new DataTable();
                getcon();
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();
                DialogResult dr = MessageBox.Show("Do you want to Generate Bill?", "Bill", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dr == DialogResult.Yes)
                {
                    if (cmbPurchaseType.Text == "" || cmbCustName.Text == "" || cmbTerms.Text == "")
                    {
                        MessageBox.Show("Please fill all the information.");
                        if (cmbTerms.Text == "")
                        {
                            cmbTerms.Focus();
                        }

                        else if (cmbCustName.Text == "")
                        {
                            cmbCustName.Focus();
                        }
                        else if (cmbPurchaseType.Text == "")
                        {
                            cmbPurchaseType.Focus();
                        }
                    }
                    else
                    {
                        if (btnPayment.Text == "Update")
                        {
                            SqlCommand cmd2 = new SqlCommand("Update billproductmaster set isactive='0' where Bill_No='" + txtVchNo.Text + "' and BillType='PR'", con);
                            cmd2.ExecuteNonQuery();
                            for (int i = 0; i < LVFO.Items.Count; i++)
                            {
                                dtpid = conn.getdataset("Select Productid from productmaster where product_name='" + LVFO.Items[i].SubItems[0].Text.Replace(",", "") + "'");

                                SqlCommand cmd1 = new SqlCommand("INSERT INTO [BillProductMaster]([Bill_No],[Bill_Run_Date],[ProductName],[Pqty],[Bags],[Rate],[Per],[Amount],[DiscountPer],[Discountamt],[Tax],[Addtax],[Total],[isactive],[BillType],[productid])VALUES('" + txtVchNo.Text + "','" + Convert.ToDateTime(TxtBillDate.Text).ToString("dd/MMM/yyyy") + "','" + LVFO.Items[i].SubItems[0].Text + "','" + LVFO.Items[i].SubItems[1].Text + "','" + LVFO.Items[i].SubItems[2].Text + "','" + LVFO.Items[i].SubItems[3].Text + "','" + LVFO.Items[i].SubItems[4].Text + "','" + LVFO.Items[i].SubItems[5].Text + "','" + LVFO.Items[i].SubItems[6].Text.Replace(",", "") + "','" + LVFO.Items[i].SubItems[7].Text + "','" + LVFO.Items[i].SubItems[8].Text.Replace(",", "") + "','" + LVFO.Items[i].SubItems[9].Text.Replace(",", "") + "','" + LVFO.Items[i].SubItems[10].Text.Replace(",", "") + "',1,'PR','" + dtpid.Rows[0][0].ToString() + "')", con);
                                cmd1.ExecuteNonQuery();
                            }
                            SqlCommand cmd = new SqlCommand("UPDATE [BillMaster] SET [Bill_No] = '" + txtVchNo.Text + "',[Bill_Date] = '" + Convert.ToDateTime(TxtBillDate.Text).ToString("dd/MMM/yyyy") + "',[Terms] = '" + cmbTerms.Text + "',[ClientID] = '" + cmbCustName.SelectedValue + "',[SaleType] = '" + cmbPurchaseType.SelectedValue + "',[Count] = " + lbltotcount.Text + ",[TotalQty] = " + lbltotpqty.Text + ",[TotalBasic] = " + lblbasictot.Text + ",[TotalTax] =" + lbltaxtot.Text + " ,[TotalAddTax] =" + txtaddtax.Text + " ,[TotalDiscount] =" + lbltotaldiscount.Text + " ,[TotalNet] = " + Math.Round(Convert.ToDouble(TxtBillTotal.Text), 2).ToString("########.00") + ",[isactive]=1,[DispatchDetails]='" + txtdispatch.Text + "',[Remarks]='" + txtremarks.Text + "',[billtype]='PR',[CompanyId]=" + Master.companyId + " where Bill_No='" + txtVchNo.Text + "' and [billtype]='PR' and [CompanyId]=" + Master.companyId + "", con);
                            cmd.ExecuteNonQuery();
                            conn.execute("UPDATE [Ledger] SET [Date1]='" + Convert.ToDateTime(TxtBillDate.Text).ToString("dd/MMM/yyyy") + "',[TranType] = 'PurchaseReturn',[AccountID] = '" + cmbCustName.SelectedValue + "',[AccountName]='" + cmbCustName.Text + "' ,[Amount] = '" + Math.Round(Convert.ToDouble(TxtBillTotal.Text), 2).ToString("########.00") + "',[DC] = 'D',[CompanyId]=" + Master.companyId + " where [VoucherID]= '" + txtVchNo.Text + "' and [TranType] = 'PurchaseReturn' and CompanyId=" + Master.companyId + "");

                            ChangeNumbersToWords sh = new ChangeNumbersToWords();
                            String   s1             = Math.Round(Convert.ToDouble(TxtBillTotal.Text), 2).ToString("########.00");
                            string[] words          = s1.Split('.');


                            string str  = sh.changeToWords(words[0]);
                            string str1 = sh.changeToWords(words[1]);
                            if (str1 == " " || str1 == null || words[1] == "00")
                            {
                                str1 = "Zero ";
                            }
                            String inword = "In words: " + str + "and " + str1 + "Paise Only";
                            //Phrase inwrd = new Phrase(inword, _font2);

                            DataTable client = conn.getdataset("select * from clientmaster where isactive=1 and clientID='" + cmbCustName.SelectedValue + "'");
                            DataTable dt1    = conn.getdataset("select * from company WHERE isactive=1");
                            prn.execute("delete from printing");
                            int j = 1;

                            for (int i = 0; i < LVFO.Items.Count; i++)
                            {
                                try
                                {
                                    string qry = "INSERT INTO Printing(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19,T20,T21,T22,T23,T24,T25,T26,T27,T28,T29,T30,T31,T32,T33,T34,T35,T36,T37,T38,T39,T40,T41,T42,T43,T44,T45,T46,T47,T48,T49,T50,T51,T52,T53,T54,T55,T56,T57,T58,T59,T60,T61,T62,T63,T64,T65,T66,T67,T68,T69,T70,T71,T72,T73,T74,T75,T76,T77,T78,T79,T80)VALUES";
                                    qry += "('" + j++ + "','" + TxtBillNo.Text + "','" + TxtBillDate.Text + "','" + cmbTerms.Text + "','0','" + cmbCustName.Text + "','0','" + cmbPurchaseType.Text + "','" + LVFO.Items[i].SubItems[0].Text + "','" + LVFO.Items[i].SubItems[1].Text + "','" + LVFO.Items[i].SubItems[2].Text + "','" + LVFO.Items[i].SubItems[3].Text + "','" + LVFO.Items[i].SubItems[4].Text + "','" + LVFO.Items[i].SubItems[5].Text + "','" + LVFO.Items[i].SubItems[6].Text + "','" + LVFO.Items[i].SubItems[7].Text + "','" + LVFO.Items[i].SubItems[8].Text + "','" + LVFO.Items[i].SubItems[9].Text + "','" + LVFO.Items[i].SubItems[10].Text + "','" + LVFO.Items[i].SubItems[11].Text + "','" + LVFO.Items[i].SubItems[12].Text + "','" + LVFO.Items[i].SubItems[13].Text + "','" + LVFO.Items[i].SubItems[14].Text + "','" + lbltotcount.Text + "','" + lbltotpqty.Text + "','0','0','" + lblbasictot.Text + "','0','0','0','0','0','0','0','0','" + TxtBillTotal.Text + "','" + dt1.Rows[0][0].ToString() + "','" + dt1.Rows[0][1].ToString() + "','" + dt1.Rows[0][2].ToString() + "','" + dt1.Rows[0][3].ToString() + "','" + dt1.Rows[0][4].ToString() + "','" + dt1.Rows[0][5].ToString() + "','" + dt1.Rows[0][6].ToString() + "','" + dt1.Rows[0][7].ToString() + "','" + dt1.Rows[0][8].ToString() + "','" + dt1.Rows[0][9].ToString() + "','" + dt1.Rows[0][10].ToString() + "','" + dt1.Rows[0][11].ToString() + "','" + dt1.Rows[0][12].ToString() + "','" + dt1.Rows[0][13].ToString() + "','" + inword + "','0','0','0','0','0','" + txtremarks.Text + "','0','0','0','0','0','0','0','0','" + client.Rows[0][0].ToString() + "','" + client.Rows[0][1].ToString() + "','" + client.Rows[0][2].ToString() + "','" + client.Rows[0][3].ToString() + "','" + client.Rows[0][4].ToString() + "','" + client.Rows[0][5].ToString() + "','" + client.Rows[0][6].ToString() + "','" + client.Rows[0][7].ToString() + "','" + client.Rows[0][8].ToString() + "','" + client.Rows[0][9].ToString() + "','" + client.Rows[0][10].ToString() + "','" + client.Rows[0][11].ToString() + "','" + client.Rows[0][12].ToString() + "','" + client.Rows[0][13].ToString() + "')";
                                    prn.execute(qry);
                                }
                                catch
                                {
                                }
                            }
                            Print popup = new Print("Purchase Return");
                            popup.ShowDialog();
                            popup.Dispose();

                            clearitem();
                            clearall();
                            LVFO.Items.Clear();
                            MessageBox.Show("Data Updated Successfully.");

                            btnPayment.Text = "Save";
                            this.Hide();
                        }
                        else
                        {
                            getsr();
                            for (int i = 0; i < LVFO.Items.Count; i++)
                            {
                                dtpid = conn.getdataset("Select Productid from productmaster where product_name='" + LVFO.Items[i].SubItems[0].Text.Replace(",", "") + "'");

                                SqlCommand cmd1 = new SqlCommand("INSERT INTO [BillProductMaster]([Bill_No],[Bill_Run_Date],[ProductName],[Pqty],[Bags],[Rate],[Per],[Amount],[DiscountPer],[Discountamt],[Tax],[Addtax],[Total],[isactive],[BillType],[productid])VALUES('" + txtVchNo.Text + "','" + Convert.ToDateTime(TxtBillDate.Text).ToString("dd/MMM/yyyy") + "','" + LVFO.Items[i].SubItems[0].Text + "','" + LVFO.Items[i].SubItems[1].Text + "','" + LVFO.Items[i].SubItems[2].Text + "','" + LVFO.Items[i].SubItems[3].Text + "','" + LVFO.Items[i].SubItems[4].Text + "','" + LVFO.Items[i].SubItems[5].Text + "','" + LVFO.Items[i].SubItems[6].Text.Replace(",", "") + "','" + LVFO.Items[i].SubItems[7].Text + "','" + LVFO.Items[i].SubItems[8].Text.Replace(",", "") + "','" + LVFO.Items[i].SubItems[9].Text.Replace(",", "") + "','" + LVFO.Items[i].SubItems[10].Text.Replace(",", "") + "',1,'PR','" + dtpid.Rows[0][0].ToString() + "')", con);
                                //SqlCommand cmd1 = new SqlCommand("INSERT INTO [BillProductMaster]([VchNo],[BillNo],[BillRunDate],[ProductName],[Qty],[Free],[Rate],[Per],[BasicAmount],[DiscountPer],[Discount],[Vat],[AddVat],[Total],[isactive],[BillType])VALUES('" + txtVchNo.Text + "','"+TxtBillNo.Text+"','" + Convert.ToDateTime(TxtBillDate.Text).ToString("dd/MMM/yyyy") + "','" + LVFO.Items[i].SubItems[0].Text + "','" + LVFO.Items[i].SubItems[1].Text + "','" + LVFO.Items[i].SubItems[2].Text + "','" + LVFO.Items[i].SubItems[3].Text + "','" + LVFO.Items[i].SubItems[4].Text + "','" + LVFO.Items[i].SubItems[5].Text + "','" + LVFO.Items[i].SubItems[6].Text.Replace(",", "") + "','" + LVFO.Items[i].SubItems[7].Text + "','" + LVFO.Items[i].SubItems[8].Text.Replace(",", "") + "','" + LVFO.Items[i].SubItems[9].Text.Replace(",", "") + "','" + LVFO.Items[i].SubItems[10].Text.Replace(",", "") + "',1,'PR')", con);
                                cmd1.ExecuteNonQuery();
                            }
                            SqlCommand cmd = new SqlCommand("INSERT INTO [BillMaster]([Bill_No],[Bill_Date],[Terms],[ClientID],[SaleType],[Count],[TotalQty],[TotalBasic],[TotalTax],[TotalAddTax],[TotalDiscount],[TotalNet],[isactive],[DispatchDetails],[Remarks],[BillType],[CompanyId])VALUES('" + txtVchNo.Text + "','" + Convert.ToDateTime(TxtBillDate.Text).ToString("dd/MMM/yyyy") + "','" + cmbTerms.Text + "','" + cmbCustName.SelectedValue + "','" + cmbPurchaseType.SelectedValue + "'," + lbltotcount.Text + "," + lbltotpqty.Text + "," + lblbasictot.Text + "," + lbltaxtot.Text + "," + txtaddtax.Text + "," + lbltotaldiscount.Text + "," + Math.Round(Convert.ToDouble(TxtBillTotal.Text), 2).ToString("########.00") + ",1,'" + txtdispatch.Text + "','" + txtremarks.Text + "','PR'," + Master.companyId + ")", con);
                            cmd.ExecuteNonQuery();

                            conn.execute("INSERT INTO [Ledger]([VoucherID],[Date1],[TranType],[AccountID],[AccountName],[Amount],[DC],[CompanyId],[isActive]) values ('" + txtVchNo.Text + "','" + Convert.ToDateTime(TxtBillDate.Text).ToString("dd/MMM/yyyy") + "','PurchaseReturn','" + cmbCustName.SelectedValue + "','" + cmbCustName.Text + "','" + TxtBillTotal.Text + "','D'," + Master.companyId + ",1)");

                            ChangeNumbersToWords sh = new ChangeNumbersToWords();
                            String   s1             = Math.Round(Convert.ToDouble(TxtBillTotal.Text), 2).ToString("########.00");
                            string[] words          = s1.Split('.');


                            string str  = sh.changeToWords(words[0]);
                            string str1 = sh.changeToWords(words[1]);
                            if (str1 == " " || str1 == null || words[1] == "00")
                            {
                                str1 = "Zero ";
                            }
                            String inword = "In words: " + str + "and " + str1 + "Paise Only";

                            DataTable client = conn.getdataset("select * from clientmaster where isactive=1 and clientID='" + cmbCustName.SelectedValue + "'");
                            DataTable dt1    = conn.getdataset("select * from company WHERE isactive=1");
                            prn.execute("delete from printing");
                            int j = 1;

                            for (int i = 0; i < LVFO.Items.Count; i++)
                            {
                                try
                                {
                                    string qry = "INSERT INTO Printing(T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19,T20,T21,T22,T23,T24,T25,T26,T27,T28,T29,T30,T31,T32,T33,T34,T35,T36,T37,T38,T39,T40,T41,T42,T43,T44,T45,T46,T47,T48,T49,T50,T51,T52,T53,T54,T55,T56,T57,T58,T59,T60,T61,T62,T63,T64,T65,T66,T67,T68,T69,T70,T71,T72,T73,T74,T75,T76,T77,T78,T79,T80)VALUES";
                                    qry += "('" + j++ + "','" + TxtBillNo.Text + "','" + TxtBillDate.Text + "','" + cmbTerms.Text + "','0','" + cmbCustName.Text + "','0','" + cmbPurchaseType.Text + "','" + LVFO.Items[i].SubItems[0].Text + "','" + LVFO.Items[i].SubItems[1].Text + "','" + LVFO.Items[i].SubItems[2].Text + "','" + LVFO.Items[i].SubItems[3].Text + "','" + LVFO.Items[i].SubItems[4].Text + "','" + LVFO.Items[i].SubItems[5].Text + "','" + LVFO.Items[i].SubItems[6].Text + "','" + LVFO.Items[i].SubItems[7].Text + "','" + LVFO.Items[i].SubItems[8].Text + "','" + LVFO.Items[i].SubItems[9].Text + "','" + LVFO.Items[i].SubItems[10].Text + "','" + LVFO.Items[i].SubItems[11].Text + "','" + LVFO.Items[i].SubItems[12].Text + "','" + LVFO.Items[i].SubItems[13].Text + "','" + LVFO.Items[i].SubItems[14].Text + "','" + lbltotcount.Text + "','" + lbltotpqty.Text + "','0','0','" + lblbasictot.Text + "','0','0','0','0','0','0','0','0','" + TxtBillTotal.Text + "','" + dt1.Rows[0][0].ToString() + "','" + dt1.Rows[0][1].ToString() + "','" + dt1.Rows[0][2].ToString() + "','" + dt1.Rows[0][3].ToString() + "','" + dt1.Rows[0][4].ToString() + "','" + dt1.Rows[0][5].ToString() + "','" + dt1.Rows[0][6].ToString() + "','" + dt1.Rows[0][7].ToString() + "','" + dt1.Rows[0][8].ToString() + "','" + dt1.Rows[0][9].ToString() + "','" + dt1.Rows[0][10].ToString() + "','" + dt1.Rows[0][11].ToString() + "','" + dt1.Rows[0][12].ToString() + "','" + dt1.Rows[0][13].ToString() + "','" + inword + "','0','0','0','0','0','" + txtremarks.Text + "','0','0','0','0','0','0','0','0','" + client.Rows[0][0].ToString() + "','" + client.Rows[0][1].ToString() + "','" + client.Rows[0][2].ToString() + "','" + client.Rows[0][3].ToString() + "','" + client.Rows[0][4].ToString() + "','" + client.Rows[0][5].ToString() + "','" + client.Rows[0][6].ToString() + "','" + client.Rows[0][7].ToString() + "','" + client.Rows[0][8].ToString() + "','" + client.Rows[0][9].ToString() + "','" + client.Rows[0][10].ToString() + "','" + client.Rows[0][11].ToString() + "','" + client.Rows[0][12].ToString() + "','" + client.Rows[0][13].ToString() + "')";
                                    prn.execute(qry);
                                }
                                catch
                                {
                                }
                            }
                            Print popup = new Print("Purchase Return");
                            popup.ShowDialog();
                            popup.Dispose();

                            clearitem();
                            clearall();
                            LVFO.Items.Clear();
                            this.Hide();
                        }
                    }
                }
                else
                {
                    MessageBox.Show("please fill all information");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:" + ex.Message);
            }
            finally
            {
                con.Close();
            }
        }
        private DialogResult PromptForConnectionStringRebuild()
        {
            DialogResult res = AppMessages.DisplayMessage("Connection string and properties on form do not match. Do you want to rebuild the connection string?", this.Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);

            return(res);
        }
Esempio n. 44
0
        private void btnGenerateClick(object sender, EventArgs e)
        {
            String savedir = "C:\\Users\\Gun2sh\\Desktop\\Camera";
            Dictionary <DateTime, double> resultsMap = new Dictionary <DateTime, double>();
            DialogResult result = folderBrowserDialog1.ShowDialog(); // Show the dialog.

            if (result == DialogResult.OK)                           // Test result.
            {
                savedir = folderBrowserDialog1.SelectedPath;
            }
            try
            {
                string yearname = Path.GetFileName(Path.GetDirectoryName(FirstFilesEntries + pathseperator));
                if (Directory.Exists(savedir + pathseperator + yearname + pathseperator))
                {
                    Directory.Delete(savedir + pathseperator + yearname + pathseperator, true);
                }
                Directory.CreateDirectory(savedir + pathseperator + yearname + pathseperator);
                foreach (string stormName in Directory.GetDirectories(FirstFilesEntries))
                {
                    string strmname = Path.GetFileName(Path.GetDirectoryName(stormName + pathseperator));
                    if (Directory.Exists(savedir + pathseperator + yearname + pathseperator + strmname + pathseperator))
                    {
                        Directory.Delete(savedir + pathseperator + yearname + pathseperator + strmname + pathseperator, true);
                    }
                    Directory.CreateDirectory(savedir + pathseperator + yearname + pathseperator + strmname + pathseperator);
                    foreach (string firstDir in Directory.GetFiles(stormName))
                    {
                        //
                        StreamReader reader = new StreamReader(File.OpenRead(firstDir));
                        Dictionary <DateTime, double> obs1 = getDataFromCSV(reader);
                        lblyear.Text = obs1.Keys.ToList()[0].Year.ToString();
                        string filename = Path.GetFileName(firstDir);
                        if (File.Exists(SecondFilesEntries + pathseperator + filename))
                        {
                            StringBuilder csv = new StringBuilder();
                            csv.Append(String.Format("{0},{1}{2}", "date and time", "water level (m)", Environment.NewLine));
                            reader = new StreamReader(File.OpenRead(SecondFilesEntries + pathseperator + filename));
                            Dictionary <DateTime, double> obs2 = getDataFromCSV(reader);
                            foreach (DateTime dt in obs1.Keys)
                            {
                                double dtemp = obs1[dt] - obs2[dt];
                                if (!resultsMap.ContainsKey(dt))
                                {
                                    resultsMap.Add(dt, dtemp);
                                }
                                else
                                {
                                    if (resultsMap[dt] < dtemp)
                                    {
                                        resultsMap[dt] = dtemp;
                                    }
                                }
                            }
                            DateTime forhighestDT = DateTime.Now;
                            double   val          = 0.0;
                            foreach (DateTime dt in resultsMap.Keys)
                            {
                                if (chkHighest.Checked)
                                {
                                    if (val < resultsMap[dt])
                                    {
                                        forhighestDT = dt;
                                        val          = resultsMap[dt];
                                    }
                                }
                                else
                                {
                                    csv.Append(String.Format("{0},{1}{2}", dt.ToString("yyyy-MM-dd"), resultsMap[dt].ToString(), Environment.NewLine));
                                }
                            }
                            if (chkHighest.Checked)
                            {
                                csv.Append(String.Format("{0},{1}{2}", forhighestDT.ToString("yyyy-MM-dd"), val.ToString(), Environment.NewLine));
                            }


                            File.WriteAllText(savedir + pathseperator + yearname + pathseperator +
                                              strmname + pathseperator + filename, csv.ToString());
                        }
                    }
                }
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Esempio n. 45
0
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                if (this.ParentForm is Atiran.CustomDocking.Docking.Desk.DeskTab)
                {
                    if (((Atiran.CustomDocking.Docking.Desk.DeskTab) this.ParentForm).DockAreas ==
                        ((Atiran.CustomDocking.Docking.DockAreas)((Atiran.CustomDocking.Docking.DockAreas.DockLeft |
                                                                   Atiran.CustomDocking.Docking.DockAreas.DockRight))))
                    {
                        return(true);
                    }

                    if (((Atiran.CustomDocking.Docking.Desk.DeskTab) this.ParentForm).Kind == 1)
                    {
                        Atiran.UI.WindowsForms.MessageBoxes.MessageBoxWarning.state = 0;
                        DialogResult CloseAnsewr =
                            Atiran.UI.WindowsForms.MessageBoxes.CustomMessageForm.CustomMessageBox.Show("پيغام",
                                                                                                        "براي خروج از فرم اطمينان داريد؟", "w");
                        if (CloseAnsewr == DialogResult.Yes)
                        {
                            this.ParentForm.Close();
                        }

                        Atiran.UI.WindowsForms.MessageBoxes.MessageBoxWarning.state = 1;
                    }
                    else
                    {
                        this.ParentForm.Close();
                    }
                }
                else
                {
                    if (((UIElements.Form) this.ParentForm) != null &&
                        ((UIElements.Form) this.ParentForm).menuLuancherButton != null &&
                        ((UIElements.Form) this.ParentForm).menuLuancherButton.MenuIsShow)
                    {
                        ((UIElements.Form) this.ParentForm).menuLuancherButton.DisableMenu();
                        return(true);
                    }

                    if (((UIElements.Form) this.ParentForm) != null &&
                        ((UIElements.Form) this.ParentForm).tabBar != null)
                    {
                        if (((UIElements.Form) this.ParentForm).tabBar.CurrentTab.Kind == 1)
                        {
                            Atiran.UI.WindowsForms.MessageBoxes.MessageBoxWarning.state = 0;
                            DialogResult CloseAnsewr =
                                Atiran.UI.WindowsForms.MessageBoxes.CustomMessageForm.CustomMessageBox.Show("پيغام",
                                                                                                            "براي خروج از فرم اطمينان داريد؟", "w");
                            if (CloseAnsewr == DialogResult.Yes)
                            {
                                ((UIElements.Form) this.ParentForm).tabBar.RemoveTab(this.UcGuid);
                            }

                            Atiran.UI.WindowsForms.MessageBoxes.MessageBoxWarning.state = 1;
                        }
                        else
                        {
                            ((UIElements.Form) this.ParentForm).tabBar.RemoveTab(this.UcGuid);
                        }
                    }
                    else if (this.ParentForm != null)
                    {
                        this.ParentForm.Close();
                    }
                }

                return(true);
            }
            else if (keyData == Keys.Home)
            {
                if (this.ParentForm is Atiran.CustomDocking.Docking.Desk.DeskTab)
                {
                    var MyMnSt =
                        (System.Windows.Forms.MenuStrip) this.ParentForm.TopLevelControl.Controls.Find("MyMnSt", true)?[
                            0];
                    ShowDropDown(MyMnSt,
                                 this.ParentForm.ActiveControl.ToString(), true);
                    return(true);
                }
                else
                {
                    if ((UIElements.Form) this.ParentForm != null & ((UIElements.Form) this.ParentForm).menuLuancherButton != null)
                    {
                        ((UIElements.Form) this.ParentForm).menuLuancherButton?.ShowMenu();
                    }
                }
            }
            else if (keyData == (Keys.Alt | Keys.Home))
            {
                if (this.ParentForm is Atiran.CustomDocking.Docking.Desk.DeskTab)
                {
                    var MyMnSt =
                        (System.Windows.Forms.MenuStrip) this.ParentForm.TopLevelControl.Controls.Find("MyMnSt", true)?[
                            0];
                    ShowDropDown(MyMnSt,
                                 this.ParentForm.ActiveControl.ToString(), false /*, this.ParentForm.ActiveControl.Name*/);
                }
                else
                {
                    if ((UIElements.Form) this.ParentForm != null)
                    {
                        ((UIElements.EnvironmentHeader)((UIElements.Form) this.ParentForm).header)?.home.BackToHome();
                    }
                }
            }
            return(base.ProcessCmdKey(ref msg, keyData));
        }
Esempio n. 46
0
        public void Gravar(bool Mensagem_Gravar)
        {
            Compra compra;
            bool baixaEstoque = false;

            if (tb_codigo.Text == string.Empty)
            {
                compra = new Compra();
                compra.COM_OBS = "";
                compra.COM_DATA_CANCELADO = DateTime.Parse("01/01/1800");
            }
            else
            {
                compra = new Compra(int.Parse(tb_codigo.Text),1);
            }

            try
            {
                compra.COM_CLIENTE_FORNECEDOR = int.Parse(cb_cliente.SelectedValue.ToString());
            }
            catch (Exception)
            {
                compra.COM_CLIENTE_FORNECEDOR = 0;
            }

            compra.COM_LANCAMENTO = 1;

            try
            {
                compra.COM_DATA = DateTime.Parse(tb_data.Text);
            }
            catch (Exception)
            {
                compra.COM_DATA = DateTime.Now;
            }
            compra.COM_ALTERACAO = DateTime.Now;

            if (rb_nao_gerar.Checked)
            {
                compra.COM_TIPO_PAGTO = 0;
            }
            else if (rb_avista.Checked)
            {
                compra.COM_TIPO_PAGTO = 1;
            }
            else
            {
                compra.COM_TIPO_PAGTO = 2;
            }
            compra.COM_OUT_DESPESAS = float.Parse(tb_out_desp.Text);
            compra.COM_ACRESCIMO = float.Parse(tb_acresc.Text);
            compra.COM_DESCONTO = float.Parse(tb_desc.Text);
            compra.COM_TOTAL = float.Parse(tb_total.Text);
            compra.COM_TIPO_MOVIMENTO = rb_orcamento.Checked ? 0 : rb_venda.Checked ? 1 : -1; 
            //ORCAMENTO = 0 , VENDA = 1, ERROR = -1

            string SqlVenda = "BEGIN TRANSACTION ";
            for(int i = 0; i < dgv_produtos.RowCount; i++)
            {
                double qtd = double.Parse(dgv_produtos["PC_QTDE_FORMATADO", i].Value.ToString());
                int cod_prod = int.Parse(dgv_produtos["PC_PRODUTO_FORMATADO", i].Value.ToString());
                SqlVenda += string.Format(@" IF (SELECT 1 FROM Produto WHERE PRO_CODIGO = {0} AND (PRO_ESTOQUE - {1}) >= 0) = 1
	                                            BEGIN
		                                            UPDATE Produto SET PRO_ESTOQUE = (PRO_ESTOQUE - {1}) WHERE PRO_CODIGO = {0}
		                                            SELECT 1 as Aviso
                                                    RETURN
	                                            END
                                            ELSE
	                                            BEGIN 
		                                            SELECT 0 as Aviso
                                                    ROLLBACK TRANSACTION
                                                    RETURN
	                                            END",cod_prod, qtd);
            }

            SqlVenda += " COMMIT TRANSACTION ";

            if (rb_venda.Enabled == true && rb_venda.Checked == true)
            {
                if (compra.BaixaEstoque(SqlVenda) == 0)
                {
                    MessageBox.Show("Não há produto suficiente para esta transação!", "Joincar", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                baixaEstoque = true;
            }
            
            grava_historico(compra,baixaEstoque);

            Log log = new Log();
            log.LOG_USUARIO = Global.FUN_CODIGO;
            log.LOG_DATA = DateTime.Now;
            log.LOG_TELA = this.Text;
            if (tb_codigo.Text == string.Empty)
            {
                log.LOG_DESCRICAO = "Cadastrou a compra de código: " + compra.COM_CODIGO.ToString() + " e cliente: " + cb_cliente.Text + ".";
            }
            else
            {
                log.LOG_DESCRICAO = "Alterou a compra de código: " + compra.COM_CODIGO.ToString() + " e cliente: " + cb_cliente.Text + ".";
            }
            log.Save();

            if (Configuracoes.Default.Mensagem_Gravar == true && Mensagem_Gravar == true)
            {
                if (tb_codigo.Text == string.Empty)
                {
                    MessageBox.Show("Cadastro efetuado com sucesso!", "Joincar", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Alteração efetuada com sucesso!", "Joincar", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            Ativar_Desativar(false);

            tb_codigo.Text = compra.COM_CODIGO.ToString();
            tb_codigo.Enabled = false;
            btn_cancelar.Enabled = true;
            dgv_produtos.Enabled = true;

            DialogResult print = MessageBox.Show("Deseja imprimir esta venda?", "Joincar", MessageBoxButtons.YesNo);
            if (print == DialogResult.Yes)
            {
                Imprimir();
            }

            cb_cliente.Focus();
        }
Esempio n. 47
0
        //マウスボタンが押されたとき、、、
        private void MainForm_MouseDown(object sender, MouseEventArgs e)
        {
            //左ボタンでなければ、、、
            if (e.Button != MouseButtons.Left)
            {
                return;
            }
            //マウスの位置を保存する
            mousePoint = e.Location;
            //現在のゲームによって見分ける
            switch (nowGameType)
            {
            case GameType.Title:    //タイトル画面
            {
                //ゲームスタートならば、、、
                if (WindowSize.Width / 2 - 100 <= mousePoint.X && mousePoint.X <= WindowSize.Width / 2 + 100 &&
                    200 <= mousePoint.Y && mousePoint.Y <= 230)
                {
                    nowGameType = GameType.Game;
                    ShotNumber  = 0;
                    gameStopWatch.Reset();
                    gameStopWatch.Start();
                }
                else if (WindowSize.Width / 2 - 100 <= mousePoint.X && mousePoint.X <= WindowSize.Width / 2 + 100 &&
                         250 <= mousePoint.Y && mousePoint.Y <= 280)   //ハイスコアならば、、、
                {
                    nowGameType = GameType.Hiscore;
                }
                else if (WindowSize.Width / 2 - 100 <= mousePoint.X && mousePoint.X <= WindowSize.Width / 2 + 100 &&
                         300 <= mousePoint.Y && mousePoint.Y <= 330)   //終了ならば、、、
                {
                    Application.Exit();
                }
                break;
            }

            case GameType.Game:    //ゲーム中
            {
                //自分の基地をクリックしたならば、、、
                if (myRectangle.X <= mousePoint.X && mousePoint.X <= myRectangle.Right &&
                    myRectangle.Y <= mousePoint.Y && mousePoint.Y <= myRectangle.Bottom)
                {
                    //ゲーム中のさまざまな処理を一時停止させる。
                    bool timeSW = timeStopwatch.IsRunning;
                    timeStopwatch.Stop();
                    gameStopWatch.Stop();
                    //ユーザーに質問する
                    DialogResult ans = MessageBox.Show("ゲームを終了しますか。", "質問",
                                                       MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
                    if (ans == DialogResult.Yes)
                    {
                        nowGameType = GameType.Title;
                    }
                    //ゲーム中のさまざな処理を再開させる。
                    gameStopWatch.Start();
                    if (timeSW)
                    {
                        timeStopwatch.Start();
                    }
                    break;
                }
                //指示線の長さから砲弾の初速度を計算する
                v0 = Math.Sqrt(Math.Pow(myRectangle.X + (myRectangle.Width / 2) - mousePoint.X - mousePoint.X, 2) +
                               Math.Pow(myRectangle.Y + (myRectangle.Height / 2) - mousePoint.Y, 2)) * MouseVelocity;
                //指示線の角度から砲弾発射角度を計算する
                angle = (180 * Math.PI / 180) -
                        Math.Atan2(myRectangle.Y + (myRectangle.Height / 2) - mousePoint.Y,
                                   myRectangle.X + (myRectangle.Width / 2) - mousePoint.X);
                //砲弾シミュレート開始
                timeStopwatch.Reset();
                timeStopwatch.Start();
                //弾を発射した回数を増やす
                ShotNumber++;
                break;
            }

            case GameType.Hiscore:    //ハイスコア画面
                nowGameType = GameType.Title;
                break;
            }
        }
Esempio n. 48
0
        private void Button1_Click(object sender, EventArgs e)
        {
            if (this.selected_com == null)
            {
                MessageBox.Show("comポートを選んでください");
                return;
            }
            if (this.button1_flag == false && this.my_all_data.Count > 0)
            {
                DialogResult my_result = MessageBox.Show("今のグラフに描かれているデータは消えますがよろしいですか?", "question", MessageBoxButtons.YesNo);
                if (my_result == DialogResult.Yes)
                {                   //すべて初期化(エラー起きやすい)
                    this.my_all_data.Clear();
                    //this.chart1.Series.Remove(this.class_my_gra.which_main_series());
                    //this.class_my_gra = new MyGraph(this.chart1);
                    this._cancellationtoken.Cancel();
                    Thread.Sleep(300);
                    this._cancellationtoken.Dispose();
                    this._cancellationtoken    = new CancellationTokenSource();
                    this.parent_manager_called = false;
                    this.class_my_starttime    = DateTime.Now;
                }
                else
                {
                    return;
                }
            }

            this.button1_flag = !this.button1_flag;
            if (this.button1_flag)
            {
                this.button1.Text = "STOP";
                if (this.parent_manager_called == false)
                {
                    this.class_my_com       = new MyCom(this.selected_com);
                    this.class_my_gra       = new MyGraph(this.chart1);
                    this.class_my_starttime = DateTime.Now;
                    this.Parent_ManagerAsync(class_my_com, 1, class_my_gra);
                }
                else
                {
                    this.class_my_starttime = DateTime.Now; //よく考えてない
                }
                //graph code
                //MyGraph mygra = new MyGraph(this.chart1);
                //List<MyPoints> mydatas = Form1.MyGraph.make_data();
                //mygra.Plot(mydatas);
            }
            else
            {
                this.button1.Text = "記録開始";
                //_cancellationtoken.Cancel();        //button2用にparent_managerAsync が死んでしまうので再起動しておく必要がある(不要かも)
                //_cancellationtoken.Dispose();
                //ここにデータをファイルに保存するかを決める
                if (this.checkBox1.Checked == true)
                {
                    前を付けて保存AToolStripMenuItem.PerformClick();
                    return;
                }
                DialogResult __result = MessageBox.Show("ファイルを保存しますか?", "question", MessageBoxButtons.YesNo);
                if (__result == DialogResult.Yes)
                {
                    前を付けて保存AToolStripMenuItem.PerformClick();
                }
            }
        }
Esempio n. 49
0
        //СЪЗДАВАНЕ НА ТАБЛО
        private void buttonCreateBoard_Click_1(object sender, EventArgs e)
        {
            string _boardName                 = "";
            string _orderName                 = "";
            int    _height                    = 0;
            int    heightIndex                = 0;
            int    widhtIndex                 = 0;
            int    depthIndex                 = 0;
            int    fHeightIndex               = 0;
            int    doorIndex                  = 0;
            int    roofIndex                  = 0;
            int    _width                     = 0;
            int    _depth                     = 0;
            bool   _isLeftSingleDoor          = false;
            bool   _isRightSingleDoor         = false;
            bool   _isDoubleDoor              = false;
            int    _foundHeight               = 0;
            bool   _isSingleRoof              = false;
            bool   _isMiddleRoof              = false;
            bool   _isLeftRoof                = false;
            bool   _isRightRoof               = false;
            bool   _isBackOpened              = false;
            bool   _isTopOpened               = false;
            bool   _isLeftPanelOpened         = false;
            bool   _isRightPanelOpened        = false;
            bool   _isMountedLeft             = false;
            bool   _isMountedRight            = false;
            bool   _hasCircuitBreaker         = false;
            List <AbstractPart> partList      = new List <AbstractPart>();
            PartGenerator       partGenerator = new PartGenerator();

            //ИМЕ ТАБЛО
            try
            {
                //string regex = "^[a-z + A-Z + 0-9] + -? + _? + \\s? [a-z + A-Z + 0-9] +$";
                if (Regex.Match(boardName.Text, @"^[\w]+[\s]?[\w]+$").Success)
                {
                    _boardName = boardName.Text;
                }
                else
                {
                    MessageBox.Show("Невалидно наименование!" +
                                    "\nИмето може да съдържа само букви и цифри!");
                    return;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Невалидно наименование!" +
                                "\nИмето може да съдържа само букви и цифри!");
                return;
            }
            //НОМЕР ПОРЪЧКА
            try
            {
                if (Regex.Match(orderNumber.Text, @"^[\w]+[\s]?[\w]+$").Success)
                {
                    _orderName = orderNumber.Text;
                }
                else
                {
                    MessageBox.Show("Невалиден номер на поръчката!" +
                                    "\nНомера може да съдържа само букви и цифри!");
                    return;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Невалиден номер на поръчката!" +
                                "\nНомера може да съдържа само букви и цифри!");
                return;
            }
            //ВИСОЧИНА
            try
            {
                _height     = int.Parse(height.Text);
                heightIndex = height.SelectedIndex;
            }
            catch (FormatException)
            {
                MessageBox.Show("Unable to parse height");
                return;
            }
            //ШИРИНА
            //TODO WHEN DOOR IS BIGGER THEN 800, DISABLE SINGLE DOORS PICKS
            try
            {
                _width     = int.Parse(width.Text);
                widhtIndex = width.SelectedIndex;
            }
            catch (FormatException)
            {
                MessageBox.Show("Unable to parse width");
                return;
            }
            //ДЪЛБОЧИНА
            try
            {
                _depth     = int.Parse(depth.Text);
                depthIndex = depth.SelectedIndex;
            }
            catch (FormatException)
            {
                MessageBox.Show("Unable to parse depth");
                return;
            }
            //ВИСОЧИНА НА ОСНОВАТА
            try
            {
                _foundHeight = int.Parse(foundHeight.Text);
                fHeightIndex = foundHeight.SelectedIndex;
            }
            catch (FormatException)
            {
                MessageBox.Show("Unable to parse foundation height");
            }

            //ТИП ВРАТА
            switch (doorType.SelectedIndex)
            {
            case 0: _isLeftSingleDoor = true;
                break;

            case 1: _isRightSingleDoor = true;
                break;

            case 2: _isDoubleDoor = true;
                break;

            default:
                MessageBox.Show("Изберете тип врата!");
                return;
            }
            doorIndex = doorType.SelectedIndex;

            //ТИП КОЗИРКА
            switch (RoofType.SelectedIndex)
            {
            case 0:
                break;

            case 1: _isSingleRoof = true;
                break;

            case 2: _isLeftRoof = true;
                break;

            case 3: _isRightRoof = true;
                break;

            case 4: _isMiddleRoof = true;
                break;

            default:
                MessageBox.Show("Изберете тип козирка!");
                return;
            }
            roofIndex = RoofType.SelectedIndex;

            //ОТОВРЕНО ОТЛЯВО
            if (isLeftPanelOpened.Checked)
            {
                _isLeftPanelOpened = true;
            }

            //ОТВОРЕНО ОТДЯСНО
            if (isRightPanelOpened.Checked)
            {
                _isRightPanelOpened = true;
            }
            //БЕЗ ГРЪБ
            if (isBackOpened.Checked)
            {
                _isBackOpened = true;
            }
            //ОТВОРЕНО ОТГОРЕ
            if (isTopPanelOpened.Checked)
            {
                _isTopOpened = true;
            }
            //ПРИСЪЕДИНЯВАНЕ ОТЛЯВО
            if (isFixedLeft.Checked)
            {
                _isMountedLeft = true;
            }
            //ПРИСЪЕДИНЯВАНЕ ОДЯСНО
            if (isFixedRight.Checked)
            {
                _isMountedRight = true;
            }
            //С ГЛАВЕН
            if (hasCicrcuitBreaker.Checked)
            {
                _hasCircuitBreaker = true;
            }
            //ГЕНЕРИРАНЕ НА ТАБЛО
            try
            {
                //ПРОВЕРКА ЗА ПОВТАРЯЩИ СЕ ТАБЛА
                if (!listBoards.Items.Contains(_boardName))
                {
                    partList.AddRange(partGenerator.GenerateParts(_height, _width, _depth, _isLeftSingleDoor, _isRightSingleDoor, _isDoubleDoor,
                                                                  _foundHeight, _isSingleRoof, _isLeftRoof, _isRightRoof,
                                                                  _isMiddleRoof, _isBackOpened, _isLeftPanelOpened,
                                                                  _isRightPanelOpened, _isMountedLeft, _isMountedRight, _isTopOpened, _hasCircuitBreaker));

                    Board board = new Board(_boardName, partList, heightIndex, widhtIndex, depthIndex, fHeightIndex, doorIndex, roofIndex,
                                            _isLeftPanelOpened, _isRightPanelOpened, _isTopOpened, _isBackOpened, _isMountedLeft, _isMountedRight, _hasCircuitBreaker);
                    //qtBoards.Enqueue(board);
                    //boardList.Add(board);
                    listBoards.Items.Add(_boardName);
                    boardDict.Add(board.GetName(), board);
                    MessageBox.Show(_boardName + " създадено!");
                    orderNumber.ReadOnly = true;
                    boardName.Text       = "";
                }
                else
                {
                    DialogResult dialogResult = MessageBox.Show("Вече има табло с това име! Желате ли да запишете промените?", "Внимание", MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        boardDict.Remove(_boardName);
                        listBoards.Items.Remove(_boardName);
                        Board board = new Board(_boardName, partList, heightIndex, widhtIndex, depthIndex, fHeightIndex, doorIndex, roofIndex,
                                                _isLeftPanelOpened, _isRightPanelOpened, _isTopOpened, _isBackOpened, _isMountedLeft, _isMountedRight, _hasCircuitBreaker);
                        listBoards.Items.Add(_boardName);
                        boardDict.Add(board.GetName(), board);
                        MessageBox.Show(_boardName.ToString() + " създадено!");
                        orderNumber.ReadOnly = true;
                        boardName.Text       = "";
                    }
                    else if (dialogResult == DialogResult.No)
                    {
                        return;
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Не може да се създаде таблото!!!");
                return;
            }
        }
Esempio n. 50
0
        /// <summary>
        /// 接收车号识别数据,开始翻车逻辑控制
        /// </summary>
        /// <param name="inTrainCarriagePass"></param>
        private void StartTippingTask(CmcsTrainCarriagePass trainCarriagePass)
        {
            Task task = new Task((state) =>
            {
                CmcsTrainCarriagePass inTrainCarriagePass = state as CmcsTrainCarriagePass;
                if (inTrainCarriagePass != null)
                {
                    #region 车号为空时,执行车号补录

                    if (string.IsNullOrEmpty(inTrainCarriagePass.TrainNumber))
                    {
                        Log4Neter.Info(this.trainTipper.EquipmentName + " - 车号识别失败,要求输入车号");

                        this.InvokeEx(() => { Form1.superTabControlManager.ChangeToTab(this.trainTipper.EquipmentCode); });

                        // 弹出输入框,要求输入车厢号
                        FrmInput frmInput = new FrmInput("请输入所翻车厢号", (input) =>
                        {
                            if (string.IsNullOrEmpty(input))
                            {
                                MessageBoxEx.Show("请输入车厢号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return(false);
                            }

                            if (!this.view_TrainTipperQueue_DF.Any(a => a.TrainNumber == input))
                            {
                                MessageBoxEx.Show("在队列中未找到此车,请重新输入", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return(false);
                            }

                            return(true);
                        });

                        if (frmInput.ShowDialog() == DialogResult.OK)
                        {
                            Log4Neter.Info(this.trainTipper.EquipmentName + " - 用户输入:" + frmInput.Input);
                            inTrainCarriagePass.TrainNumber = frmInput.Input;
                        }
                        else
                        {
                            Log4Neter.Info(this.trainTipper.EquipmentName + " - 用户关闭输入窗口");

                            inTrainCarriagePass.DataFlag = 1;
                            Dbers.GetInstance().SelfDber.Update(inTrainCarriagePass);

                            autoResetEvent.Set();
                        };
                    }

                    #endregion

                    Log4Neter.Info(this.trainTipper.EquipmentName + " - 当前车号:" + inTrainCarriagePass.TrainNumber);
                    commonDAO.SetSignalDataValue(this.trainTipper.EquipmentCode, eSignalDataName.当前车号.ToString(), inTrainCarriagePass.TrainNumber);

                    View_TrainTipperQueue selfView_TrainTipperQueue = this.view_TrainTipperQueue_All.FirstOrDefault(a => a.TrainNumber == inTrainCarriagePass.TrainNumber);
                    if (selfView_TrainTipperQueue != null)
                    {
                        commonDAO.SetSignalDataValue(this.trainTipper.EquipmentCode, eSignalDataName.当前车Id.ToString(), selfView_TrainTipperQueue.TransportId);

                        if (selfView_TrainTipperQueue.SampleType != eSamplingType.皮带采样.ToString())
                        {
                            // 采样方案中设置为非火车皮采

                            Log4Neter.Info(this.trainTipper.EquipmentName + " - 采样方案中设置为非皮带采样,SampleType=" + selfView_TrainTipperQueue.SampleType);

                            DialogResult dialogResult = MessageBoxEx2Show("<font size='+2'>车号: <font color='red'>" + selfView_TrainTipperQueue.TrainNumber + "</font><br/><br/>该车为" + selfView_TrainTipperQueue.SampleType + "<br/><br/>点击<font color='red'>[是]</font>立即通知皮带采样机停止采样<br/>然后在采样机成功停止后开始翻车<br/><br/>点击<font color='red'>[否]</font>直接开始翻车<br/><br/>点击<font color='red'>[取消]</font>不做任何处理</font>", "提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                            if (dialogResult == DialogResult.Yes)
                            {
                                if (SendSamplerStopCmd(selfView_TrainTipperQueue))
                                {
                                    // 标记为已处理
                                    ToHandled(inTrainCarriagePass.Id, selfView_TrainTipperQueue.Id);
                                }
                            }
                            else if (dialogResult == DialogResult.No)
                            {
                                // 标记为已处理
                                ToHandled(inTrainCarriagePass.Id, selfView_TrainTipperQueue.Id);
                            }
                        }
                        else
                        {
                            if (MessageBoxEx2Show("<font size='+2'>车号: <font color='red'>" + selfView_TrainTipperQueue.TrainNumber + "</font><br/><br/>点击<font color='red'>[确定]</font>立即通知皮带采样机开始采样<br/>确认采样机启动成功后再开始翻车<br/><br/>点击<font color='red'>[取消]</font>不做任何处理</font>", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                            {
                                if (SendSamplerStartCmd(selfView_TrainTipperQueue))
                                {
                                    // 标记为已处理
                                    ToHandled(inTrainCarriagePass.Id, selfView_TrainTipperQueue.Id);
                                }
                            }
                        }
                    }
                    else
                    {
                        // 未找到此车

                        commonDAO.SetSignalDataValue(this.trainTipper.EquipmentCode, eSignalDataName.当前车Id.ToString(), string.Empty);

                        if (MessageBoxEx2Show("未找到车厢[" + inTrainCarriagePass.TrainNumber + "],是否忽略?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            // 标记车号识别记录为已处理
                            carriageRecognitionerDAO.ChangeTrainCarriagePassToHandled(inTrainCarriagePass.Id);
                        }
                    }
                }

                autoResetEvent.Set();
            }, trainCarriagePass);

            task.Start();
        }
Esempio n. 51
0
        private void bntInThongBao_Click(object sender, EventArgs e)
        {
            epInThongBao.Clear();
            if (txtNoiLamViec.Text.Length == 0)
            {
                epInThongBao.SetError(txtNoiLamViec, "Nơi làm việc không được bỏ trống!");
                txtNoiLamViec.Focus();
                return;
            }
            ;
            if (txtYeuCauKyThuat.Text.Length == 0)
            {
                epInThongBao.SetError(txtYeuCauKyThuat, "Yêu cầu kĩ thuật không được bỏ trống!");
                txtYeuCauKyThuat.Focus();
                return;
            }
            if (cbbViTriTuyen.Text.Length == 0)
            {
                epInThongBao.SetError(cbbViTriTuyen, "Vị trí tuyển không được bỏ trống!");
                cbbViTriTuyen.Focus();
                return;
            }
            ;
            if (txtLuongCB.Text.Length == 0)
            {
                epInThongBao.SetError(txtLuongCB, "Lương cơ bản không được bỏ trống!");
                txtLuongCB.Focus();
                return;
            }
            if (txtThoiGianLam.Text.Length == 0)
            {
                epInThongBao.SetError(txtThoiGianLam, "Thời gian làm không được bỏ trống!");
                txtThoiGianLam.Focus();
                return;
            }
            if (cbbTuoiTu.Text.Length == 0)
            {
                epInThongBao.SetError(cbbTuoiTu, "Tuổi không được bỏ trống!");
                cbbTuoiTu.Focus();
                return;
            }
            if (cbbTuoiDen.Text.Length == 0)
            {
                epInThongBao.SetError(cbbTuoiDen, "Tuổi không được bỏ trống!");
                cbbTuoiDen.Focus();
                return;
            }
            if (cbbViTriTuyen.Text != dtCongViec.Rows[indexSelected][1].ToString())
            {
                epInThongBao.SetError(cbbViTriTuyen, "Không tìm thấy công việc!");
                cbbViTriTuyen.Focus();
                return;
            }
            print();
            DialogResult result = MessageBox.Show("Bạn có muốn lưu lại mẫu không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.Yes)
            {
                try
                {
                    string sql = String.Format("Insert into tbl_MauThongBao values(@NoiLamViec, @YeuCauKyThuat, @SoLuongThamGia, @SoNguoiCanTuyen, @MaCV, @YeuCauKhac, @YeuCauNgoaiNgu, @TuoiTu, @TuoiDen, @MucLuong, @ThoiGianLamViec, @TinhTrangHonNhan, @HinhThucTuyen, @NgayDuKienXuatCanh, @NgayTaoMau)");
                    SqlServerHelper.ExecuteNonQuery(sql, CommandType.Text,
                                                    "@NoiLamViec", SqlDbType.NVarChar, txtNoiLamViec.Text,
                                                    "@YeuCauKyThuat", SqlDbType.NVarChar, txtYeuCauKyThuat.Text,
                                                    "@SoLuongThamGia", SqlDbType.NVarChar, txtSLThamGia.Text,
                                                    "@SoNguoiCanTuyen", SqlDbType.NVarChar, txtSoNguoiCanTuyen.Text,
                                                    "@MaCV", SqlDbType.Int, Convert.ToInt32(dtCongViec.Rows[indexSelected][0]),
                                                    "@YeuCauKhac", SqlDbType.NVarChar, txtYeuCauKhac.Text,
                                                    "@YeuCauNgoaiNgu", SqlDbType.NVarChar, txtNgoaiNgu.Text,
                                                    "@TuoiTu", SqlDbType.Int, Convert.ToInt32(cbbTuoiTu.Text),
                                                    "@TuoiDen", SqlDbType.Int, Convert.ToInt32(cbbTuoiDen.Text),
                                                    "@MucLuong", SqlDbType.NVarChar, txtLuongCB.Text,
                                                    "@ThoiGianLamViec", SqlDbType.NVarChar, txtThoiGianLam.Text,
                                                    "@TinhTrangHonNhan", SqlDbType.NVarChar, (radioDocThan.Checked ? 1 : radioDaKetHon.Checked ? 2 : 0),
                                                    "@HinhThucTuyen", SqlDbType.NVarChar, txtHinhThucTuyen.Text,
                                                    "@NgayDuKienXuatCanh", SqlDbType.NVarChar, txtXuatCanh.Text,
                                                    "@NgayTaoMau", SqlDbType.Date, DateTime.Now);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Lưu bị lỗi", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    MessageBox.Show(ex.ToString());
                }
            }
            this.Close();
        }
        private void btnImport_Click(object sender, EventArgs e)
        {
            // check if data already added is encripted
            #region check if data already added is encripted
            string ContiuneImport = "0";

            string ManifestFile = "maFiles/manifest.json";
            if (File.Exists(ManifestFile))
            {
                string      AppManifestContents       = File.ReadAllText(ManifestFile);
                AppManifest AppManifestData           = JsonConvert.DeserializeObject <AppManifest>(AppManifestContents);
                bool        AppManifestData_encrypted = AppManifestData.Encrypted;
                if (AppManifestData_encrypted == true)
                {
                    MessageBox.Show("You can't import an .maFile because the existing account in the app is encrypted.\nDecrypt it and try again.");
                    this.Close();
                }
                else if (AppManifestData_encrypted == false)
                {
                    ContiuneImport = "1";
                }
                else
                {
                    MessageBox.Show("invalid value for variable 'encrypted' inside manifest.json");
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show("An Error occurred, Restart the program!");
            }
            #endregion

            // Continue
            #region Continue
            if (ContiuneImport == "1")
            {
                this.Close();

                // read EncriptionKey from imput box
                string ImportUsingEncriptionKey = txtBox.Text;

                // Open file browser > to select the file
                OpenFileDialog openFileDialog1 = new OpenFileDialog();

                // Set filter options and filter index.
                openFileDialog1.Filter      = "maFiles (.maFile)|*.maFile|All Files (*.*)|*.*";
                openFileDialog1.FilterIndex = 1;
                openFileDialog1.Multiselect = false;

                // Call the ShowDialog method to show the dialog box.
                DialogResult userClickedOK = openFileDialog1.ShowDialog();

                // Process input if the user clicked OK.
                if (userClickedOK == DialogResult.OK)
                {
                    // Open the selected file to read.
                    System.IO.Stream fileStream   = openFileDialog1.OpenFile();
                    string           fileContents = null;

                    using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
                    {
                        fileContents = reader.ReadToEnd();
                    }
                    fileStream.Close();

                    try
                    {
                        if (ImportUsingEncriptionKey == "")
                        {
                            // Import maFile
                            //-------------------------------------------
                            #region Import maFile
                            SteamGuardAccount maFile = JsonConvert.DeserializeObject <SteamGuardAccount>(fileContents);
                            if (maFile.Session.SteamID != 0)
                            {
                                mManifest.SaveAccount(maFile, false);
                                MessageBox.Show("Account Imported!");
                            }
                            else
                            {
                                throw new Exception("Invalid SteamID");
                            }
                            #endregion
                        }
                        else
                        {
                            // Import Encripted maFile
                            //-------------------------------------------
                            #region Import Encripted maFile
                            //Read manifest.json encryption_iv encryption_salt
                            string ImportFileName_Found = "0";
                            string Salt_Found           = null;
                            string IV_Found             = null;
                            string ReadManifestEx       = "0";

                            //No directory means no manifest file anyways.
                            ImportManifest newImportManifest = new ImportManifest();
                            newImportManifest.Encrypted = false;
                            newImportManifest.Entries   = new List <ImportManifestEntry>();

                            // extract folder path
                            string fullPath = openFileDialog1.FileName;
                            string fileName = openFileDialog1.SafeFileName;
                            string path     = fullPath.Replace(fileName, "");

                            // extract fileName
                            string ImportFileName = fullPath.Replace(path, "");

                            string ImportManifestFile = path + "manifest.json";


                            if (File.Exists(ImportManifestFile))
                            {
                                string ImportManifestContents = File.ReadAllText(ImportManifestFile);


                                try
                                {
                                    ImportManifest account = JsonConvert.DeserializeObject <ImportManifest>(ImportManifestContents);
                                    //bool Import_encrypted = account.Encrypted;

                                    List <ImportManifest> newEntries = new List <ImportManifest>();

                                    foreach (var entry in account.Entries)
                                    {
                                        string FileName        = entry.Filename;
                                        string encryption_iv   = entry.IV;
                                        string encryption_salt = entry.Salt;

                                        if (ImportFileName == FileName)
                                        {
                                            ImportFileName_Found = "1";
                                            IV_Found             = entry.IV;
                                            Salt_Found           = entry.Salt;
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    ReadManifestEx = "1";
                                    MessageBox.Show("Invalid content inside manifest.json!\nImport Failed.");
                                }


                                // DECRIPT & Import
                                //--------------------
                                #region DECRIPT & Import
                                if (ReadManifestEx == "0")
                                {
                                    if (ImportFileName_Found == "1" && Salt_Found != null && IV_Found != null)
                                    {
                                        string decryptedText = FileEncryptor.DecryptData(ImportUsingEncriptionKey, Salt_Found, IV_Found, fileContents);

                                        if (decryptedText == null)
                                        {
                                            MessageBox.Show("Decryption Failed.\nImport Failed.");
                                        }
                                        else
                                        {
                                            string fileText = decryptedText;

                                            SteamGuardAccount maFile = JsonConvert.DeserializeObject <SteamGuardAccount>(fileText);
                                            if (maFile.Session.SteamID != 0)
                                            {
                                                mManifest.SaveAccount(maFile, false);
                                                MessageBox.Show("Account Imported!\nYour Account in now Decrypted!");
                                                //MainForm.loadAccountsList();
                                            }
                                            else
                                            {
                                                MessageBox.Show("Invalid SteamID.\nImport Failed.");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (ImportFileName_Found == "0")
                                        {
                                            MessageBox.Show("Account not found inside manifest.json.\nImport Failed.");
                                        }
                                        else if (Salt_Found == null && IV_Found == null)
                                        {
                                            MessageBox.Show("manifest.json does not contain encrypted data.\nYour account may be unencrypted!\nImport Failed.");
                                        }
                                        else
                                        {
                                            if (IV_Found == null)
                                            {
                                                MessageBox.Show("manifest.json does not contain: encryption_iv\nImport Failed.");
                                            }
                                            else if (IV_Found == null)
                                            {
                                                MessageBox.Show("manifest.json does not contain: encryption_salt\nImport Failed.");
                                            }
                                        }
                                    }
                                }
                                #endregion     //DECRIPT & Import END
                            }
                            else
                            {
                                MessageBox.Show("manifest.json is missing!\nImport Failed.");
                            }
                            #endregion //Import Encripted maFile END
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("This file is not a valid SteamAuth maFile.\nImport Failed.");
                    }
                }
            }
            #endregion // Continue End
        }
Esempio n. 53
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="provider"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
        {
            IWindowsFormsEditorService editorService = null;

            if (provider != null)
            {
                editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            }

            if (editorService == null)
            {
                return(value);
            }

            bool      singleSel = true;
            SAMTimbre tim       = context.Instance as SAMTimbre;

            SAMTimbre[] tims = value as SAMTimbre[];
            if (tims != null)
            {
                tim       = tims[0];
                singleSel = false;
            }

            SAM inst = null;

            try
            {
                //InstrumentManager.ExclusiveLockObject.EnterReadLock();

                inst = InstrumentManager.FindParentInstrument(InstrumentType.SAM, tim) as SAM;
            }
            finally
            {
                //InstrumentManager.ExclusiveLockObject.ExitReadLock();
            }

            using (var frm = new FormPhonemesEditor(inst, tim, singleSel))
            {
                frm.Tag           = context;
                frm.Allophones    = (string)value;
                frm.ValueChanged += (s, e) =>
                {
                    try
                    {
                        //InstrumentManager.ExclusiveLockObject.EnterWriteLock();

                        context.PropertyDescriptor.SetValue(context.Instance, frm.Allophones);
                    }
                    finally
                    {
                        //InstrumentManager.ExclusiveLockObject.ExitWriteLock();
                    }
                };

                DialogResult dr = frm.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    value = frm.Allophones;
                }
                else if (value != null)
                {
                    value = ((string)value + " ").Clone();
                }
            }
            return(value);
        }
Esempio n. 54
0
        private void InstallUpdateSyncWithInfo()
        {
            UpdateCheckInfo info = null;

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
                try
                {
                    info = ad.CheckForDetailedUpdate();
                }
                catch (DeploymentDownloadException dde)
                {
                    MessageBox.Show("The new version of the application cannot be downloaded at this time. \n\nPlease check your network connection, or try again later. Error: " + dde.Message);
                    return;
                }
                catch (InvalidDeploymentException ide)
                {
                    MessageBox.Show("Cannot check for a new version of the application. The ClickOnce deployment is corrupt. Please redeploy the application and try again. Error: " + ide.Message);
                    return;
                }
                catch (InvalidOperationException ioe)
                {
                    MessageBox.Show("This application cannot be updated. It is likely not a ClickOnce application. Error: " + ioe.Message);
                    return;
                }

                if (info.UpdateAvailable)
                {
                    Boolean doUpdate = true;

                    if (!info.IsUpdateRequired)
                    {
                        DialogResult dr = MessageBox.Show("An update is available. Would you like to update the application now?", "Update Available", MessageBoxButtons.OKCancel);
                        if (!(DialogResult.OK == dr))
                        {
                            doUpdate = false;
                        }
                    }
                    else
                    {
                        // Display a message that the app MUST reboot. Display the minimum required version.
                        MessageBox.Show("This application has detected a mandatory update from your current " +
                                        "version to version " + info.MinimumRequiredVersion.ToString() +
                                        ". The application will now install the update and restart.",
                                        "Update Available", MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }

                    if (doUpdate)
                    {
                        try
                        {
                            ad.Update();
                            MessageBox.Show("The application has been upgraded, and will now restart.");
                            Application.Restart();
                        }
                        catch (DeploymentDownloadException dde)
                        {
                            MessageBox.Show("Cannot install the latest version of the application. \n\nPlease check your network connection, or try again later. Error: " + dde);
                            return;
                        }
                    }
                }
            }
        }
Esempio n. 55
0
        private void ChangeCommand_(int newSelected, Color color, bool force = false)
        {
            if (newSelected < -1 || commandList.Items.Count <= newSelected)
            {
                return;
            }

            if (newSelected != selected_ || force)
            {
                if (!isCommandSaved_ && !force)
                {
                    DialogResult saveRes = MessageBox.Show(
                        "Сохранить текущую команду?",
                        "Сохранение",
                        MessageBoxButtons.YesNoCancel,
                        MessageBoxIcon.Question,
                        MessageBoxDefaultButton.Button1
                        );
                    if (saveRes == DialogResult.Cancel)
                    {
                        return;
                    }
                    if (saveRes == DialogResult.Yes)
                    {
                        SaveCommand_();
                    }
                }
                SelectCommand_(newSelected, color);

                if (newSelected == -1)
                {
                    LoadCommand_(Command.GetDefault());

                    removeButton.Enabled = false;
                    saveButton.Enabled   = false;
                    upButton.Enabled     = false;
                    downButton.Enabled   = false;
                }
                else
                {
                    LoadCommand_(new Command(emulator_.GetCommand(newSelected)));

                    removeButton.Enabled = true;
                    saveButton.Enabled   = true;
                    if (newSelected == 0)
                    {
                        upButton.Enabled = false;
                    }
                    else
                    {
                        upButton.Enabled = true;
                    }
                    if (newSelected == commandList.Items.Count - 1)
                    {
                        downButton.Enabled = false;
                    }
                    else
                    {
                        downButton.Enabled = true;
                    }
                }
            }
        }
Esempio n. 56
0
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog inFile = new OpenFileDialog();

            inFile.Filter = "All Files|*.*";
            if (inFile.ShowDialog() == DialogResult.Cancel)
            {
                goto toss;
            }
            tbxFile.Text = inFile.FileName;

            btnSave.Enabled = true;
            dgvTable.Rows.Clear();
            dgvTable.Refresh();
verify:
            byte[] fileCheck = System.IO.File.ReadAllBytes(tbxFile.Text);
            if (fileCheck[0] == 'Y' && fileCheck[1] == 'a' && fileCheck[2] == 'z' && fileCheck[3] == '0') // if Yaz0 encoded, ask if they want to decode it
            {
                DialogResult diagResult = MessageBox.Show("This file is encoded!" + "\n\n" + "Do you want to decode?\nIt will create a seperate file automatically", "Yaz0 Encoded file...", MessageBoxButtons.YesNo);
                if (diagResult == DialogResult.No)
                {
                    tbxFile.Text    = "";
                    btnSave.Enabled = false;
                    goto toss;
                }
                string outFile = Yaz0.DecodeOutputFileRename(inFile.FileName);
                if (!Yaz0.Decode(inFile.FileName, outFile))
                {
                    MessageBox.Show("Decode error:" + "\n\n" + Yaz0.lerror);
                    tbxFile.Text    = "";
                    btnSave.Enabled = false;
                    goto toss;
                }
                tbxFile.Text = outFile;
                goto verify;
            }
            if (("" + ((char)fileCheck[0]) + ((char)fileCheck[1]) + ((char)fileCheck[2]) + ((char)fileCheck[3])) != "SARC")
            {
                MessageBox.Show("Not a SARC archive! Missing SARC header at 0x00" + "\n" + "( Your file header is: " + ((char)fileCheck[0]) + ((char)fileCheck[1]) + ((char)fileCheck[2]) + ((char)fileCheck[3]) + " )");
                tbxFile.Text    = "";
                btnSave.Enabled = false;
                goto toss;
            }

            int nodeCount = SARC.GetFileNodeCount(tbxFile.Text);

            string[] nodeTypes    = SARC.GetFileNodeType(tbxFile.Text);
            uint[]   nodeSizes    = SARC.GetFileNodeSizes(tbxFile.Text);
            string[] nodePaths    = SARC.GetFileNodePaths(tbxFile.Text);
            uint[]   nodePaddings = SARC.GetFileNodePaddings(tbxFile.Text);

            for (int i = 0; i < nodeCount; i++)
            {
                dgvTable.Rows.Add();
                dgvTable.Rows[i].Cells[0].Value = i + 1;
                dgvTable.Rows[i].Cells[1].Value = nodePaddings[i];
                dgvTable.Rows[i].Cells[2].Value = nodeTypes[i];
                dgvTable.Rows[i].Cells[3].Value = nodeSizes[i];
                dgvTable.Rows[i].Cells[4].Value = nodeSizes[i].ToString("X");
                dgvTable.Rows[i].Cells[5].Value = nodePaths[i];
            }

            fileSize           = fileCheck.Length;
            tbxFileSize.Text   = fileSize.ToString();
            dataOffset         = SARC.GetFileDataOffset(tbxFile.Text);
            tbxDataOffset.Text = "0x" + dataOffset.ToString("X");

toss:
            inFile.Dispose();
            GC.Collect();
        }
Esempio n. 57
0
        //****************************************************************************Inserts a new company into the company table
        //This function is good for second round modification
        private void submitButton_Click(object sender, EventArgs e)
        {
            if (txtcname.Text == string.Empty)
            {
                errorProvider1.SetError(txtcname, "Please Enter a Company Name");
            }
            if (txtAddr.Text == string.Empty)
            {
                errorProvider1.SetError(txtAddr, "Please Enter a Company Name");
            }
            if (stateComboBox.Text == string.Empty)
            {
                errorProvider1.SetError(stateComboBox, "Please Enter a State");
            }
            if (mskedtxtphone.Text == string.Empty)
            {
                errorProvider1.SetError(mskedtxtphone, "Pleae Enter a Phone Number");
            }
            if (txtcompzip.Text == string.Empty)
            {
                errorProvider1.SetError(txtcompzip, "Pleae Enter a Zip Code");
            }
            if (txtcontact.Text == string.Empty)
            {
                DialogResult dr = MessageBox.Show("Contact is blank, do you wish to continue?", "Important Question", MessageBoxButtons.YesNo);
            }

            else
            {
                //string connectionString = "Data Source=localhost" + "; Database=commissionrepo" + "; User ID=root" + "; Password=141210;";
                string          connectionString = ConfigurationManager.ConnectionStrings["CommDB"].ConnectionString;
                MySqlConnection MySqlConn        = new MySqlConnection(connectionString);

                try
                {
                    MySqlConn.Open();
                    //company insert query
                    string       commandString7 = ("INSERT into company SET company_name = '" + txtcname.Text.Trim() + "', address = '" + txtAddr.Text.Trim() + "', state = '" + stateComboBox.Text.Trim() + "', phone_number = '" + mskedtxtphone.Text.Trim() + "', contact_person = '" + txtcontact.Text.Trim() + "', city = '" + txtcompcity.Text.Trim() + "', zip = '" + txtcompzip.Text.Trim() + "'");
                    MySqlCommand mysqlcommand   = new MySqlCommand(commandString7, MySqlConn);

                    //companyTableAdapter getcomp = new companyDSTableAdapters.companyTableAdapter();

                    //DataTable table =  new companyDS.companyDataTable();
                    DataTable table = GetDataTable(
                        // Pass open database connection to function
                        ref MySqlConn,
                        // Pass SQL statement to create SqlDataReader
                        commandString7);


                    String item = txtcname.Text.Trim();
                    cbocname.Items.Add(item);
                    cbojcname.Items.Add(item);
                }
                catch (MySqlException ex)
                {
                    MessageBox.Show(ex.Message);
                }


                txtcname.Text      = " ";
                txtAddr.Text       = " ";
                txtcompcity.Text   = " ";
                txtcompzip.Text    = " ";
                stateComboBox.Text = " ";
                mskedtxtphone.Text = " ";
                txtcontact.Text    = " ";
            }
        }
Esempio n. 58
0
        public static int ShowChooseChangelistYesNoCancel(string prompt, IList <string> files, IList <P4.Changelist> items, ref string NewChangeDescription)
        {
            //if ((items == null) || (items.Count <= 0))
            //{
            //    return 0;
            //}
            if (ActiveChangeList > -1)
            {
                CurrentChangeListLastUse = DateTime.Now;
                //					NewChangeDescription = CurrentChangeDescription;
                return(CurrentChangeList);
            }
            SelectChangelistDlg2 dlg = new SelectChangelistDlg2(prompt, files, items);

            dlg.NewChangelistDescription = NewChangeDescription;

            dlg.OkBtn.Visible     = false;
            dlg.CancelBtn.Visible = true;

            dlg.saveToChangelistBtn.Visible = false;
            dlg.submitBtn.Visible           = false;

            dlg.YesBtn1.Visible = false;
            dlg.NoBtn1.Visible  = false;

            dlg.YesBtn2.Visible = true;
            dlg.NoBtn2.Visible  = true;

            dlg.DontShowAgainCB.Visible = false;

            dlg.BtnBar.Controls.Clear();
            dlg.BtnBar.Controls.Add(dlg.BtnSpacer);
            dlg.BtnBar.Controls.Add(dlg.YesBtn2);
            dlg.BtnBar.Controls.Add(dlg.NoBtn2);
            dlg.BtnBar.Controls.Add(dlg.CancelBtn);

            dlg.YesBtn2.Column   = 1;
            dlg.NoBtn2.Column    = 2;
            dlg.CancelBtn.Column = 3;
            dlg.BtnBar.InitializeGrid(true);

            DialogResult res = dlg.ShowDialog();

            if (res == DialogResult.Cancel)
            {
                CurrentChangeList = -3;
                return(CurrentChangeList);
            }
            if (res == DialogResult.No)
            {
                CurrentChangeList = -2;
                return(CurrentChangeList);
            }
            int changelistId = dlg.Result;

            if (changelistId == -1)
            {
                NewChangeDescription = dlg.DescriptionTB.Text;
                //					CurrentChangeDescription = NewChangeDescription;
            }
            CurrentChangeListLastUse = DateTime.Now;
            CurrentChangeList        = changelistId;
            return(changelistId);
        }
Esempio n. 59
0
        /// <summary>
        /// Event Handler for next click event
        /// </summary>
        private void next_Click(object sender, System.EventArgs e)
        {
            // Check if we're on the last page.
            if (currentIndex == (maxPages - 1))
            {
                // Exit
                return;
            }

            System.Resources.ResourceManager resManager = new System.Resources.ResourceManager(typeof(Connecting));

            if (currentIndex == 3)             // Set Passphrase
            {
                if (this.passphrasePage.Passphrase != this.passphrasePage.RetypePassphrase)
                {
                    MessageBox.Show(Resource.GetString("TypeRetypeMisMatch"));
                }
                else
                {
                    string publicKey = "";
                    string ragent    = null;
                    if (this.passphrasePage.RecoveryAgent != null && this.passphrasePage.RecoveryAgent != "None")
                    {
                        // Show the certificate.....
                        byte[] CertificateObj = this.simws.GetRACertificateOnClient(this.identityPage.domain.ID, this.passphrasePage.RecoveryAgent);
                        System.Security.Cryptography.X509Certificates.X509Certificate cert = new System.Security.Cryptography.X509Certificates.X509Certificate(CertificateObj);
                        //	MyMessageBox mmb = new MyMessageBox( "Verify Certificate", "Verify Certificate", cert.ToString(true), MyMessageBoxButtons.YesNo, MyMessageBoxIcon.Question, MyMessageBoxDefaultButton.Button2 );
                        MyMessageBox mmb = new MyMessageBox(string.Format(resManager.GetString("verifyCert"), this.passphrasePage.RecoveryAgent), resManager.GetString("verifyCertTitle"), cert.ToString(true), MyMessageBoxButtons.YesNo, MyMessageBoxIcon.Question, MyMessageBoxDefaultButton.Button2);
                        DialogResult messageDialogResult = mmb.ShowDialog();
                        mmb.Dispose();
                        mmb.Close();
                        if (messageDialogResult != DialogResult.OK)
                        {
                            return;
                        }
                        else
                        {
                            ragent    = this.passphrasePage.RecoveryAgent;
                            publicKey = Convert.ToBase64String(cert.GetPublicKey());
                        }
                    }
                    Status passPhraseStatus = null;
                    try
                    {
                        passPhraseStatus = this.simiasWebService.SetPassPhrase(this.identityPage.domain.ID, this.passphrasePage.Passphrase, null, publicKey);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(Resource.GetString("IsPassphraseSetException") + ex.Message);
                        return;
                    }
                    if (passPhraseStatus.statusCode == StatusCodes.Success)
                    {
                        this.simiasWebService.StorePassPhrase(this.identityPage.domain.ID, this.passphrasePage.Passphrase, CredentialType.Basic, this.passphrasePage.RememberPassphrase);
                        Novell.iFolderCom.MyMessageBox mmb = new MyMessageBox(Resource.GetString("SetPassphraseSuccess") /*"Successfully set the passphrase"*/, "", "", MyMessageBoxButtons.OK, MyMessageBoxIcon.Information);
                        mmb.ShowDialog();
                        mmb.Dispose();
                        this.Dispose();
                        this.Close();
                    }
                    else
                    {
                        // Unable to set the passphrase
                        Novell.iFolderCom.MyMessageBox mmb = new MyMessageBox(Resource.GetString("IsPassphraseSetException") /*"Unable to set the passphrase"*/, "" /*"Error setting the passphrase"*/, "" /*Resource.GetString("TryAgain")*//*"Please try again"*/, MyMessageBoxButtons.OK, MyMessageBoxIcon.Error);
                        mmb.ShowDialog();
                        mmb.Dispose();
                        return;
                    }
                }
            }
            else if (currentIndex == 4)           // Validate passphrase
            {
                Status passPhraseStatus = null;
                try
                {
                    passPhraseStatus = this.simiasWebService.ValidatePassPhrase(this.identityPage.domain.ID, this.passphraseVerifyPage.Passphrase);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(resManager.GetString("ValidatePPError") /*"Unable to validate the Passphrase. {0}"*/, ex.Message);
                    return;
                }
                if (passPhraseStatus != null)
                {
                    if (passPhraseStatus.statusCode == StatusCodes.PassPhraseInvalid)                      // check for invalid passphrase
                    {
                        Novell.iFolderCom.MyMessageBox mmb = new MyMessageBox(Resource.GetString("InvalidPPText") /*"Invalid the passphrase"*/, Resource.GetString("VerifyPP") /*"Passphrase Invalid"*/, "" /*Resource.GetString("TryAgain")*//*"Please try again"*/, MyMessageBoxButtons.OK, MyMessageBoxIcon.Error);
                        mmb.ShowDialog();
                        mmb.Dispose();
                        return;
                    }
                    else if (passPhraseStatus.statusCode == StatusCodes.Success)
                    {
                        try
                        {
                            this.simiasWebService.StorePassPhrase(this.identityPage.domain.ID, this.passphraseVerifyPage.Passphrase, CredentialType.Basic, this.passphraseVerifyPage.RememberPassphrase);
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("Unable to store Passphrase");
                            return;
                        }
                    }
                }
            }

            int nextIndex = this.pages[currentIndex].ValidatePage(currentIndex);

            if (nextIndex == 4)
            {
                // Set the passphrase
                nextIndex = 5;
            }
            else if (nextIndex == 3)
            {
                if (this.identityPage.Encrypion == false)
                {
                    // if 2.x is encrypted make a prompt
                    if (this.encryptedOriginal == true)
                    {
                        MyMessageBox mmb1 = new MyMessageBox(Resource.GetString("EncryptTotext"), Resource.GetString("MigrationAlert"), "", MyMessageBoxButtons.YesNo, MyMessageBoxIcon.Warning, MyMessageBoxDefaultButton.Button1);
                        DialogResult res  = mmb1.ShowDialog();
                        if (res == DialogResult.No)
                        {
                            nextIndex = currentIndex;
                        }
                        else
                        {
                            nextIndex = 5;
                        }
                    }
                    else
                    {
                        nextIndex = 5;
                    }
                }
                else                 // encryption selected..
                {
                    try
                    {
                        string passphrasecheck = this.simiasWebService.GetPassPhrase(this.identityPage.domain.ID);
                        if (passphrasecheck != null && passphrasecheck != "")
                        {
                            Status status = this.simiasWebService.ValidatePassPhrase(this.identityPage.domain.ID, passphrasecheck);
                            if (status != null && status.statusCode == StatusCodes.Success)
                            {
                                // Passphrase validated.
                                nextIndex = 5;
                            }
                        }
                        else if (this.simiasWebService.IsPassPhraseSet(this.identityPage.domain.ID) == true)
                        {
                            //MessageBox.Show("passphrase set");
                            nextIndex = 4;
                        }
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Unable to get passphrase. \nLogin to the domain and try again.");
                        // Stay in the same page
                        nextIndex = currentIndex;
                    }
                }
            }

            if (nextIndex != currentIndex)
            {
                this.pages[currentIndex].DeactivatePage();
                this.pages[nextIndex].ActivatePage(currentIndex);
                if (nextIndex == 5)
                {
                    this.pages[nextIndex].PreviousIndex = 2;
                }

                currentIndex = nextIndex;

                if (currentIndex == (maxPages - 2))
                {
                    next.Text = Resource.GetString("MigrateText");
                    this.verifyPage.UpdateDetails();
                }
                else if (currentIndex == (maxPages - 1))
                {
                    // We're on the completion page ... change the Next
                    // button to a Finish button.
                    next.DialogResult = DialogResult.OK;
                    next.Text         = Resource.GetString("FinishText");            //"&Finish";
                }
            }
        }
Esempio n. 60
0
 private void btnDownloadOnly_Click(object sender, EventArgs e)
 {
     Log("Download Only");
     GetUpdateFile(true);
     _result = DialogResult.No;
 }