Exemplo n.º 1
0
		public NewProtectSimpleDialog(bool serverMode = false)
			: base()
		{
            Logger.LogDebug("Create new instance of Protect Simple dialog: Start");
            try
            {
				IsServerMode = serverMode;
                CreateContentControl();

                Height = 520;
			    ResizeMode = System.Windows.ResizeMode.NoResize;
			    WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
			    this.Title = "Workshare Protect";

			    DialogResultEx = System.Windows.Forms.DialogResult.None;

			    _processworker = new BackgroundWorker();
			    _processworker.DoWork += new DoWorkEventHandler(_processworker_DoWork);
			    _processworker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_processworker_RunWorkerCompleted);
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                throw;
            }
            finally
            {
                Logger.LogDebug("Create new instance of Protect Simple dialog: End");
            }
		}
 private void brouse_Click(object sender, RoutedEventArgs e)
 {
     dlg = new System.Windows.Forms.FolderBrowserDialog();
     result = dlg.ShowDialog(this.GetIWin32Window());
     if (result == System.Windows.Forms.DialogResult.OK)
         pathLabel.Content = dlg.SelectedPath;
 }
Exemplo n.º 3
0
 public static System.Windows.Forms.DialogResult Show(string i_StrMsg, string i_Title, MsgBtnType i_ButtonStyle, MsgIconType i_IconMessage)
 {
     switch (i_ButtonStyle)
     {
         case MsgBtnType.MsgBtnOK:
             MsgBoxForm_OK v_MyFormMsgOK = new MsgBoxForm_OK();
             m_MsgResult = v_MyFormMsgOK.Display(i_StrMsg, i_Title, i_IconMessage);
             break;
         case MsgBtnType.MsgBtnYes_No:
             MsgBoxForm_Yes_No v_MyFormMsgYN = new MsgBoxForm_Yes_No();
             m_MsgResult = v_MyFormMsgYN.Display(i_StrMsg, i_Title, i_IconMessage);
             break;
         case MsgBtnType.MsgBtnYes_No_Cancel:
             MsgBoxFormYes_No_Cancel v_MyFormMsgYNC = new MsgBoxFormYes_No_Cancel();
             m_MsgResult = v_MyFormMsgYNC.Display(i_StrMsg, i_Title, i_IconMessage);
             break;
     }
     return m_MsgResult;
 }
 public System.Windows.Forms.DialogResult Display(string i_strMsg, string i_titleMsg, MessageForms.Msgs.MsgIconType i_IconType)
 {
     SetWidthHeightForm(i_strMsg);
     FormatFormMsg(i_titleMsg, this.m_PanelCtrl);
     m_MsgResult = System.Windows.Forms.DialogResult.No;
     switch (i_IconType)
     {
         case MessageForms.Msgs.MsgIconType.ErrorIcon:
             PicIcon.Image = this.MsgIcons.Images[System.Convert.ToInt32(MessageForms.Msgs.MsgIconType.ErrorIcon)];
             break;
         case MessageForms.Msgs.MsgIconType.InfomationIcon:
             PicIcon.Image = this.MsgIcons.Images[System.Convert.ToInt32(MessageForms.Msgs.MsgIconType.InfomationIcon)];
             break;
         case MessageForms.Msgs.MsgIconType.QuestionIcon:
             PicIcon.Image = this.MsgIcons.Images[System.Convert.ToInt32(MessageForms.Msgs.MsgIconType.QuestionIcon)];
             break;
         case MessageForms.Msgs.MsgIconType.WarningIcon:
             PicIcon.Image = this.MsgIcons.Images[System.Convert.ToInt32(MessageForms.Msgs.MsgIconType.WarningIcon)];
             break;
     }
     this.ShowDialog();
     return m_MsgResult;
 }
Exemplo n.º 5
0
 private void TextBox_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
 {
     System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
     System.Windows.Forms.DialogResult        result = dialog.ShowDialog();
     _savePathTextBox.Text = dialog.SelectedPath;
 }
Exemplo n.º 6
0
        //Extract utility
        private void MenuItem_Click_5(object sender, RoutedEventArgs e)
        {
            if (!File.Exists("WinExtract.exe"))
            {
                MessageBox.Show("I couldn't find WinExtract.exe please copy it here. You can get it here https://github.com/fjay69/UndertaleTools");
                return;
            }
            //Extract Undertale
            var dialog = new System.Windows.Forms.FolderBrowserDialog();

            if (Directory.Exists(Project.UndertalePath))
            {
                dialog.SelectedPath = Project.UndertalePath;
            }
            dialog.Description = "Select Undertale folder";
            System.Windows.Forms.DialogResult result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                string up = System.IO.Path.Combine(dialog.SelectedPath, "data.win");
                if (!File.Exists(up))
                {
                    MessageBox.Show("This is not Undertale! YOU LITTLE LIAR!111");
                    return;
                }
                var dialog2 = new System.Windows.Forms.FolderBrowserDialog();
                dialog2.Description = "Select destination path where Undertale will be extracted.";
                result = dialog2.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string dest = System.IO.Path.Combine(dialog2.SelectedPath, "UndertaleRes");
                    if (Directory.Exists(dest))
                    {
                        MessageBox.Show("The game has already been extracted here. Choose another path.");
                        return;
                    }
                    Directory.CreateDirectory(dest);

                    var proc = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName               = "WinExtract.exe",
                            Arguments              = up + " " + dest + "",
                            UseShellExecute        = false,
                            RedirectStandardOutput = true,
                            CreateNoWindow         = true
                        }
                    };
                    if (System.Environment.OSVersion.Version.Major >= 6)
                    {
                        proc.StartInfo.Verb = "runas";
                    }
                    proc.Start();
                    string o    = "";
                    string line = "";
                    while (!proc.StandardOutput.EndOfStream)
                    {
                        line = proc.StandardOutput.ReadLine();
                        o   += line + "\n";
                    }
                    MessageBox.Show(o);

                    File.WriteAllLines("lastpath.txt", new string[] { dest, dialog.SelectedPath });
                    Project.UndertalePath = dialog.SelectedPath;

                    if (line.StartsWith("Chunk AUDO offset:"))
                    {
                        MessageBox.Show("* Undertale has been extracted. \n* You are filled with determination.");
                        if (Project.Loaded)
                        {
                            if (MessageBox.Show("Do you want open new project without saving the current?", "Do not save current?", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                            {
                                LoadProject(dest);
                            }
                        }
                        else
                        {
                            LoadProject(dest);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Something went wrong...");
                    }
                }
                else
                {
                    MessageBox.Show("Please, select destination path.");
                }
            }
            else
            {
                MessageBox.Show("Please, choose Undertale folder.");
            }
        }
Exemplo n.º 7
0
        public void Choose(System.Windows.Forms.DialogResult dialogResult)
        {
            var automationId = DialogResultMapper.ToAutomationId(GetButtons().Count, dialogResult);

            FindFirstChild(x => x.ByAutomationId(automationId)).Click();
        }
Exemplo n.º 8
0
        public static bool Import(string filename = null)
        {
            if (filename == null)
            {
                using (System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog())
                {
                    ofd.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                    ofd.Filter           = "ZippedButton|*.zbn;*.gz";
                    ofd.AddExtension     = true;

                    System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.DialogResult.Cancel;
                    try
                    {
                        dialogResult = ofd.ShowDialog();
                    }
                    catch (System.Runtime.InteropServices.COMException)
                    {
                        ofd.AutoUpgradeEnabled = false;
                        dialogResult           = ofd.ShowDialog();
                    }

                    if (dialogResult == System.Windows.Forms.DialogResult.OK && ofd.FileName != null)
                    {
                        filename = ofd.FileName;
                    }
                }
            }

            if (filename != null && System.IO.File.Exists(filename))
            {
                try
                {
                    List <CustomButton> list = Tools.Serializer.ObjFromFile(filename) as List <CustomButton>;
                    if (list.Count > 0)
                    {
                        System.Windows.Forms.DialogResult rv = buttons.Count == 0 ? System.Windows.Forms.DialogResult.No : System.Windows.Forms.MessageBox.Show(Strings.BoxImportCustomButtonClearText, Strings.BoxImportCustomButtonCaption, System.Windows.Forms.MessageBoxButtons.YesNoCancel);

                        if (rv == System.Windows.Forms.DialogResult.Yes || rv == System.Windows.Forms.DialogResult.No)
                        {
                            if (rv == System.Windows.Forms.DialogResult.Yes)
                            {
                                buttons.Clear();
                            }

                            foreach (CustomButton cb in list)
                            {
                                if (System.Windows.Forms.MessageBox.Show(string.Format("Import \"{0}\"?", cb.ToolTip.Trim().Length > 0 ? cb.ToolTip : "[no name]"), Strings.BoxImportCustomButtonCaption, System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                                {
                                    buttons.Add(cb);
                                }
                            }

                            return(true);
                        }
                    }
                }
                catch { System.Windows.Forms.MessageBox.Show($"Error importing custom buttons from {filename}"); }
            }

            return(false);
        }
Exemplo n.º 9
0
        public bool Export(string templatePath)
        {
            EQASubSystemCollectin subSystems = DrawingData as EQASubSystemCollectin;

            if (subSystems.Count == 0)
            {
                return(true);
            }

            subSystems.Sort();

            frmMMKEquipmentList FrmMMKEquipmentList = new frmMMKEquipmentList();

            System.Windows.Forms.DialogResult dlgResult = FrmMMKEquipmentList.ShowDialog();

            if (dlgResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return(true);
            }

            _drawingLanguage = FrmMMKEquipmentList.Language;

            _contractNo = FrmMMKEquipmentList.ContractNo;
            _drawingNo  = FrmMMKEquipmentList.DrawingNo;
            _revision   = FrmMMKEquipmentList.Revision;
            _topLevelNo = FrmMMKEquipmentList.TopLevelNo;
            _speciality = FrmMMKEquipmentList.Speciality;
            _stage      = FrmMMKEquipmentList.Stage;
            _date       = FrmMMKEquipmentList.Date;
            _madeBy     = FrmMMKEquipmentList.MadeBy;
            _designBy   = FrmMMKEquipmentList.DesignBy;
            _checkedBy  = FrmMMKEquipmentList.CheckedBy;
            _reviewedBy = FrmMMKEquipmentList.ApprovedBy;

            if (!FrmMMKEquipmentList.KeepETNo)
            {
                int startNo = 0;
                for (int i = 0; i < subSystems.Count; i++)
                {
                    for (int j = 0; j < subSystems[i].Loops.Count; j++)
                    {
                        for (int k = 0; k < subSystems[i].Loops[j].Equipments.Count; k++)
                        {
                            startNo = subSystems[i].Loops[j].Equipments[k].TagNo.IndexOf("-", 0);
                            subSystems[i].Loops[j].Equipments[k].TagNo =
                                subSystems[i].Loops[j].Equipments[k].TagNo.Substring(startNo);
                        }
                    }
                }
            }

            Microsoft.Office.Interop.Excel.ApplicationClass xlsApp = new ApplicationClass();
            // 打开文件
            xlsApp.Workbooks.Add(FrmMMKEquipmentList.TemplatePath);

            Microsoft.Office.Interop.Excel.Workbook xlsWorkBook
                           = xlsApp.Workbooks[1];
            xlsApp.Visible = true;

            try {
                int pageCount;
                int currentPageNumber;
                int eqpNumberInPages;

                Microsoft.Office.Interop.Excel.Worksheet xlsWorkSheet;

                switch (_drawingLanguage)
                {
                case DrawingLanguage.SimplifiedChinese:

                    pageCount = 0;

                    foreach (EQASubSystem subSystem in subSystems)
                    {
                        if ((subSystem.EquipmentsCount % 7) == 0)
                        {
                            pageCount += subSystem.EquipmentsCount / 7;
                        }
                        else
                        {
                            pageCount += Convert.ToInt32(Math.Ceiling(subSystem.EquipmentsCount / 7.0f));
                        }
                    }

                    for (int i = 0; i < pageCount - 1; i++)
                    {
                        (xlsApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet).Copy(Missing.Value, xlsApp.Worksheets[1 + i]);
                    }

                    currentPageNumber = 0;
                    eqpNumberInPages  = 7;

                    lock (subSystems) {
                        if (subSystems.Count > 0)
                        {
                            for (int i = 0; i < subSystems.Count; i++)
                            {
                                EQASubSystem subSystem = subSystems[i];
                                currentPageNumber++;
                                if (i > 0 && (subSystems[i - 1].EquipmentsCount % 7 == 0))
                                {
                                    currentPageNumber--;
                                }
                                eqpNumberInPages  = 7;
                                xlsWorkSheet      = (Microsoft.Office.Interop.Excel.Worksheet)xlsApp.Worksheets[currentPageNumber];
                                xlsWorkSheet.Name = (currentPageNumber).ToString();
                                xlsWorkSheet.Activate();

                                // 图纸格式
                                // 字体
                                xlsWorkSheet.get_Range("B7", "S13").Font.Name = "Times New Roman";
                                xlsWorkSheet.get_Range("B7", "S13").Font.Size = 11f;

                                // 格式
                                xlsWorkSheet.get_Range("B7", "S13").HorizontalAlignment = Constants.xlCenter;
                                xlsWorkSheet.get_Range("B7", "S13").VerticalAlignment   = Constants.xlCenter;
                                xlsWorkSheet.get_Range("M7", "M13").HorizontalAlignment = Constants.xlGeneral;
                                xlsWorkSheet.get_Range("M7", "M13").VerticalAlignment   = Constants.xlGeneral;
                                xlsWorkSheet.get_Range("B7", "S13").WrapText            = true;

                                //
                                // 图纸内容
                                //
                                // 项目名称
                                xlsWorkSheet.get_Range("B2", Missing.Value).Value2
                                    += "俄罗斯MMK冷轧公辅EP项目";
                                // 子系统
                                xlsWorkSheet.get_Range("B3", Missing.Value).Value2
                                    += subSystem.Name;

                                //
                                // 图框内容
                                xlsWorkSheet.Shapes.Item("BTL").Ungroup();
                                // 专业
                                xlsWorkSheet.Shapes.Item("DWG_SPECIALITY").TextFrame.Characters(Missing.Value, Missing.Value).Text = _speciality;
                                // 设计阶段
                                xlsWorkSheet.Shapes.Item("DESIGN_STAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = _stage;
                                // 日期
                                xlsWorkSheet.Shapes.Item("PRINT_DATE").TextFrame.Characters(Missing.Value, Missing.Value).Text = _date;
                                // 室审
                                xlsWorkSheet.Shapes.Item("DEPT_CHECKER").TextFrame.Characters(Missing.Value, Missing.Value).Text = _reviewedBy;
                                // 审核
                                xlsWorkSheet.Shapes.Item("DWG_CHECKER").TextFrame.Characters(Missing.Value, Missing.Value).Text = _checkedBy;
                                // 设计
                                xlsWorkSheet.Shapes.Item("DWG_DESIGN").TextFrame.Characters(Missing.Value, Missing.Value).Text = _designBy;
                                // 制图
                                xlsWorkSheet.Shapes.Item("DWG_DRAW").TextFrame.Characters(Missing.Value, Missing.Value).Text = _madeBy;
                                // 合同号
                                xlsWorkSheet.Shapes.Item("CONTRACT").TextFrame.Characters(Missing.Value, Missing.Value).Text = _contractNo;
                                // 图号
                                xlsWorkSheet.Shapes.Item("DRAWING_NO").TextFrame.Characters(Missing.Value, Missing.Value).Text = _drawingNo;
                                // 高层代号
                                xlsWorkSheet.Shapes.Item("=").TextFrame.Characters(Missing.Value, Missing.Value).Text = "=" + _topLevelNo;
                                // 修改号
                                xlsWorkSheet.Shapes.Item("REVISE_NO").TextFrame.Characters(Missing.Value, Missing.Value).Text = _revision;
                                // 页次
                                if (xlsWorkSheet.Index < pageCount)
                                {
                                    xlsWorkSheet.Shapes.Item("PAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = xlsWorkSheet.Index.ToString() + "+";
                                }
                                else
                                {
                                    xlsWorkSheet.Shapes.Item("PAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = (xlsWorkSheet.Index).ToString();
                                }

                                if (subSystem.Loops.Count > 0)
                                {
                                    for (int j = 0; j < subSystem.Loops.Count; j++)
                                    {
                                        EQALoop loop = subSystem.Loops[j];
                                        if (loop.Equipments.Count > 0)
                                        {
                                            // 回路号
                                            xlsWorkSheet.get_Range("B" + eqpNumberInPages.ToString(), Missing.Value).Value2
                                                = FrmMMKEquipmentList.HasLoopNo ? loop.LoopNo : "";

                                            //检测与控制项目
                                            string item = loop.Location + loop.ProcParameter +
                                                          (loop.HasLocalIndication ? @"/就地显示" : "") +
                                                          (loop.HasLocalOperating ? @"/就地操作" : "") +
                                                          (loop.HasComputerIndication ? @"/显示" : "") +
                                                          (loop.HasComputerOperating ? @"/操作" : "") +
                                                          (loop.HasRecording ? @"/记录" : "") +
                                                          (loop.HasAlarm ? @"/报警" : "") +
                                                          (loop.HasControlling ? @"/调节" : "") +
                                                          (loop.HasInterlock ? @"/联锁" : "");

                                            xlsWorkSheet.get_Range("D" + eqpNumberInPages.ToString(), Missing.Value).Value2
                                                = FrmMMKEquipmentList.HasItems ? item : "";
                                        }

                                        for (int m = 0; m < loop.Equipments.Count; m++)
                                        {
                                            EQAEquipment eqp = loop.Equipments[m];
                                            if (!eqp.IsEquipment)
                                            {
                                                continue;
                                            }

                                            // 位号
                                            xlsWorkSheet.get_Range("C" + eqpNumberInPages.ToString(), Missing.Value).Value2
                                                = FrmMMKEquipmentList.HasTagNo ? eqp.TagNo : "";

                                            // 其他项目
                                            xlsWorkSheet.get_Range("E" + eqpNumberInPages.ToString(), "S" + eqpNumberInPages.ToString()).Value2
                                                = new object[] { FrmMMKEquipmentList.HasEqpName?eqp.Name                                                                          : "",
                                                                                                    FrmMMKEquipmentList.HasEqpType?eqp.EqpType                                    : "",
                                                                                                    FrmMMKEquipmentList.HasMeasuringRangeMin?eqp.LowerLimit                       : "",
                                                                                                    FrmMMKEquipmentList.HasMeasuringRangeMax?eqp.UpperLimit                       : "",
                                                                                                    FrmMMKEquipmentList.HasMeasuringRangeUnit?eqp.Unit                            : "",
                                                                                                    FrmMMKEquipmentList.HasInputSignal?eqp.InputSignal                            : "",
                                                                                                    FrmMMKEquipmentList.HasOutputSignal?eqp.OutputSignal                          : "",
                                                                                                    FrmMMKEquipmentList.HasPowerSupply?eqp.PowerSupply                            : "",
                                                                                                    FrmMMKEquipmentList.HasSpec?eqp.Spec1 + ",\n" + eqp.Spec2 + ",\n" + eqp.Spec3 : "",
                                                                                                    FrmMMKEquipmentList.HasQuantity?eqp.Quantity.ToString()                       : "",
                                                                                                    FrmMMKEquipmentList.HasLocation?eqp.FixedPlace                                : "",
                                                                                                    FrmMMKEquipmentList.HasOperationRangeMin?loop.LowerLimit                      : "",
                                                                                                    FrmMMKEquipmentList.HasOperationRangeMax?loop.UpperLimit                      : "",
                                                                                                    FrmMMKEquipmentList.HasOperationRangeUnit?loop.Unit                           : "",
                                                                                                    FrmMMKEquipmentList.HasRemark?eqp.Remark                                      : "" };

                                            eqpNumberInPages++;


                                            if (eqpNumberInPages >= 14)
                                            {
                                                currentPageNumber++;
                                                xlsWorkSheet      = (Microsoft.Office.Interop.Excel.Worksheet)xlsApp.Worksheets[currentPageNumber];
                                                xlsWorkSheet.Name = (currentPageNumber).ToString();
                                                xlsWorkSheet.Activate();

                                                // 图纸格式
                                                // 字体
                                                xlsWorkSheet.get_Range("B7", "S13").Font.Name = "Times New Roman";
                                                xlsWorkSheet.get_Range("B7", "S13").Font.Size = 11f;

                                                // 格式
                                                xlsWorkSheet.get_Range("B7", "S13").HorizontalAlignment = Constants.xlCenter;
                                                xlsWorkSheet.get_Range("B7", "S13").VerticalAlignment   = Constants.xlCenter;
                                                xlsWorkSheet.get_Range("M7", "M13").HorizontalAlignment = Constants.xlGeneral;
                                                xlsWorkSheet.get_Range("M7", "M13").VerticalAlignment   = Constants.xlGeneral;
                                                xlsWorkSheet.get_Range("B7", "S13").WrapText            = true;

                                                //
                                                // 图纸内容
                                                //
                                                // 项目名称
                                                xlsWorkSheet.get_Range("B2", Missing.Value).Value2
                                                    = "项目名称:俄罗斯MMK冷轧公辅EP项目";
                                                // 子系统
                                                xlsWorkSheet.get_Range("B3", Missing.Value).Value2
                                                    = "子系统:" + subSystem.Name;

                                                //
                                                // 图框内容
                                                xlsWorkSheet.Shapes.Item("BTL").Ungroup();
                                                // 专业
                                                xlsWorkSheet.Shapes.Item("DWG_SPECIALITY").TextFrame.Characters(Missing.Value, Missing.Value).Text = _speciality;
                                                // 设计阶段
                                                xlsWorkSheet.Shapes.Item("DESIGN_STAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = _stage;
                                                // 日期
                                                xlsWorkSheet.Shapes.Item("PRINT_DATE").TextFrame.Characters(Missing.Value, Missing.Value).Text = _date;
                                                // 室审
                                                xlsWorkSheet.Shapes.Item("DEPT_CHECKER").TextFrame.Characters(Missing.Value, Missing.Value).Text = _reviewedBy;
                                                // 审核
                                                xlsWorkSheet.Shapes.Item("DWG_CHECKER").TextFrame.Characters(Missing.Value, Missing.Value).Text = _checkedBy;
                                                // 设计
                                                xlsWorkSheet.Shapes.Item("DWG_DESIGN").TextFrame.Characters(Missing.Value, Missing.Value).Text = _designBy;
                                                // 制图
                                                xlsWorkSheet.Shapes.Item("DWG_DRAW").TextFrame.Characters(Missing.Value, Missing.Value).Text = _madeBy;
                                                // 合同号
                                                xlsWorkSheet.Shapes.Item("CONTRACT").TextFrame.Characters(Missing.Value, Missing.Value).Text = _contractNo;
                                                // 图号
                                                xlsWorkSheet.Shapes.Item("DRAWING_NO").TextFrame.Characters(Missing.Value, Missing.Value).Text = _drawingNo;
                                                // 高层代号
                                                xlsWorkSheet.Shapes.Item("=").TextFrame.Characters(Missing.Value, Missing.Value).Text = "=" + _topLevelNo;
                                                // 修改号
                                                xlsWorkSheet.Shapes.Item("REVISE_NO").TextFrame.Characters(Missing.Value, Missing.Value).Text = _revision;
                                                // 页次
                                                if (xlsWorkSheet.Index < pageCount)
                                                {
                                                    xlsWorkSheet.Shapes.Item("PAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = xlsWorkSheet.Index.ToString() + "+";
                                                }
                                                else
                                                {
                                                    xlsWorkSheet.Shapes.Item("PAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = (xlsWorkSheet.Index).ToString();
                                                }

                                                eqpNumberInPages = 7;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    break;

                case DrawingLanguage.English:

                    pageCount = 0;

                    foreach (EQASubSystem subSystem in subSystems)
                    {
                        if ((subSystem.EquipmentsCount % 3 == 0))
                        {
                            pageCount += subSystem.EquipmentsCount / 3;
                        }
                        else
                        {
                            pageCount += Convert.ToInt32(Math.Ceiling(subSystem.EquipmentsCount / 3.0f));
                        }
                    }

                    (xlsApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet).Shapes.Item("BTL").Ungroup();

                    // 图纸格式
                    // 字体
                    (xlsApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet).get_Range("B9", "S14").Font.Name = "Times New Roman";
                    (xlsApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet).get_Range("B9", "S14").Font.Size = 11f;

                    // 格式
                    (xlsApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet).get_Range("B9", "S14").HorizontalAlignment = Constants.xlCenter;
                    (xlsApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet).get_Range("B9", "S14").VerticalAlignment   = Constants.xlCenter;
                    (xlsApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet).get_Range("M9", "M14").HorizontalAlignment = Constants.xlGeneral;
                    (xlsApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet).get_Range("B9", "S14").WrapText            = true;

                    for (int i = 0; i < pageCount - 1; i++)
                    {
                        (xlsApp.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet).Copy(Missing.Value, xlsApp.Worksheets[1 + i]);
                    }

                    currentPageNumber = 0;
                    eqpNumberInPages  = 9;

                    lock (subSystems) {
                        if (subSystems.Count > 0)
                        {
                            for (int i = 0; i < subSystems.Count; i++)
                            {
                                EQASubSystem subSystem = subSystems[i];
                                currentPageNumber++;
                                if (i > 0 && (subSystems[i - 1].EquipmentsCount % 3 == 0))
                                {
                                    currentPageNumber--;
                                }

                                eqpNumberInPages  = 9;
                                xlsWorkSheet      = (Microsoft.Office.Interop.Excel.Worksheet)xlsApp.Worksheets[currentPageNumber];
                                xlsWorkSheet.Name = (currentPageNumber).ToString();
                                xlsWorkSheet.Activate();

                                //
                                // 图纸内容
                                //

                                // 子系统
                                xlsWorkSheet.get_Range("B3", Missing.Value).Value2
                                    = "Sub-system/Подсистема: " + subSystem.Name;

                                //
                                // 图框内容

                                // 专业
                                xlsWorkSheet.Shapes.Item("DWG_SPECIALITY").TextFrame.Characters(Missing.Value, Missing.Value).Text = _speciality;
                                // 设计阶段
                                xlsWorkSheet.Shapes.Item("DESIGN_STAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = _stage;
                                // 日期
                                xlsWorkSheet.Shapes.Item("PRINT_DATE").TextFrame.Characters(Missing.Value, Missing.Value).Text = _date;
                                // 室审
                                xlsWorkSheet.Shapes.Item("DEPT_CHECKER").TextFrame.Characters(Missing.Value, Missing.Value).Text = _reviewedBy;
                                // 审核
                                xlsWorkSheet.Shapes.Item("DWG_CHECKER").TextFrame.Characters(Missing.Value, Missing.Value).Text = _checkedBy;
                                // 设计
                                xlsWorkSheet.Shapes.Item("DWG_DESIGN").TextFrame.Characters(Missing.Value, Missing.Value).Text = _designBy;
                                // 制图
                                xlsWorkSheet.Shapes.Item("DWG_DRAW").TextFrame.Characters(Missing.Value, Missing.Value).Text = _madeBy;
                                // 合同号
                                xlsWorkSheet.Shapes.Item("CONTRACT").TextFrame.Characters(Missing.Value, Missing.Value).Text = _contractNo;
                                // 图号
                                xlsWorkSheet.Shapes.Item("DRAWING_NO").TextFrame.Characters(Missing.Value, Missing.Value).Text = _drawingNo;
                                // 高层代号
                                xlsWorkSheet.Shapes.Item("=").TextFrame.Characters(Missing.Value, Missing.Value).Text = "=" + _topLevelNo;
                                // 修改号
                                xlsWorkSheet.Shapes.Item("REVISE_NO").TextFrame.Characters(Missing.Value, Missing.Value).Text = _revision;
                                // 页次
                                if (xlsWorkSheet.Index < pageCount)
                                {
                                    xlsWorkSheet.Shapes.Item("PAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = xlsWorkSheet.Index.ToString() + "+";
                                }
                                else
                                {
                                    xlsWorkSheet.Shapes.Item("PAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = (xlsWorkSheet.Index).ToString();
                                }


                                if (subSystem.Loops.Count > 0)
                                {
                                    for (int j = 0; j < subSystem.Loops.Count; j++)
                                    {
                                        EQALoop loop = subSystem.Loops[j];
                                        if (loop.Equipments.Count > 0)
                                        {
                                            // 回路号
                                            xlsWorkSheet.get_Range("B" + eqpNumberInPages.ToString(), Missing.Value).Value2
                                                = FrmMMKEquipmentList.HasLoopNo ? loop.LoopNo : "";

                                            //检测与控制项目
                                            string item = loop.Location + loop.ProcParameter +
                                                          (loop.HasLocalIndication ? @"/就地显示" : "") +
                                                          (loop.HasLocalOperating ? @"/就地操作" : "") +
                                                          (loop.HasComputerIndication ? @"/显示" : "") +
                                                          (loop.HasComputerOperating ? @"/操作" : "") +
                                                          (loop.HasRecording ? @"/记录" : "") +
                                                          (loop.HasAlarm ? @"/报警" : "") +
                                                          (loop.HasControlling ? @"/调节" : "") +
                                                          (loop.HasInterlock ? @"/联锁" : "");

                                            xlsWorkSheet.get_Range("D" + eqpNumberInPages.ToString(), Missing.Value).Value2
                                                = FrmMMKEquipmentList.HasItems ? item : "";
                                        }

                                        for (int m = 0; m < loop.Equipments.Count; m++)
                                        {
                                            EQAEquipment eqp = loop.Equipments[m];
                                            if (!eqp.IsEquipment)
                                            {
                                                continue;
                                            }

                                            // 位号
                                            xlsWorkSheet.get_Range("C" + eqpNumberInPages.ToString(), Missing.Value).Value2
                                                = FrmMMKEquipmentList.HasTagNo ? eqp.TagNo : "";

                                            // 其他项目
                                            xlsWorkSheet.get_Range("E" + eqpNumberInPages.ToString(), "S" + eqpNumberInPages.ToString()).Value2
                                                = new object[] { FrmMMKEquipmentList.HasEqpName?eqp.Name:"",
                                                                                                    FrmMMKEquipmentList.HasEqpType?eqp.EqpType:"",
                                                                                                    FrmMMKEquipmentList.HasMeasuringRangeMin?eqp.LowerLimit:"",
                                                                                                    FrmMMKEquipmentList.HasMeasuringRangeMax?eqp.UpperLimit:"",
                                                                                                    FrmMMKEquipmentList.HasMeasuringRangeUnit?eqp.Unit:"",
                                                                                                    FrmMMKEquipmentList.HasInputSignal?eqp.InputSignal:"",
                                                                                                    FrmMMKEquipmentList.HasOutputSignal?eqp.OutputSignal:"",
                                                                                                    FrmMMKEquipmentList.HasPowerSupply?eqp.PowerSupply:"",
                                                                                                    FrmMMKEquipmentList.HasSpec?eqp.Spec1 + ",\n" + eqp.Spec2:"",
                                                                                                    FrmMMKEquipmentList.HasQuantity?eqp.Quantity.ToString():"",
                                                                                                    FrmMMKEquipmentList.HasLocation?eqp.FixedPlace:"",
                                                                                                    FrmMMKEquipmentList.HasOperationRangeMin?loop.LowerLimit:"",
                                                                                                    FrmMMKEquipmentList.HasOperationRangeMax?loop.UpperLimit:"",
                                                                                                    FrmMMKEquipmentList.HasOperationRangeUnit?loop.Unit:"",
                                                                                                    FrmMMKEquipmentList.HasRemark?eqp.Remark:"" };

                                            xlsWorkSheet.get_Range("B" + (eqpNumberInPages + 1).ToString(), "S" + (eqpNumberInPages + 1).ToString()).Value2
                                                = xlsWorkSheet.get_Range("B" + eqpNumberInPages.ToString(), "S" + eqpNumberInPages.ToString()).Value2;

                                            eqpNumberInPages += 2;

                                            if (eqpNumberInPages >= 15)
                                            {
                                                currentPageNumber++;
                                                xlsWorkSheet      = (Microsoft.Office.Interop.Excel.Worksheet)xlsApp.Worksheets[currentPageNumber];
                                                xlsWorkSheet.Name = (currentPageNumber).ToString();
                                                xlsWorkSheet.Activate();

                                                //
                                                // 图纸内容
                                                //
                                                // 子系统
                                                xlsWorkSheet.get_Range("B3", Missing.Value).Value2
                                                    = "Sub-system/Подсистема: " + subSystem.Name;

                                                //
                                                // 图框内容

                                                // 专业
                                                xlsWorkSheet.Shapes.Item("DWG_SPECIALITY").TextFrame.Characters(Missing.Value, Missing.Value).Text = _speciality;
                                                // 设计阶段
                                                xlsWorkSheet.Shapes.Item("DESIGN_STAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = _stage;
                                                // 日期
                                                xlsWorkSheet.Shapes.Item("PRINT_DATE").TextFrame.Characters(Missing.Value, Missing.Value).Text = _date;
                                                // 室审
                                                xlsWorkSheet.Shapes.Item("DEPT_CHECKER").TextFrame.Characters(Missing.Value, Missing.Value).Text = _reviewedBy;
                                                // 审核
                                                xlsWorkSheet.Shapes.Item("DWG_CHECKER").TextFrame.Characters(Missing.Value, Missing.Value).Text = _checkedBy;
                                                // 设计
                                                xlsWorkSheet.Shapes.Item("DWG_DESIGN").TextFrame.Characters(Missing.Value, Missing.Value).Text = _designBy;
                                                // 制图
                                                xlsWorkSheet.Shapes.Item("DWG_DRAW").TextFrame.Characters(Missing.Value, Missing.Value).Text = _madeBy;
                                                // 合同号
                                                xlsWorkSheet.Shapes.Item("CONTRACT").TextFrame.Characters(Missing.Value, Missing.Value).Text = _contractNo;
                                                // 图号
                                                xlsWorkSheet.Shapes.Item("DRAWING_NO").TextFrame.Characters(Missing.Value, Missing.Value).Text = _drawingNo;
                                                // 高层代号
                                                xlsWorkSheet.Shapes.Item("=").TextFrame.Characters(Missing.Value, Missing.Value).Text = "=" + _topLevelNo;
                                                // 修改号
                                                xlsWorkSheet.Shapes.Item("REVISE_NO").TextFrame.Characters(Missing.Value, Missing.Value).Text = _revision;
                                                // 页次
                                                if (xlsWorkSheet.Index < pageCount)
                                                {
                                                    xlsWorkSheet.Shapes.Item("PAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = xlsWorkSheet.Index.ToString() + "+";
                                                }
                                                else
                                                {
                                                    xlsWorkSheet.Shapes.Item("PAGE").TextFrame.Characters(Missing.Value, Missing.Value).Text = (xlsWorkSheet.Index).ToString();
                                                }

                                                eqpNumberInPages = 9;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    break;

                default:
                    break;
                }

                return(true);
            } catch (Exception ex) {
                return(false);
            }


            //} finally {
            //    IntPtr t = new IntPtr(xlsApp.Hwnd);

            //    int k = 0;
            //    GetWindowThreadProcessId(t, out k);
            //    System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
            //    p.Kill();
            //}
        }
Exemplo n.º 10
0
        private void AllClearButton_Click(object sender, System.EventArgs e)
        {
            if (foodStoreDataGridView.Rows.Count >= 1)
            {
                System.Windows.Forms.DialogResult dialogResult =
                    Mbb.Windows.Forms.MessageBox.Show
                        (text: $"آیا همه اطلاعات حذف گردد؟!",
                        caption: "هشدار",
                        icon: Mbb.Windows.Forms.MessageBoxIcon.Warning,
                        button: Mbb.Windows.Forms.MessageBoxButtons.YesNo);

                if (dialogResult == System.Windows.Forms.DialogResult.Yes)                //----جهت حذف کامل اطلاعات مربوط به نوشیدنی
                {
                    List <Models.Food> foods = new List <Models.Food>();

                    using (Models.DataBaseContext dataBaseContext = new Models.DataBaseContext())
                    {
                        foods =
                            dataBaseContext.Foods
                            .OrderBy(current => current.FoodName)
                            .ToList();

                        if (foods != null)
                        {
                            foreach (var item in foods)                             //---توسط این کد با پیمایش در لیست نوشیدنی یکی یکی ایتمهای موجود در لیست نوشیدنی را حذف میکند.
                            {
                                dataBaseContext.Foods.Remove(item);
                                dataBaseContext.SaveChanges();
                            }
                        }
                        else if (foods == null)
                        {
                            return;
                        }

                        #region EventLog
                        Username   = Program.AuthenticatedUser.Username;
                        FullName   = $"{Program.AuthenticatedUser.First_Name} {Program.AuthenticatedUser.Last_Name}";
                        EventDate  = $"{Infrastructure.Utility.PersianCalendar(System.DateTime.Now)}";
                        EventTime  = $"{Infrastructure.Utility.ShowTime()}";
                        EventTitle = $"حذف کامل اطلاعات غذا.";

                        Infrastructure.Utility.EventLog
                            (username: Username,
                            fullName: FullName,
                            eventDate: EventDate,
                            eventTime: EventTime,
                            eventTitle: EventTitle);
                        #endregion /EventLog

                        FoodLoader();
                    }

                    Infrastructure.Utility.WindowsNotification
                        (message: "کلیه اطلاعات غذا حذف گردید!",
                        caption: Infrastructure.PopupNotificationForm.Caption.موفقیت);
                }
            }
            else
            {
                Mbb.Windows.Forms.MessageBox.Show
                    (text: $"موردی برای حذف وجود ندارد!",
                    caption: "اطلاع",
                    icon: Mbb.Windows.Forms.MessageBoxIcon.Information,
                    button: Mbb.Windows.Forms.MessageBoxButtons.Ok);
                return;
            }
        }
Exemplo n.º 11
0
 private void Button_Click(object sender, RoutedEventArgs e)
 {
     object Result = Enum.Parse(typeof(System.Windows.Forms.DialogResult), ((Button)sender).Name.ToString());
     _DialogResult = (System.Windows.Forms.DialogResult)Result;
     this.Close();
 }
        void FillVault()
        {
            try
            {

                //Fill transaction     
                Dispatcher.Invoke(new Action(() =>
                {
                    if (cmbTransactionReason.SelectedIndex < 1)
                    {
                        lbl_Status.Text = Application.Current.FindResource("Vault_MessageID6") as string;
                        cmbTransactionReason.Focus();
                        return;
                    }
                    if (_IsStandardFill)
                    {
                        ucValueCalc.ValueText = VaultStandardFillAmount.ToString();
                    }

                    try // In case of error proceed with fill 
                    {
                        if (Decimal.Parse(_DrVaultBalance["Capacity"].ToString()) < (Decimal.Parse(ucValueCalc.ValueText) + Decimal.Parse(txt_CurrentBalance.Text)))
                        {
                            lbl_Status.Text = Application.Current.FindResource("Vault_MessageID17") as string + _DrVaultBalance["Capacity"].ToString();
                            return;
                        }

                    }
                    catch (Exception Ex)
                    {
                        ExceptionManager.Publish(Ex);
                    }
                    if (ucValueCalc.ValueText == string.Empty || Decimal.Parse(ucValueCalc.ValueText) <= 0)
                    {
                        if (_FillType.ToLower() == "adjustment")
                            lbl_Status.Text = Application.Current.FindResource("Vault_MessageID11") as string;
                        else
                            lbl_Status.Text = Application.Current.FindResource("Vault_MessageID3") as string;
                        return;
                    }
                    string strMsg = _IsStandardFill ? "standard fill" : ((_FillType.ToLower() == "adjustment") ? "positive adjustment" : _FillType.ToLower());
                    
                    System.Windows.Forms.DialogResult dlgResult = new System.Windows.Forms.DialogResult();
                    if (Settings.ShowVaultConfirmMessage)
                    {
                        dlgResult = MessageBox.ShowBox("Vault_MessageID8", BMC_Icon.Question, BMC_Button.YesNo, strMsg.ToLower(), ExtensionMethods.GetCurrencySymbol(string.Empty) + " " + ucValueCalc.ValueText);
                        if (dlgResult == System.Windows.Forms.DialogResult.No)
                        {
                            ucValueCalc.ValueText = "0.00";
                            ucValueCalc.s_UnformattedText = "";
                            return;
                        }
                    }

                    int iResult = 0;
                    LogManager.WriteLog("CFillVault:Start FillVault ", LogManager.enumLogLevel.Debug);
                    DataRow Dr = objVault.FillVault(int.Parse(cmb_DeviceName.SelectedValue.ToString()), Decimal.Parse(ucValueCalc.ValueText), Decimal.Parse(txt_CurrentBalance.Text), 0, _FillType, int.Parse(cmbTransactionReason.SelectedValue.ToString()), ref iResult, _sendAlert).Rows[0];

                    LogManager.WriteLog("CFillVault:FillVault Complete ", LogManager.enumLogLevel.Debug);
                    AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                    {
                        AuditModuleName = ModuleName.Vault,
                        Audit_Screen_Name = "Vault Transaction",
                        Audit_Desc = "Updating Vault:ID " + cmb_DeviceName.SelectedValue.ToString() + " Transaction : " + _FillType + " Device Name:" + cmb_DeviceName.Text + " Amount:" + ucValueCalc.ValueText,
                        AuditOperationType = OperationType.ADD,
                    });

                    _DrVaultBalance = Dr;

                    if (Settings.ShowVaultPrintMessage)
                    {
                        //Get slip print confirmation
                        dlgResult = MessageBox.ShowBox("Vault_MessageID10", BMC_Icon.Question, BMC_Button.YesNo, "");
                        if (dlgResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            this.Print(Dr, strMsg);
                        }
                    }
                    txt_SerialNo.Text = Dr["Serial_NO"].ToString();
                    txt_AlertLevel.Text = Dr["Alert_Level"].ToString();
                    //txt_FillAmount.Text = Dr["FillAmount"].ToString();
                    //txt_TotalFillAmount.Text = Dr["TotalAmountOnFill"].ToString();
                    txt_CurrentBalance.Text = Dr["CurrentBalance"].ToString();
                    txt_Manufacturer.Text = Dr["Manufacturer_Name"].ToString();
                    txt_Type.Text = Dr["Type_Prefix"].ToString();
                    ucValueCalc.s_UnformattedText = string.Empty;
                    lbl_Status.Text = string.Empty;
                    ucValueCalc.txtDisplay.Clear();
                    ucValueCalc.textBox1.Clear();
                    ucValueCalc.ValueText = string.Empty;
                    DisableControls();
                    cmbTransactionReason.SelectedIndex = 0;
                    lbl_Status.Text = Application.Current.FindResource("Vault_MessageID1") as string;

                }));
            }
            catch (Exception Ex)
            {
                ExceptionManager.Publish(Ex);
            }
            //RefreshVaultBalance();
        }
 private void BtnKhongDongY_Click(System.Object sender, System.EventArgs e)
 {
     m_Result = System.Windows.Forms.DialogResult.No;
     if (ClickMeEvent != null)
         ClickMeEvent();
 }
 private void BtnBoQua_Click(System.Object sender, System.EventArgs e)
 {
     m_Result = System.Windows.Forms.DialogResult.Cancel;
     if (ClickMeEvent != null)
         ClickMeEvent();
 }
        private void button_Click(object sender, RoutedEventArgs e)
        {
            bool isValid = false;
            RTOnlineTicketDetail objTicketDetail = null;
           
            double redeemTicketAmount = 0;

            bool IsCashDispenseError = false;
            try
            {

                if (isScannerFired) //check done not to fire the verify event twice while verifying a ticket using scanner
                {
                    isScannerFired = false;
                    return;
                }
                ClearAll(true);
                TextBlock_11.Text = string.Empty;
                txtAmount.Text = string.Empty;               
                btnVerify.IsEnabled = false;
                if ((sender is System.Windows.Controls.TextBox))
                    isScannerFired = true;
                else
                    isScannerFired = false;

                if (this.ucValueCalc.txtDisplay.Text.Trim().Length > 0)
                {
                    if (this.ucValueCalc.txtDisplay.Text.Trim().Length < 4 )
                    {
                        MessageBox.ShowBox("MessageID403", BMC_Icon.Error);
                        this.txtStatus.Visibility = Visibility.Hidden;
                        this.ucValueCalc.txtDisplay.Text = String.Empty;
                        return;
                    }

                    IRedeemOnlineTicket objCashDeskOper = RedeemOnlineTicketBusinessObject.CreateInstance();
                    objTicketDetail = new RTOnlineTicketDetail();

                    objTicketDetail.ClientSiteCode = Settings.SiteCode;
                    objTicketDetail.TicketString = this.ucValueCalc.txtDisplay.Text.Trim();
                    objTicketDetail.HostSiteCode = objTicketDetail.TicketString.Substring(0, 4);
                    objTicketDetail.RedeemedMachine = System.Environment.MachineName;

                    objTicketDetail = objCashDeskOper.GetRedeemTicketAmount(objTicketDetail);

                    if (objTicketDetail.TicketStatusCode == -990) //TIS Error (If any)
                    {
                        MessageBox.ShowBox(objTicketDetail.TicketErrorMessage, BMC_Icon.Error, true);
                        disptimerRedeem.Stop();
                        this.txtStatus.Visibility = Visibility.Hidden;
                        return;
                    }

                    if (objTicketDetail.TicketStatusCode == -234) //Exception Occured
                    {
                        MessageBox.ShowBox("MessageID425", BMC_Icon.Error);
                        disptimerRedeem.Stop();
                        this.txtStatus.Visibility = Visibility.Hidden;
                        return;
                    }

                    if (objTicketDetail.TicketStatusCode == -99) //Included for Cross Ticketing
                    {
                        MessageBox.ShowBox("MessageID403", BMC_Icon.Error);
                        disptimerRedeem.Stop();
                        this.txtStatus.Visibility = Visibility.Hidden;
                        this.ucValueCalc.txtDisplay.Text = String.Empty;
                        return;
                    }

                   
                   
                        if (objTicketDetail.TicketStatusCode == 250) //Any/specific player card required for TIS
                        {
                            bool ValidCard = false;
                            int PlayerCardClose = 0;
                            


                            if (objTicketDetail.CardRequired == 2)
                            {
                                PlayerCardValidation objPlayerCardValidation = new PlayerCardValidation(objTicketDetail.CardRequired);
                                objPlayerCardValidation.ShowDialogEx(this);
                                ValidCard = objPlayerCardValidation.valid;
                                PlayerCardClose = objPlayerCardValidation.Close;

                                if (PlayerCardClose == 1)
                                {
                                    this.ucValueCalc.txtDisplay.Text = String.Empty;
                                    this.ucValueCalc.txtDisplay.Focus();
                                    return;
                                }

                                else if (!ValidCard)
                                {
                                    MessageBox.ShowBox("PlayerCardRedeem6", BMC_Icon.Error);
                                    this.ucValueCalc.txtDisplay.Text = String.Empty;
                                    this.ucValueCalc.txtDisplay.Focus();
                                    return;
                                }

                            }
                            else if (objTicketDetail.CardRequired == 1)
                            {
                                PlayerCardValidation objPlayerCardValidation = new PlayerCardValidation(objTicketDetail.CardRequired, objTicketDetail.PlayerCardNumber);
                                objPlayerCardValidation.ShowDialogEx(this);
                                ValidCard = objPlayerCardValidation.valid;
                                PlayerCardClose = objPlayerCardValidation.Close;
                                if (PlayerCardClose == 1)
                                {
                                    this.ucValueCalc.txtDisplay.Text = String.Empty;
                                    this.ucValueCalc.txtDisplay.Focus();
                                    return;
                                }
                                else if (!ValidCard)
                                {
                                    MessageBox.ShowBox("PlayerCardRedeem6", BMC_Icon.Error);
                                    this.ucValueCalc.txtDisplay.Text = String.Empty;
                                    this.ucValueCalc.txtDisplay.Focus();
                                    return;
                                }
                            }

                            objTicketDetail.TicketStatusCode = 0;
                        }
                    

                    int ticketAmount = Convert.ToInt32(objTicketDetail.RedeemedAmount);

                    redeemTicketAmount = ticketAmount / 100;

                    objTicketDetail.CustomerId = Custid;

                    this.txtStatus.Visibility = Visibility.Visible;
                    this.txtStatus.Text = "VALIDATING.";
                    disptimerRedeem.IsEnabled = true;
                    disptimerRedeem.Start();


                    //if ((objCashDeskOper.CheckSDGTicket(objTicketDetail.TicketString) == 0) && (Settings.RedeemConfirm))
                    if (objTicketDetail.TicketStatusCode == 0 && (Settings.RedeemConfirm))
                    {
                        disptimerRedeem.Stop();
                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                        {
                            _diagResult = MessageBox.ShowBox("MessageID225", BMC_Icon.Question, BMC_Button.YesNo);
                        }
                        else
                        {
                            _diagResult = System.Windows.Forms.DialogResult.Yes;
                        }
                        if (_diagResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            #region ITALY CODE COMMENTED
                            //if (Settings.RegulatoryEnabled == true && Settings.RegulatoryType == "AAMS")
                            //{
                            //    ProcessCancelled = false;
                            //    if (ticketStatus == 0)
                            //    {
                            //        if (redeemTicketAmount >= Settings.RedeemTicketCustomer_Min && redeemTicketAmount <= Settings.RedeemTicketCustomer_Max)
                            //        {
                            //            customerDetails = new BMC.Presentation.POS.Views.CustomerDetails();
                            //            customerDetails.delCustomerUpdated += new BMC.Presentation.POS.Views.CustomerDetails.CustomerUpdateHandler(delCustomerUpdated);
                            //            customerDetails.delCustomerCancelled += new BMC.Presentation.POS.Views.CustomerDetails.CustomerCancelHandler(delCustomerCancelled);
                            //            Owner = Window.GetWindow(this);
                            //            customerDetails.ShowDialog();
                            //        }
                            //        else if (redeemTicketAmount >= Settings.RedeemTicketCustomer_BankAcctNo)
                            //        {
                            //            customerDetails = new BMC.Presentation.POS.Views.CustomerDetails(true);
                            //            customerDetails.delCustomerUpdated += new BMC.Presentation.POS.Views.CustomerDetails.CustomerUpdateHandler(delCustomerUpdated);
                            //            customerDetails.delCustomerCancelled += new BMC.Presentation.POS.Views.CustomerDetails.CustomerCancelHandler(delCustomerCancelled);
                            //            Owner = Window.GetWindow(this);
                            //            customerDetails.ShowDialog();
                            //        }

                            //        if (ProcessCancelled)
                            //        {
                            //            MessageBox.ShowBox("MessageID299", BMC_Icon.Information);
                            //            this.ucValueCalc.txtDisplay.Text = string.Empty;
                            //            return;
                            //        }
                            //    }
                            //} 
                            #endregion

                            objTicketDetail = objCashDeskOper.RedeemOnlineTicket(objTicketDetail);
                            isValid = objTicketDetail.ValidTicket;
                        }
                        else
                        {
                            disptimerRedeem.Start();
                            this.txtStatus.Visibility = Visibility.Hidden;
                            return;
                        }
                        disptimerRedeem.Start();
                    }
                    //else if ((objCashDeskOper.CheckSDGTicket(objTicketDetail.TicketString) == -3) && (Settings.RedeemConfirm)
                    else if (objTicketDetail.TicketStatusCode == -3 && (Settings.RedeemConfirm) && Settings.RedeemExpiredTicket)
                    {
                        disptimerRedeem.Stop();

                        CAuthorize objAuthorize = null;
                        //Manoj 26th Aug 2010. CR383384
                        //RedeemExpiredTicket functionality has been implmented for Winchells.
                        //So, in settings RedeemExpiredTicket will be True for Winchells, for rest it will be False.
                        //So we dont need the following if condition.
                        //if (Settings.Client != null && Settings.Client.ToLower() == "winchells")
                        //{
                        objAuthorize = new CAuthorize("CashdeskOperator.Authorize.cs.ReedemExpiredTicket");
                        objAuthorize.User = Security.SecurityHelper.CurrentUser;
                        string Cur_User_Name = Security.SecurityHelper.CurrentUser.Last_Name + ", " + Security.SecurityHelper.CurrentUser.First_Name;
                        objTicketDetail.RedeemedUser = Cur_User_Name;
                        
                        if (!Security.SecurityHelper.HasAccess("CashdeskOperator.Authorize.cs.ReedemExpiredTicket"))
                        {
                            objAuthorize.ShowDialogEx(this);
                            
                            string Auth_User_Name = objAuthorize.User.UserName;
                            if (objAuthorize.User.Last_Name != null && objAuthorize.User.First_Name != null)
                            {
                                Auth_User_Name = objAuthorize.User.Last_Name + ", " + objAuthorize.User.First_Name;
                            }
                            else
                            {
                                Auth_User_Name = objAuthorize.User.UserName;
                            }

                            objTicketDetail.RedeemedUser = Auth_User_Name;
                            
                            if (!objAuthorize.IsAuthorized)
                            {
                                ClearAll(false);
                                return;
                            }
                        }
                        else
                        {
                            objAuthorize.IsAuthorized = true;
                        }
                        //}

                        if (objAuthorize != null && objAuthorize.IsAuthorized)
                        {
                            objTicketDetail.AuthorizedUser_No = objAuthorize.User.SecurityUserID;
                            objTicketDetail.Authorized_Date = DateTime.Now;

                            AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                            {

                                AuditModuleName = ModuleName.Voucher,
                                Audit_Screen_Name = "Vouchers|RedeemVoucher",
                                Audit_Desc = "Voucher Number-" + objTicketDetail.TicketString,
                                AuditOperationType = OperationType.MODIFY,
                                Audit_Field = "AuthorizedUser_No",
                                Audit_New_Vl = Security.SecurityHelper.CurrentUser.SecurityUserID.ToString()
                            });

                        }
                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                        {
                            _diagResult = MessageBox.ShowBox("MessageID225", BMC_Icon.Question, BMC_Button.YesNo);
                        }
                        else
                        {
                            _diagResult = System.Windows.Forms.DialogResult.Yes;
                        }
                        if (_diagResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            #region ITALY CODE COMMENTED
                            //if (Settings.RegulatoryEnabled == true && Settings.RegulatoryType == "AAMS")
                            //{
                            //    ProcessCancelled = false;
                            //    if (ticketStatus == 0)
                            //    {
                            //        if (redeemTicketAmount >= Settings.RedeemTicketCustomer_Min && redeemTicketAmount <= Settings.RedeemTicketCustomer_Max)
                            //        {
                            //            customerDetails = new BMC.Presentation.POS.Views.CustomerDetails();
                            //            customerDetails.delCustomerUpdated += new BMC.Presentation.POS.Views.CustomerDetails.CustomerUpdateHandler(delCustomerUpdated);
                            //            customerDetails.delCustomerCancelled += new BMC.Presentation.POS.Views.CustomerDetails.CustomerCancelHandler(delCustomerCancelled);
                            //            Owner = Window.GetWindow(this);
                            //            customerDetails.ShowDialog();
                            //        }
                            //        else if (redeemTicketAmount >= Settings.RedeemTicketCustomer_BankAcctNo)
                            //        {
                            //            customerDetails = new BMC.Presentation.POS.Views.CustomerDetails(true);
                            //            customerDetails.delCustomerUpdated += new BMC.Presentation.POS.Views.CustomerDetails.CustomerUpdateHandler(delCustomerUpdated);
                            //            customerDetails.delCustomerCancelled += new BMC.Presentation.POS.Views.CustomerDetails.CustomerCancelHandler(delCustomerCancelled);
                            //            Owner = Window.GetWindow(this);
                            //            customerDetails.ShowDialog();
                            //        }

                            //        if (ProcessCancelled)
                            //        {
                            //            MessageBox.ShowBox("MessageID299", BMC_Icon.Information);
                            //            this.ucValueCalc.txtDisplay.Text = string.Empty;
                            //            return;
                            //        }
                            //    }
                            //}

                            #endregion
                            objTicketDetail = objCashDeskOper.RedeemOnlineTicket(objTicketDetail);
                            isValid = objTicketDetail.ValidTicket;
                        }
                        else
                        {
                            disptimerRedeem.Start();
                            this.txtStatus.Visibility = Visibility.Hidden;
                            return;
                        }
                        disptimerRedeem.Start();
                    }
                    else
                    {
                        objTicketDetail = objCashDeskOper.RedeemOnlineTicket(objTicketDetail);
                        isValid = objTicketDetail.ValidTicket;
                    }

                    if (objTicketDetail.TicketStatus == "MessageID210")
                        objTicketDetail.TicketStatus = Application.Current.FindResource(objTicketDetail.TicketStatus).ToString() +
                            "(" + CommonUtilities.GetCurrency(Convert.ToDouble(objTicketDetail.TicketValue / 100)) + ")";
                    else
                        objTicketDetail.TicketStatus = Application.Current.FindResource(objTicketDetail.TicketStatus).ToString();

                    IsCashDispenseError = true;
                    if (isValid && objTicketDetail.RedeemedMachine != null && objTicketDetail.RedeemedMachine != string.Empty)
                    {
                        try
                        {
                            //DateTime PrintDate;
                            //string strbar_pos = objCashDeskOper.GetTicketPrintDevice(objTicketDetail.TicketString, out PrintDate);
                            DateTime PrintDate = DateTime.Now;
                            string strbar_pos = objCashDeskOper.GetTicketPrintDevice(objTicketDetail.TicketString, out PrintDate);
                            //TextBlock_11.Text = "#" + strbar_pos + PrintDate.ToString().Replace("/", "").Replace(":", "").Replace("AM", "0").Replace("PM", "1").Replace(" ", "");
                            //TextBlock_11.Text = "#" + objTicketDetail.PrintedDevice + objTicketDetail.PrintedDate.ToString().Replace("/", "").Replace(":", "").Replace("AM", "0").Replace("PM", "1").Replace(" ", "");
                            if (objTicketDetail.RedeemedDate == null || objTicketDetail.RedeemedDate.ToString().Trim().Equals(string.Empty))
                            {
                                TextBlock_11.Text = string.Empty;
                            }
                            else
                            {
                                TextBlock_11.Text = "#" + strbar_pos + objTicketDetail.RedeemedDate.ToString("ddMMyyyyHHmmss");
                            }

                            txtAmount.Text = objTicketDetail.RedeemedAmount.GetUniversalCurrencyFormat();
                            if (!objTicketDetail.TicketStatus.Trim().ToUpper().Equals("ALREADY CLAIMED"))
                            {
                                #region GCD
                                if (Settings.IsGloryCDEnabled && Settings.CashDispenserEnabled)
                                {
                                    LogManager.WriteLog(string.Format("Process Redeem Voucher: {2} for Bar Postion: {0} - Amount: {1} in cents", strbar_pos, ticketAmount, objTicketDetail.TicketString), LogManager.enumLogLevel.Info);

                                    //implement Cash Dispenser
                                    LogManager.WriteLog(string.Format("Amount: {0:0.00} Sending to Cash Dispenser ", ticketAmount), LogManager.enumLogLevel.Info);
                                    LoadingWindow ld = new LoadingWindow(Window.GetWindow(this), ModuleName.Voucher, TextBlock_11.Text , strbar_pos, ticketAmount);
                                    ld.Topmost = true;
                                    ld.ShowDialogEx(this);
                                    Result res = ld.Result;
                                    if (!res.IsSuccess)
                                    {
                                        IsCashDispenseError = false;
                                        this.txtStatus.Text = res.error.Message;
                                        LogManager.WriteLog(string.Format("Unable to Dispense Cash - Amount: {0}", ticketAmount), LogManager.enumLogLevel.Info);
                                        LogManager.WriteLog("Rollback Redeem Voucher Process", LogManager.enumLogLevel.Info);
                                        AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                                        {
                                            AuditModuleName = ModuleName.Voucher,
                                            Audit_Screen_Name = "Vouchers|RedeemVoucher",
                                            Audit_Desc = "Rollback redeem voucher:" + objTicketDetail.TicketString + " due to cash dispenser error",
                                            AuditOperationType = OperationType.MODIFY,
                                            Audit_Old_Vl = "iPayDeviceid:" + objTicketDetail.RedeemedDevice + ";dtPaid:" + objTicketDetail.RedeemedDate.GetUniversalDateTimeFormat() + ";Customerid:" + objTicketDetail.CustomerId.ToString()
                                        });
                                        objCashDeskOper.RollbackRedeemTicket(objTicketDetail.TicketString);
                                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                                        {
                                            BMC.Presentation.MessageBox.ShowBox(res.error.Message, res.error.MessageType.Equals("Error") ? BMC_Icon.Error : BMC_Icon.Information, true);
                                        }
                                    }
                                    else
                                    {
                                        LogManager.WriteLog(string.Format("Cash Dispensed Successfully - Amount: {0}", ticketAmount), LogManager.enumLogLevel.Info);

                                        IsCashDispenseError = true;
                                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                                        {
                                            BMC.Presentation.MessageBox.ShowBox(res.error.Message, res.error.MessageType.Equals("Error") ? BMC_Icon.Error : BMC_Icon.Information, true);
                                        }

                                    }
                                }
                                #endregion
                            }

                        }
                        catch (Exception Ex)
                        {
                            LogManager.WriteLog("Error showing Voucher Info :" + Ex.Message, LogManager.enumLogLevel.Error);
                        }
                    }

                    if (objTicketDetail.ShowOfflineTicketScreen)
                    {
                        int result;

                        if (objTicketDetail.HostSiteCode == Settings.SiteCode) // Offline Tickets redemption is valid only for local site code
                            result = objCashDeskOper.CheckSDGOfflineTicket(objTicketDetail.TicketString);
                        else
                            result = -14;

                        if (result == -14)// Site Code Mismatch
                        {
                            this.txtStatus.Visibility = Visibility.Visible;
                            this.txtStatus.Text = Application.Current.FindResource("MessageID312") as string;
                            this.txtStatus.Background = System.Windows.Media.Brushes.Red;
                            return;
                        }
                        else
                        {
                            frmRedeemOffline = new BMC.Presentation.POS.Views.CRedeemOfflineTicket();
                            frmRedeemOffline.TicketNumber = ucValueCalc.txtDisplay.Text.Trim();
                            frmRedeemOffline.ShowDialogEx(this);
                            if(frmRedeemOffline.IsSuccessfull)
                            {
                                this.ucValueCalc.txtDisplay.Text = frmRedeemOffline.TicketNumber;
                                button_Click(sender, e);
                            }
                            else
                            {
                                this.ucValueCalc.txtDisplay.Text = string.Empty;
                                this.txtStatus.Clear();
                            }
                        }
                    }
                    else
                    {
                        if (Settings.IsGloryCDEnabled && (!IsCashDispenseError))
                        {
                            disptimerRedeem.Stop();
                            this.txtStatus.Visibility = Visibility.Visible;
                            this.txtStatus.Background = System.Windows.Media.Brushes.Red;
                            TextBlock_11.Text = string.Empty;
                            txtAmount.Text = string.Empty;
                            System.Threading.Thread.Sleep(100);
                            //System.Threading.Thread.CurrentThread
                            disptimerRedeem.Start();
                        }
                        else
                        {
                            this.txtStatus.Text = objTicketDetail.TicketStatus;
                            //"(" + CommonUtilities.GetCurrency(Convert.ToDouble(TicketDetail.TicketValue / 100)) + ")";
                            if (Application.Current.FindResource("MessageID219").ToString() == objTicketDetail.TicketStatus)
                            {
                                bisTicketExpired = true;
                            }
                            this.txtWarning.Text = objTicketDetail.TicketWarning;
                            if (!objTicketDetail.ValidTicket)
                            {
                                this.txtStatus.Background = System.Windows.Media.Brushes.Red;

                                AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                                {

                                    AuditModuleName = ModuleName.Voucher,
                                    Audit_Screen_Name = "Vouchers|RedeemVoucher",
                                    Audit_Desc = "Invalid Voucher Redemption Attempt",
                                    AuditOperationType = OperationType.MODIFY,
                                    Audit_Field = "Voucher Number",
                                    Audit_New_Vl = objTicketDetail.TicketString
                                });

                            }
                            else
                            {
                                this.txtStatus.Background = System.Windows.Media.Brushes.White;

                                AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                                {

                                    AuditModuleName = ModuleName.Voucher,
                                    Audit_Screen_Name = "Vouchers|RedeemVoucher",
                                    Audit_Desc = "Voucher Number-" + objTicketDetail.TicketString,
                                    AuditOperationType = OperationType.ADD,
                                    Audit_Field = "Voucher Status",
                                    Audit_New_Vl = objTicketDetail.TicketStatus
                                });

                                //Cross Ticketing- Insert Local Record 
                                if (!string.IsNullOrEmpty(objTicketDetail.VoucherXMLData))
                                {
                                    objTicketDetail.RedeemedUser = Security.SecurityHelper.CurrentUser.UserName;
                                    objCashDeskOper.ImportVoucherDetails(objTicketDetail);
                                }

                                if (objTicketDetail.TicketStatus.Contains(Application.Current.FindResource("MessageID210").ToString()))
                                {
                                    //disptimerRedeem.Stop();

                                    Action act = new Action(() =>
                                    {
                                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                                        {
                                            if (IsCashDispenseError)
                                            {
                                                if (Settings.IsGloryCDEnabled)
                                                {
                                                    disptimerRedeem.Stop();
                                                    this.txtStatus.Visibility = Visibility.Visible;
                                                }
                                                else
                                                {
                                                    this.ClearAll(false);
                                                }
                                                MessageBox.ShowBox("MessageID377", BMC_Icon.Information);
                                            }


                                        }
                                        else
                                        {
                                            this.txtStatus.Text = Application.Current.FindResource("MessageID377").ToString();
                                            txtAmount.Text = Convert.ToDecimal(objTicketDetail.TicketValue / 100).GetUniversalCurrencyFormat();
                                            bisTicketExpired = false;
                                            this.txtStatus.Background = System.Windows.Media.Brushes.GreenYellow;
                                        }
                                        if (!Settings.IsGloryCDEnabled)
                                        {
                                            this.dispenserStatus.LoadItemsAysnc();
                                        }
                                    });

                                    if (!Settings.IsGloryCDEnabled)
                                    {
                                        _worker.Dispense("Voucher Number", objTicketDetail.TicketString, objTicketDetail.RedeemedAmount, act);

                                    }
                                    else
                                    {
                                        act();
                                        disptimerRedeem.Start();
                                    }

                                }
                            }
                            if (objTicketDetail.EnableTickerPrintDetails)
                            {
                                this.gridRedeemedTicket.Visibility = Visibility.Visible;
                                this.txtPrintedMachine.Text = objTicketDetail.RedeemedMachine;
                                this.txtClaimedDevice.Text = objTicketDetail.RedeemedDevice;
                                this.txtTickAmount.Text = objTicketDetail.RedeemedAmount.GetUniversalCurrencyFormatWithSymbol();
                                this.txtClaimedDate.Text = objTicketDetail.RedeemedDate.GetUniversalDateTimeFormat();
                            }
                            else
                            {
                                this.gridRedeemedTicket.Visibility = Visibility.Hidden;
                            }
                            this.ucValueCalc.txtDisplay.Focus();
                        }
                    }
                }
                else
                {
                    MessageBox.ShowBox("MessageID105", BMC_Icon.Warning);
                    this.ucValueCalc.txtDisplay.Focus();
                }
            }
            catch (Exception ex)
            {
                BMC.Common.ExceptionManagement.ExceptionManager.Publish(ex);
            }
            finally
            {
                btnVerify.IsEnabled = true;
            }
        }
 private void Init(string user, string pass, System.Windows.Forms.DialogResult result)
 {
     _user = user;
     _pass = pass;
     _result = result;
 }
 private void m_KhongDongY_Click(System.Object sender, System.EventArgs e)
 {
     m_MsgResult = System.Windows.Forms.DialogResult.No;
     DongForm();
 }
Exemplo n.º 18
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;
            Document      doc   = uidoc.Document;

            // Initializing variables
            // categories dic to recognize choosen categories
            Dictionary <string, Category> categoriesDic = new Dictionary <string, Category>();
            List <string> categoryNames = new List <string>();

            // categories exception, which are not to be deleted
            List <string> categoryExceptions = new List <string>()
            {
                "Níveis",
                "Informações do projeto",
                "Materiais",
                "Vistas",
                "Tabelas",
                "Itens de detalhe",
                "Vínculos RVT"
            };

            // populating categoryNames and categoriesDic
            foreach (Category category in doc.Settings.Categories)
            {
                if (category.AllowsBoundParameters)
                {
                    categoryNames.Add(category.Name);
                    categoriesDic.Add(category.Name, category);
                }
            }

            // categories deletion try count to count how many times it was tryed to delete each category
            List <int> zeros = new List <int>(new int[categoriesDic.Count]);
            Dictionary <string, int> categoriesDeletionTryCount = categoriesDic.Keys.Zip(zeros, (k, v) => new { k, v })
                                                                  .ToDictionary(x => x.k, x => x.v);

            // sorting categoryNames to show in GUI
            categoryNames.Sort();

            // creating selectFromList instance, show it and get its result
            SelectFromList selectFromList = new SelectFromList(categoryNames);

            System.Windows.Forms.DialogResult dialogResult = selectFromList.ShowDialog();
            List <string> selectedCategories = selectFromList.GetSelectedItems();

            if (dialogResult == System.Windows.Forms.DialogResult.OK)
            {
                // main loop, iterating over categories trying to delete them, until none of them least or max attempt achived
                Category category;
                string   categoriesDeleted        = "";
                string   categoriesNotDeleted     = "";
                string   categoriesNotToBeDeleted = "";
                while (true)
                {
                    if (!selectedCategories.Any())
                    {
                        break;
                    }
                    if (categoryExceptions.Contains(selectedCategories[0]))
                    {
                        categoriesNotToBeDeleted += "  -" + selectedCategories[0] + "\n";
                        selectedCategories.RemoveAt(0);
                    }
                    else
                    {
                        categoriesDic.TryGetValue(selectedCategories[0], out category);
                        Transaction t = new Transaction(doc, "Limpar " + category.Name);
                        // trying to delete category elements
                        try
                        {
                            var elementIds = new FilteredElementCollector(doc)
                                             .OfCategoryId(category.Id)
                                             .WhereElementIsNotElementType()
                                             .ToElementIds();
                            if (elementIds.Any())
                            {
                                t.Start();
                                doc.Delete(elementIds);
                                t.Commit();
                                categoriesDeleted += "  -" + category.Name + "\n";
                            }
                            selectedCategories.Remove(category.Name);
                        }
                        catch (Exception)
                        {
                            // if not possible, handle it
                            t.RollBack();
                            selectedCategories.Remove(category.Name);
                            // adding in the category.Name count
                            categoriesDeletionTryCount[category.Name] += 1;
                            // at least 8 attempts to delete
                            if (categoriesDeletionTryCount[category.Name] < 8)
                            {
                                selectedCategories.Add(category.Name);
                            }
                            else
                            {
                                categoriesNotDeleted += "  -" + category.Name + "\n";
                            }
                        }
                    }
                }
                string text = "";
                if (categoriesDeleted.Any())
                {
                    text += "Categorias excluídas: \n" + categoriesDeleted;
                }
                if (categoriesNotDeleted.Any())
                {
                    text += "\nCategorias que não puderam ser excluídas: \n" + categoriesNotDeleted;
                }
                if (categoriesNotToBeDeleted.Any())
                {
                    text += "\nCategorias que não devem ser excluídas: \n" + categoriesNotToBeDeleted;
                }
                ToolExtract toolExtract = new ToolExtract(text);
                toolExtract.ShowDialog();

                return(Result.Succeeded);
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("Limpar projeto foi cancelado.", "Limpar projeto");
            }
            return(Result.Cancelled);
        }
        void BleedVault()
        {

            try
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    if (cmbTransactionReason.SelectedIndex < 1)
                    {
                        lbl_Status.Text = Application.Current.FindResource("Vault_MessageID6") as string;
                        cmbTransactionReason.Focus();
                        return;
                    }
                    if (ucValueCalc.ValueText == string.Empty || Decimal.Parse(ucValueCalc.ValueText) <= 0)
                    {
                        if (_FillType.ToLower() == "adjustment")
                            lbl_Status.Text = Application.Current.FindResource("Vault_MessageID11") as string;
                        else
                            lbl_Status.Text = Application.Current.FindResource("Vault_MessageID4") as string;
                        return;
                    }
                    //Return if bleed amount greater than current balance
                    if (Decimal.Parse(ucValueCalc.ValueText) > Decimal.Parse(txt_CurrentBalance.Text))
                    {
                        RefreshVaultBalance();
                        lbl_Status.Text = Application.Current.FindResource("Vault_MessageID7") as string;
                        return;
                    }
                    string strMsg = (_FillType.ToLower() == "adjustment") ? "negative adjustment" : _FillType.ToLower();
                    System.Windows.Forms.DialogResult dlgResult = new System.Windows.Forms.DialogResult();
                    if (Settings.ShowVaultConfirmMessage)
                    {
                        dlgResult = MessageBox.ShowBox("Vault_MessageID8", BMC_Icon.Question, BMC_Button.YesNo, strMsg, ExtensionMethods.GetCurrencySymbol(string.Empty) + " -" + ucValueCalc.ValueText);
                        if (dlgResult == System.Windows.Forms.DialogResult.No)
                        {
                            ucValueCalc.ValueText = "0.00";
                            ucValueCalc.s_UnformattedText = "";
                            return;
                        }
                    }
                    int iResult = 0;
                    LogManager.WriteLog("CFillVault:Start Adjust Value:" + ucValueCalc.ValueText, LogManager.enumLogLevel.Debug);
                    DataRow Dr = objVault.FillVault(int.Parse(cmb_DeviceName.SelectedValue.ToString()), Decimal.Parse(ucValueCalc.ValueText), Decimal.Parse(txt_CurrentBalance.Text), 1, _FillType, int.Parse(cmbTransactionReason.SelectedValue.ToString()), ref iResult, false).Rows[0];
                    if (iResult == -1)
                    {
                        RefreshVaultBalance();
                        lbl_Status.Text = Application.Current.FindResource("Vault_MessageID7") as string;
                        return;
                    }
                    LogManager.WriteLog("CFillVault:Start Audit ", LogManager.enumLogLevel.Debug);
                    AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                    {
                        AuditModuleName = ModuleName.Vault,
                        Audit_Screen_Name = "Vault Transaction",
                        Audit_Desc = "Updating Vault  ID: " + cmb_DeviceName.SelectedValue.ToString() + " Transaction : " + _FillType + " Device Name:" + cmb_DeviceName.Text + " Amount: -" + ucValueCalc.ValueText,
                        AuditOperationType = OperationType.ADD,
                    });

                    _DrVaultBalance = Dr;
                    if (Settings.ShowVaultPrintMessage)
                    {
                        //Get slip print confirmation
                        dlgResult = MessageBox.ShowBox("Vault_MessageID10", BMC_Icon.Question, BMC_Button.YesNo, "");
                        if (dlgResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            this.Print(Dr, strMsg);
                        }
                    }
                    txt_SerialNo.Text = Dr["Serial_NO"].ToString();
                    txt_AlertLevel.Text = Dr["Alert_Level"].ToString();
                    //txt_FillAmount.Text = Dr["FillAmount"].ToString();
                    //txt_TotalFillAmount.Text = Dr["TotalAmountOnFill"].ToString();
                    txt_CurrentBalance.Text = Dr["CurrentBalance"].ToString();
                    txt_Manufacturer.Text = Dr["Manufacturer_Name"].ToString();
                    txt_Type.Text = Dr["Type_Prefix"].ToString();
                    ucValueCalc.s_UnformattedText = string.Empty;
                    lbl_Status.Text = string.Empty;
                    ucValueCalc.txtDisplay.Clear();
                    ucValueCalc.textBox1.Clear();
                    ucValueCalc.ValueText = string.Empty;

                    //Return if bleed amount greater than current balance(DB CHECK)
                    if (iResult == -1)
                    {
                        lbl_Status.Text = Application.Current.FindResource("Vault_MessageID7") as string;
                        return;
                    }

                    DisableControls();

                    cmbTransactionReason.SelectedIndex = 0;
                    lbl_Status.Text = Application.Current.FindResource("Vault_MessageID1") as string;

                }));
            }
            catch (Exception Ex)
            {
                ExceptionManager.Publish(Ex);
                throw;
            }
            //RefreshVaultBalance();
        }
 private void WmClose(ref Message m)
 {
     FormClosingEventArgs e = new FormClosingEventArgs(this.CloseReason, false);
     if (m.Msg == 0x16)
     {
         e.Cancel = m.WParam == IntPtr.Zero;
     }
     else
     {
         if (this.Modal)
         {
             if (this.dialogResult == System.Windows.Forms.DialogResult.None)
             {
                 this.dialogResult = System.Windows.Forms.DialogResult.Cancel;
             }
             this.CalledClosing = false;
             e.Cancel = !this.CheckCloseDialog(true);
         }
         else
         {
             e.Cancel = !base.Validate(true);
             if (this.IsMdiContainer)
             {
                 FormClosingEventArgs args2 = new FormClosingEventArgs(System.Windows.Forms.CloseReason.MdiFormClosing, e.Cancel);
                 foreach (Form form in this.MdiChildren)
                 {
                     if (form.IsHandleCreated)
                     {
                         form.OnClosing(args2);
                         form.OnFormClosing(args2);
                         if (args2.Cancel)
                         {
                             e.Cancel = true;
                             break;
                         }
                     }
                 }
             }
             Form[] ownedForms = this.OwnedForms;
             for (int i = base.Properties.GetInteger(PropOwnedFormsCount) - 1; i >= 0; i--)
             {
                 FormClosingEventArgs args3 = new FormClosingEventArgs(System.Windows.Forms.CloseReason.FormOwnerClosing, e.Cancel);
                 if (ownedForms[i] != null)
                 {
                     ownedForms[i].OnFormClosing(args3);
                     if (args3.Cancel)
                     {
                         e.Cancel = true;
                         break;
                     }
                 }
             }
             this.OnClosing(e);
             this.OnFormClosing(e);
         }
         if (m.Msg == 0x11)
         {
             m.Result = e.Cancel ? IntPtr.Zero : ((IntPtr) 1);
         }
         if (this.Modal)
         {
             return;
         }
     }
     if ((m.Msg != 0x11) && !e.Cancel)
     {
         FormClosedEventArgs args4;
         this.IsClosing = true;
         if (this.IsMdiContainer)
         {
             args4 = new FormClosedEventArgs(System.Windows.Forms.CloseReason.MdiFormClosing);
             foreach (Form form2 in this.MdiChildren)
             {
                 if (form2.IsHandleCreated)
                 {
                     form2.OnClosed(args4);
                     form2.OnFormClosed(args4);
                 }
             }
         }
         Form[] formArray2 = this.OwnedForms;
         for (int j = base.Properties.GetInteger(PropOwnedFormsCount) - 1; j >= 0; j--)
         {
             args4 = new FormClosedEventArgs(System.Windows.Forms.CloseReason.FormOwnerClosing);
             if (formArray2[j] != null)
             {
                 formArray2[j].OnClosed(args4);
                 formArray2[j].OnFormClosed(args4);
             }
         }
         args4 = new FormClosedEventArgs(this.CloseReason);
         this.OnClosed(args4);
         this.OnFormClosed(args4);
         base.Dispose();
     }
 }
        void DropVault()
        {
            Dispatcher.Invoke(new Action(() =>
            {
                if (cmbTransactionReason.SelectedIndex < 1)
                {
                    lbl_Status.Text = Application.Current.FindResource("Vault_MessageID6") as string;
                    cmbTransactionReason.Focus();
                    return;
                }
                System.Windows.Forms.DialogResult dlgResult = new System.Windows.Forms.DialogResult();
                if (Settings.ShowVaultConfirmMessage)
                {
                    dlgResult = MessageBox.ShowBox("Vault_MessageID9", BMC_Icon.Question, BMC_Button.OKCancel, "");
                    if (dlgResult == System.Windows.Forms.DialogResult.Cancel)
                    {
                        return;
                    }
                }

                LogManager.WriteLog("CFillVault:Start Drop Vault ", LogManager.enumLogLevel.Debug);


                int result = 0;
                DataTable dt_balance = objVault.DropVault(int.Parse(cmb_DeviceName.SelectedValue.ToString()), int.Parse(cmbTransactionReason.SelectedValue.ToString()), _IsFinalDrop, ref result);
                if (result == -2)
                {
                    MessageBox.ShowBox("Vault_MessageID19", BMC_Icon.Error);
                    return;
                }

                DataRow dr_bal = dt_balance.Rows[0];
                _DrVaultBalance = dr_bal;
                if (Settings.ShowVaultPrintMessage)
                {
                    //Get slip print confirmation
                    dlgResult = MessageBox.ShowBox("Vault_MessageID10", BMC_Icon.Question, BMC_Button.YesNo, "");
                    if (dlgResult == System.Windows.Forms.DialogResult.Yes)
                    {
                        this.PrintDrop(dr_bal);
                    }
                }

                AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                {
                    AuditModuleName = ModuleName.Vault,
                    Audit_Screen_Name = "Vault Transaction",
                    Audit_Desc = "Droping Vault  ID: " + cmb_DeviceName.SelectedValue.ToString() + " Transaction : " + _FillType + " Device Name:" + cmb_DeviceName.Text,
                    AuditOperationType = OperationType.ADD,
                });
                if (_IsFinalDrop)
                {
                    GetVaultDetails(false);
                    return;
                }
                txt_SerialNo.Text = dr_bal["Serial_NO"].ToString();
                txt_AlertLevel.Text = dr_bal["Alert_Level"].ToString();
                //txt_FillAmount.Text = dr_bal["FillAmount"].ToString();
                //txt_TotalFillAmount.Text = dr_bal["TotalAmountOnFill"].ToString();
                txt_CurrentBalance.Text = dr_bal["CurrentBalance"].ToString();
                txt_Manufacturer.Text = dr_bal["Manufacturer_Name"].ToString();
                txt_Type.Text = dr_bal["Type_Prefix"].ToString();
                ucValueCalc.s_UnformattedText = string.Empty;
                lbl_Status.Text = string.Empty;
                ucValueCalc.txtDisplay.Clear();
                ucValueCalc.textBox1.Clear();
                ucValueCalc.ValueText = string.Empty;

                DisableControls();



                cmbTransactionReason.SelectedIndex = 0;
                lbl_Status.Text = Application.Current.FindResource("Vault_MessageID1") as string;
                LogManager.WriteLog("CFillVault:Drop Vault Complete", LogManager.enumLogLevel.Debug);
                if (!_IsFinalDrop && _IsStandardFillHasAccess)
                {
                    System.Windows.Forms.DialogResult dlgResultStandardDrop = MessageBox.ShowBox("Vault_MessageID18", BMC_Icon.Question, BMC_Button.YesNo, "");
                    if (dlgResultStandardDrop == System.Windows.Forms.DialogResult.Yes)
                    {
                        try
                        {
                            //Fill  standard amount
                            LogManager.WriteLog("CFillVault:Start standard Fill ", LogManager.enumLogLevel.Debug);
                            cmbTransactionReason.SelectedValue = InitialFillValue;
                            _IsStandardFill = true;
                            _FillType = "STANDARDFILL";
                            showModel(FillVault);
                            _IsStandardFill = false;
                        }
                        catch (Exception Ex)
                        {
                            _IsStandardFill = false;
                            ExceptionManager.Publish(Ex);
                            lbl_Status.Text = Application.Current.FindResource("Vault_MessageID2") as string;
                        }
                    }
                }


            }));
        }
 private void Button_OnClick(object sender, RoutedEventArgs e)
 {
     var dialog = new System.Windows.Forms.FolderBrowserDialog();
     result = dialog.ShowDialog();
     _brutto.Folder = dialog.SelectedPath;
 }
Exemplo n.º 23
0
 private void propertyPage_PropertyWantsClose(int idx)
 {
     result = System.Windows.Forms.DialogResult.OK;
 }
Exemplo n.º 24
0
            /// <summary>
            /// Same as System.Windows.Froms.MessageBox.Show but using a message box tailored to Rhino.
            /// </summary>
            /// <param name="message">Message box text content.</param>
            /// <param name="title">Message box title text.</param>
            /// <param name="buttons">One of the System.Windows.Forms.MessageBoxButtons values that specifies which buttons to display in the message box.</param>
            /// <param name="icon">One of the System.Windows.Forms.MessageBoxIcon values that specifies which icon to display in the message box.</param>
            /// <param name="defaultButton">One of the System.Windows.Forms.MessageBoxDefaultButton values that specifies the default button for the message box.</param>
            /// <returns>One of the System.Windows.Forms.DialogResult values.</returns>
            public static System.Windows.Forms.DialogResult ShowMessageBox(string message,
                                                                           string title,
                                                                           System.Windows.Forms.MessageBoxButtons buttons,
                                                                           System.Windows.Forms.MessageBoxIcon icon,
                                                                           System.Windows.Forms.MessageBoxDefaultButton defaultButton)
            {
                const uint MB_OK               = 0x00000000;
                const uint MB_OKCANCEL         = 0x00000001;
                const uint MB_ABORTRETRYIGNORE = 0x00000002;
                const uint MB_YESNOCANCEL      = 0x00000003;
                const uint MB_YESNO            = 0x00000004;
                const uint MB_RETRYCANCEL      = 0x00000005;
                //const uint MB_CANCELTRYCONTINUE = 0x00000006;
                const uint MB_ICONHAND        = 0x00000010;
                const uint MB_ICONQUESTION    = 0x00000020;
                const uint MB_ICONEXCLAMATION = 0x00000030;
                const uint MB_ICONASTERISK    = 0x00000040;
                //const uint MB_USERICON = 0x00000080;
                const uint MB_ICONWARNING     = MB_ICONEXCLAMATION;
                const uint MB_ICONERROR       = MB_ICONHAND;
                const uint MB_ICONINFORMATION = MB_ICONASTERISK;
                const uint MB_ICONSTOP        = MB_ICONHAND;
                const uint MB_DEFBUTTON1      = 0x00000000;
                const uint MB_DEFBUTTON2      = 0x00000100;
                const uint MB_DEFBUTTON3      = 0x00000200;
                //const uint MB_DEFBUTTON4 = 0x00000300;

                uint buttonFlags = 0;

                if (System.Windows.Forms.MessageBoxButtons.AbortRetryIgnore == buttons)
                {
                    buttonFlags = MB_ABORTRETRYIGNORE;
                }
                else if (System.Windows.Forms.MessageBoxButtons.OK == buttons)
                {
                    buttonFlags = MB_OK;
                }
                else if (System.Windows.Forms.MessageBoxButtons.OKCancel == buttons)
                {
                    buttonFlags = MB_OKCANCEL;
                }
                else if (System.Windows.Forms.MessageBoxButtons.RetryCancel == buttons)
                {
                    buttonFlags = MB_RETRYCANCEL;
                }
                else if (System.Windows.Forms.MessageBoxButtons.YesNo == buttons)
                {
                    buttonFlags = MB_YESNO;
                }
                else if (System.Windows.Forms.MessageBoxButtons.YesNoCancel == buttons)
                {
                    buttonFlags = MB_YESNOCANCEL;
                }

                uint iconFlags = 0; //System.Windows.Forms.MessageBoxIcon.None

                if (System.Windows.Forms.MessageBoxIcon.Asterisk == icon)
                {
                    iconFlags = MB_ICONASTERISK;
                }
                else if (System.Windows.Forms.MessageBoxIcon.Error == icon)
                {
                    iconFlags = MB_ICONERROR;
                }
                else if (System.Windows.Forms.MessageBoxIcon.Exclamation == icon)
                {
                    iconFlags = MB_ICONEXCLAMATION;
                }
                else if (System.Windows.Forms.MessageBoxIcon.Hand == icon)
                {
                    iconFlags = MB_ICONHAND;
                }
                else if (System.Windows.Forms.MessageBoxIcon.Information == icon)
                {
                    iconFlags = MB_ICONINFORMATION;
                }
                else if (System.Windows.Forms.MessageBoxIcon.Question == icon)
                {
                    iconFlags = MB_ICONQUESTION;
                }
                else if (System.Windows.Forms.MessageBoxIcon.Stop == icon)
                {
                    iconFlags = MB_ICONSTOP;
                }
                else if (System.Windows.Forms.MessageBoxIcon.Warning == icon)
                {
                    iconFlags = MB_ICONWARNING;
                }

                uint defaultButtonFlags = 0;

                if (System.Windows.Forms.MessageBoxDefaultButton.Button1 == defaultButton)
                {
                    defaultButtonFlags = MB_DEFBUTTON1;
                }
                else if (System.Windows.Forms.MessageBoxDefaultButton.Button2 == defaultButton)
                {
                    defaultButtonFlags = MB_DEFBUTTON2;
                }
                else if (System.Windows.Forms.MessageBoxDefaultButton.Button3 == defaultButton)
                {
                    defaultButtonFlags = MB_DEFBUTTON3;
                }

                uint flags = buttonFlags | iconFlags | defaultButtonFlags;

                System.Windows.Forms.DialogResult result = System.Windows.Forms.DialogResult.None;
                try
                {
                    int rc = UnsafeNativeMethods.RHC_RhinoMessageBox(message, title, flags);
                    result = DialogResultFromInt(rc);
                }
                catch (System.EntryPointNotFoundException)
                {
                    if (!Rhino.Runtime.HostUtils.RunningInRhino)
                    {
                        result = System.Windows.Forms.MessageBox.Show(message, title, buttons, icon, defaultButton);
                    }
                }
                return(result);
            }
Exemplo n.º 25
0
        private async void ButtonWrite_OnClick(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog FileDialog = new System.Windows.Forms.SaveFileDialog
            {
                Filter = "STAR Files|*.star"
            };
            System.Windows.Forms.DialogResult Result = FileDialog.ShowDialog();

            if (Result.ToString() == "OK")
            {
                ExportPath = FileDialog.FileName;
            }
            else
            {
                return;
            }

            bool Relative = (bool)CheckRelative.IsChecked;
            bool Filter   = (bool)CheckFilter.IsChecked;
            bool Manual   = (bool)CheckManual.IsChecked;

            ProgressWrite.Visibility = Visibility.Visible;
            PanelButtons.Visibility  = Visibility.Hidden;

            await Task.Run(() =>
            {
                List <TiltSeries> ValidSeries = Series.Where(v =>
                {
                    if (!Filter && v.UnselectFilter && v.UnselectManual == null)
                    {
                        return(false);
                    }
                    if (!Manual && v.UnselectManual != null && (bool)v.UnselectManual)
                    {
                        return(false);
                    }
                    return(true);
                }).ToList();

                string PathPrefix = "";
                if (ValidSeries.Count > 0 && Relative)
                {
                    Uri UriStar = new Uri(ExportPath);
                    PathPrefix  = UriStar.MakeRelativeUri(new Uri(ValidSeries[0].Path)).ToString();

                    PathPrefix = PathPrefix.Substring(0, PathPrefix.IndexOf(Helper.PathToNameWithExtension(PathPrefix)));
                }

                Dispatcher.Invoke(() => ProgressWrite.Maximum = ValidSeries.Count);

                bool IncludeCTF = ValidSeries.Any(v => v.OptionsCTF != null);

                Star TableOut = new Star(new[] { "rlnMicrographName" });
                if (IncludeCTF)
                {
                    TableOut.AddColumn("rlnCtfMaxResolution");
                }

                int r = 0;
                foreach (var series in ValidSeries)
                {
                    List <string> Row = new List <string> {
                        PathPrefix + series.Name
                    };

                    if (IncludeCTF)
                    {
                        if (series.OptionsCTF != null)
                        {
                            Row.Add(series.CTFResolutionEstimate.ToString("F1", CultureInfo.InvariantCulture));
                        }
                        else
                        {
                            Row.Add("999");
                        }
                    }

                    TableOut.AddRow(Row);

                    Dispatcher.Invoke(() => ProgressWrite.Value = ++r);
                }

                TableOut.Save(ExportPath);
            });

            Close?.Invoke();
        }
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {

            try
            {
                LogManager.WriteLog(stitle + "btnSubmit_Click()", LogManager.enumLogLevel.Debug);
                int error_flag = 0;
                string ErrorMsg = "";
                string CassetteInfo = "";
                bool sendAlert = false;
                System.Windows.Forms.DialogResult dlgResult = new System.Windows.Forms.DialogResult();
                XElement Cassette_xml = FrameXml(_isdroptransaction);
                if (!lst_NGADetails.Any(obj => obj.IsChecked))
                {
                    MessageBox.ShowBox("VaultCassette_MessageID6", BMC_Icon.Information);
                    return;
                }

                #region Validate
                if (!_isdroptransaction)
                {
                    if (IsAmountEditable && !ValidateAmount())
                        return;
                    if (!Validate(ref ErrorMsg))
                    {
                        MessageBox.ShowBox(ErrorMsg, BMC_Icon.Error, true);
                        return;
                    }
                    object defaultValue = null;
                    bool check_onetime = false;
                    foreach (GetNGADetailsResult sel_Cassette in lst_NGADetails)
                    {
                        if (sel_Cassette.IsChecked)
                        {
                            CassetteInfo += "CassetteName: " + sel_Cassette.Cassette_Name + ", Amount: " + sel_Cassette.Amount + "; ";  //for audit purpose
                            if (_VType == VaultTransactionType.StandardFill && (!check_onetime))
                            {
                                if (sel_Cassette.Amount != sel_Cassette.OldAmount)
                                {
                                    dlgResult = MessageBox.ShowBox("Vault_MessageID21", BMC_Icon.Question, BMC_Button.YesNo, "");
                                    if (dlgResult == System.Windows.Forms.DialogResult.No)
                                    {
                                        return;
                                    }
                                    else
                                    {
                                        check_onetime = true;
                                    }
                                }
                            }
                            else if (_VType == VaultTransactionType.PositiveAdjustment)
                            {
                                if (sel_Cassette.Amount < sel_Cassette.CurrentBalance.Value)
                                {
                                    ErrorMsg = Application.Current.FindResource("VaultCassette_MessageID10").ToString()
                                                .Replace("*****", sel_Cassette.Cassette_Name)
                                                .Replace("@@@@@", sel_Cassette.CurrentBalance.Value.GetUniversalCurrencyFormatWithSymbol());
                                    MessageBox.ShowBox(ErrorMsg, BMC_Icon.Error, true);
                                    lst_CassetteDetails.SelectedItem = sel_Cassette;
                                    return;
                                }
                            }
                            else if (_VType == VaultTransactionType.NegativeAdjustment)
                            {
                                if (sel_Cassette.Amount > sel_Cassette.CurrentBalance.Value)
                                {
                                    ErrorMsg = Application.Current.FindResource("VaultCassette_MessageID11").ToString()
                                               .Replace("*****", sel_Cassette.Cassette_Name)
                                               .Replace("@@@@@", sel_Cassette.CurrentBalance.Value.GetUniversalCurrencyFormatWithSymbol());
                                    MessageBox.ShowBox(ErrorMsg, BMC_Icon.Error, true);
                                    lst_CassetteDetails.SelectedItem = sel_Cassette;
                                    return;
                                }
                            }

                            if (!Validate(sel_Cassette, ref defaultValue, ref ErrorMsg))
                            {
                                MessageBox.ShowBox(ErrorMsg, BMC_Icon.Error, true);
                                return;
                            }
                        }
                    }
                }
                else
                {
                    //for audit purpose
                    foreach (GetNGADetailsResult sel_Cassette in lst_NGADetails)
                    {
                        if (sel_Cassette.IsChecked)
                        {
                            CassetteInfo += "CassetteName: " + sel_Cassette.Cassette_Name + ", Amount: " + sel_Cassette.Amount + "; ";
                        }
                    }
                }

                if (_VType == VaultTransactionType.StandardFill)
                {
                    if (Vault.CreateInstance().IsStandardFillDoneTwice(_vaultid))
                    {
                        dlgResult = MessageBox.ShowBox("Vault_MessageID20", BMC_Icon.Question, BMC_Button.YesNo, "");
                        if (dlgResult == System.Windows.Forms.DialogResult.No)
                        {
                            return;
                        }
                        else
                        {
                            sendAlert = true;
                        }
                    }
                }
                #endregion

                bool result = false;
                usp_Vault_DropResult v_droprep = null;
                usp_Vault_FillVaultResult v_fillrep = null;
                decimal tot_amount = 0;
                if (_isdroptransaction)
                {
                    if (Settings.ShowVaultConfirmMessage)
                    {
                        dlgResult = MessageBox.ShowBox("Vault_MessageID9", BMC_Icon.Question, BMC_Button.YesNo, "");
                    }

                }
                else
                {
                    tot_amount = lst_NGADetails.Where(obj => obj.IsChecked).Sum(obj => obj.Amount);
                    if (Settings.ShowVaultConfirmMessage)
                    {
                        dlgResult = MessageBox.ShowBox("Vault_MessageID8", BMC_Icon.Question, BMC_Button.YesNo, dic_transtype[_VType].ToLower(),
                            ExtensionMethods.GetCurrencySymbol(string.Empty) + ((_VType == VaultTransactionType.Bleed) ? " -" : " ") + tot_amount);
                    }
                }
                if (!Settings.ShowVaultConfirmMessage)
                {
                    dlgResult = System.Windows.Forms.DialogResult.Yes;
                }
                if (dlgResult == System.Windows.Forms.DialogResult.Yes)
                {
                    if (_isdroptransaction)
                    {
                        result = Vault.CreateInstance().DropVaultCassettes(_vaultid, SecurityHelper.CurrentUser.SecurityUserID,
                            _transaction_reason_id, Cassette_xml, _isfinaldrop, ref error_flag, ref  v_droprep);

                        if (result)
                        {


                            LogManager.WriteLog(stitle + "Drop Succeeded, VaultID: " + _vaultid + " IsFinalDrop: " + _isfinaldrop, LogManager.enumLogLevel.Debug);

                            ///<Cassette Cassette_ID="18" Denom="50" FillAmount="100.00
                            AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                            {
                                AuditModuleName = ModuleName.Vault,
                                Audit_Screen_Name = "Vault Transaction",
                                Audit_Desc = "Droping Vault  ID: " + _vaultid + " Transaction : " + _transactiontype +
                                " Device Name:" + _VaultName + "Cassette_info:" + CassetteInfo,
                                AuditOperationType = OperationType.ADD,
                            });
                        }
                    }
                    else
                    {

                        if (_VType == VaultTransactionType.NegativeAdjustment)
                        {
                            tot_amount = lst_NGADetails.Where(obj => obj.IsChecked).Sum(obj => (obj.CurrentBalance.Value - obj.Amount));

                        }
                        else if (_VType == VaultTransactionType.PositiveAdjustment)
                        {
                            tot_amount = lst_NGADetails.Where(obj => obj.IsChecked).Sum(obj => (obj.Amount - obj.CurrentBalance.Value));

                        }
                        result = Vault.CreateInstance().FillAmountinCassettes(_vaultid, tot_amount, 0m,
                           SecurityHelper.CurrentUser.SecurityUserID, _withdrawalflag, _transactiontype,
                           true, _transaction_reason_id, Cassette_xml, ref error_flag, ref v_fillrep, sendAlert);
                        if (result)
                        {

                            LogManager.WriteLog(stitle + "Transaction Succeeded, VaultID: " + _vaultid + " Type: " + _transactiontype + " Amount: " + tot_amount, LogManager.enumLogLevel.Debug);

                            AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                            {
                                AuditModuleName = ModuleName.Vault,
                                Audit_Screen_Name = "Vault Transaction",
                                Audit_Desc = "Updating Vault:ID " + _vaultid + " Transaction : " + _transactiontype + " Device Name:" + _VaultName + " Amount:" + tot_amount + " Cassette_info:" + CassetteInfo,
                                AuditOperationType = OperationType.ADD,
                            });
                        }
                    }
                    if (result)
                    {
                        if (Settings.ShowVaultSuccessMessage)
                        {
                            MessageBox.ShowBox("VaultCassette_MessageID3", BMC_Icon.Information);
                        }

                        if (Settings.ShowVaultPrintMessage)
                        {
                            dlgResult = MessageBox.ShowBox("Vault_MessageID10", BMC_Icon.Question, BMC_Button.YesNo, "");
                            if (dlgResult == System.Windows.Forms.DialogResult.Yes)
                            {
                                if (_isdroptransaction)
                                {
                                    if (v_droprep != null)
                                        CreateVaultCassettesCurrentDropReport(v_droprep);
                                }
                                else
                                {
                                    if (v_fillrep != null)
                                        CreateVaultCassettesCurrentTransactionReport(v_fillrep, dic_transtype[_VType]);
                                }
                            }
                        }
                        if (_act_refresh != null)
                        {
                            _act_refresh();
                        }
                        this.Close();
                    }
                    else
                    {
                        ShowErrorStatus(error_flag);
                    }
                }


            }
            catch (Exception Ex)
            {
                ExceptionManager.Publish(Ex);
                MessageBox.ShowBox("Vault_MessageID2", BMC_Icon.Error);

            }
        }
Exemplo n.º 27
0
        private void ContextMenu_RightClick(object sender, MouseButtonEventArgs e)
        {
            if (activationFunction)
            {
                Location location = MyMap.ViewportPointToLocation(Mouse.GetPosition(MyMap));
                var      temp     = MyMap.GetCurrentRegion(location, companyEntities);
                if (temp != null && regionVisibility)
                {
                    ContextMenu context = new ContextMenu();
                    context.IsOpen = true;
                    var editRegion = new MenuItem()
                    {
                        Header = "Edytuj region"
                    };
                    var removeRegion = new MenuItem()
                    {
                        Header = "Usuń region"
                    };
                    var infoRegion = new MenuItem()
                    {
                        Header = "Info"
                    };

                    infoRegion.Click += (s, es) => MessageBox.Show($"Kod: {temp.code}");
                    editRegion.Click += async(s, es) =>
                    {
                        MyMap.Children.Remove(MyMap.GetPolyline(temp));
                        while (e.LeftButton == MouseButtonState.Released)
                        {
                            await Task.Delay(25);
                        }
                        var viewModel = (RegionViewModel)this.DataContext;
                        viewModel.WarehouseSelectedRegion = viewModel.Warehouses.FirstOrDefault(w => w.id == temp.idWarehouse);
                        viewModel.EmployeeSelectedRegion  = viewModel.Employees.FirstOrDefault(e => e.idRegion == temp.id);
                        CreateRegions_ClickAsync(s, es);
                        region = temp;
                    };
                    removeRegion.Click += (s, es) =>
                    {
                        System.Windows.Forms.DialogResult result = (System.Windows.Forms.DialogResult)MessageBox.Show($"Na pewno chcesz usunąć region {temp.code}?", "", MessageBoxButton.YesNo, MessageBoxImage.Question);
                        if (result == System.Windows.Forms.DialogResult.Yes)
                        {
                            var emplTemp = companyEntities.Employee.Where(e => e.idRegion == temp.id);
                            foreach (var employee in emplTemp)
                            {
                                employee.idRegion = null;
                            }
                            MyMap.Children.Remove(MyMap.GetPolyline(temp));
                            companyEntities.Localization.Remove(temp.Localization);
                            companyEntities.Localization.Remove(temp.Localization1);
                            temp.idWarehouse = null;
                            companyEntities.Region.Remove(temp);
                            companyEntities.SaveChanges();
                        }
                    };
                    context.Items.Add(editRegion);
                    context.Items.Add(removeRegion);
                    context.Items.Add(infoRegion);
                }
                else
                {
                    ContextMenu context = new ContextMenu();
                    context.IsOpen = true;
                    var createRegions = new MenuItem()
                    {
                        Header = "Dodaj nowy region"
                    };
                    var connectPushPins = new MenuItem()
                    {
                        Header = "Połącz pinezki"
                    };
                    var clear = new MenuItem()
                    {
                        Header = "Wyczyść trase"
                    };
                    clear.Click           += ClearPolyline_Click;
                    connectPushPins.Click += ConnectPushPins_Click;
                    createRegions.Click   += CreateRegions_ClickAsync;
                    context.Items.Add(createRegions);
                    context.Items.Add(connectPushPins);
                    context.Items.Add(clear);
                }
            }
        }
Exemplo n.º 28
0
        private void BrowseButtonClicked(object sender, RoutedEventArgs e)
        {
            AddAPIModelWizard.IsParsingWasDone = false;
            if (APITypeComboBox.SelectedValue.ToString() == eAPIType.WSDL.ToString())
            {
                if (FileRadioButton.IsChecked == true)
                {
                    if (string.IsNullOrEmpty(xURLTextBox.Text))
                    {
                        System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();

                        dlg.Filter = "XML Files (*.xml)|*.xml" + "|WSDL Files (*.wsdl)|*.wsdl" + "|All Files (*.*)|*.*";

                        System.Windows.Forms.DialogResult result = dlg.ShowDialog();

                        if (result == System.Windows.Forms.DialogResult.OK)
                        {
                            xURLTextBox.Text = dlg.FileName;
                            // AddAPIModelWizard.NextEnabled = true;
                            LoadFileValidation();
                        }
                    }
                    else
                    {
                        LoadFileValidation();
                    }
                }
                else
                {
                    LoadFileValidation();
                }
            }
            else if (APITypeComboBox.SelectedValue.ToString() == eAPIType.Swagger.ToString())
            {
                AddAPIModelWizard.APIType = eAPIType.Swagger;
                if (FileRadioButton.IsChecked == true)
                {
                    System.Windows.Forms.OpenFileDialog dlg2 = new System.Windows.Forms.OpenFileDialog();

                    dlg2.Filter = "Json Files (*.json)|*.json" + "|YAML Files (*.yaml)|*.yaml;*.yml" + "|All Files (*.*)|*.*";

                    System.Windows.Forms.DialogResult result = dlg2.ShowDialog();

                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        xURLTextBox.Text = dlg2.FileName;
                        // AddAPIModelWizard.NextEnabled = true;
                        AddAPIModelWizard.XTFList.Add(new TemplateFile()
                        {
                            FilePath = dlg2.FileName
                        });
                    }
                }
                else
                {
                    string tempfile    = System.IO.Path.GetTempFileName();
                    string filecontent = Amdocs.Ginger.Common.GeneralLib.HttpUtilities.Download(new System.Uri(xURLTextBox.Text));
                    System.IO.File.WriteAllText(tempfile, filecontent);
                    AddAPIModelWizard.XTFList.Add(new TemplateFile()
                    {
                        FilePath = tempfile
                    });
                    // AddAPIModelWizard.NextEnabled = true;
                }
            }

            else
            {
                BrowseForTemplateFiles();
            }
        }
Exemplo n.º 29
0
        public MainWindow()
        {
            bool boolRunningFromHome = false;
            var  window = new Window() //make sure the window is invisible
            {
                Width         = 0,
                Height        = 0,
                Left          = -2000,
                WindowStyle   = WindowStyle.None,
                ShowInTaskbar = false,
                ShowActivated = false,
            };

            window.Show();
            IdealAutomate.Core.Methods myActions = new Methods();
            myActions.ScriptStartedUpdateStats();

            InitializeComponent();
            this.Hide();

            myActions.DebugMode = true;
            ImageEntity myImage = new ImageEntity();

            string strWindowTitle = myActions.PutWindowTitleInEntity();

            if (strWindowTitle.StartsWith("OpenNotepadLineInVS"))
            {
                myActions.TypeText("%(\" \"n)", 1000); // minimize visual studio
            }
            //myImage.ImageFile = "Images\\Ready.PNG";
            //myImage.Sleep = 3500;
            //myImage.Attempts = 2;
            //myImage.RelativeX = 10;
            //myActions.ClickImageIfExists(myImage);
            List <string> myWindowTitles = myActions.GetWindowTitlesByProcessName("notepad++");

            myWindowTitles.RemoveAll(item => item == "");
            if (myWindowTitles.Count > 0)
            {
                myActions.ActivateWindowByTitle(myWindowTitles[0], 3);
                myActions.Sleep(1000);
                //int[,] myCursorPosition = myActions.PutCursorPosition();

                //myActions.RightClick(myCursorPosition);
                myActions.TypeText("{RIGHT}", 500);
                myActions.TypeText("{HOME}", 500);
                myActions.TypeText("+({END})", 500);
                myActions.TypeText("^(c)", 500);
                myActions.Sleep(500);
                string strCurrentLine = "";
                RunAsSTAThread(
                    () => {
                    strCurrentLine = myActions.PutClipboardInEntity();
                });
            }
            myWindowTitles = myActions.GetWindowTitlesByProcessName("devenv");
            string myWebSite = "";

TryAgainClip:
            string myOrigEditPlusLine = myActions.PutClipboardInEntity();

            if (myOrigEditPlusLine.Length == 0)
            {
                System.Windows.Forms.DialogResult myResult = myActions.MessageBoxShowWithYesNo("You forgot to put line in clipboard - Put line in clipboard and click yes to continue");
                if (myResult == System.Windows.Forms.DialogResult.Yes)
                {
                    goto TryAgainClip;
                }
                else
                {
                    goto myExit;
                }
            }
            //string myOrigEditPlusLine = strReadLine;
            bool          boolSolutionFileFound = true;
            string        strSolutionName       = "";
            List <string> myBeginDelim          = new List <string>();
            List <string> myEndDelim            = new List <string>();

            myBeginDelim.Add("\"");
            myEndDelim.Add("\"");
            FindDelimitedTextParms delimParms = new FindDelimitedTextParms(myBeginDelim, myEndDelim);

            string myQuote = "\"";

            delimParms.lines[0] = myOrigEditPlusLine;


            myActions.FindDelimitedText(delimParms);
            int intLastSlash = delimParms.strDelimitedTextFound.LastIndexOf('\\');

            if (intLastSlash < 1)
            {
                myActions.MessageBoxShow("Could not find last slash in in EditPlusLine - aborting");
                goto myExit;
            }
            string strPathOnly     = delimParms.strDelimitedTextFound.SubstringBetweenIndexes(0, intLastSlash);
            string strFileNameOnly = delimParms.strDelimitedTextFound.Substring(intLastSlash + 1);

            myBeginDelim.Clear();
            myEndDelim.Clear();
            myBeginDelim.Add("(");
            myEndDelim.Add(",");
            delimParms          = new FindDelimitedTextParms(myBeginDelim, myEndDelim);
            delimParms.lines[0] = myOrigEditPlusLine;
            myActions.FindDelimitedText(delimParms);
            string strLineNumber = delimParms.strDelimitedTextFound;

            //========
            string strFullName             = Path.Combine(strPathOnly, strFileNameOnly);
            string strSolutionFullFileName = "";

            string currentTempName = strFullName;

            while (currentTempName.IndexOf("\\") > -1)
            {
                currentTempName = currentTempName.Substring(0, currentTempName.LastIndexOf("\\"));
                FileInfo fi = new FileInfo(currentTempName);
                if (Directory.Exists(currentTempName))
                {
                    string[] files = null;
                    try {
                        files = System.IO.Directory.GetFiles(currentTempName, "*.sln");
                        if (files.Length > 0)
                        {
                            // TODO: Currently defaulting to last one, but should ask the user which one to use if there is more than one
                            strSolutionFullFileName = files[files.Length - 1];
                            boolSolutionFileFound   = true;
                            strSolutionName         = strSolutionFullFileName.Substring(strSolutionFullFileName.LastIndexOf("\\") + 1).Replace(".sln", "");
                            myWindowTitles          = myActions.GetWindowTitlesByProcessName("devenv");
                            myWindowTitles.RemoveAll(vsItem => vsItem == "");
                            bool boolVSMatchingSolutionFound = false;
                            foreach (var vsTitle in myWindowTitles)
                            {
                                if (vsTitle.StartsWith(strSolutionName + " - "))
                                {
                                    boolVSMatchingSolutionFound = true;
                                    myActions.ActivateWindowByTitle(vsTitle, 3);
                                    myActions.Sleep(1000);
                                    myActions.TypeText("{ESCAPE}", 500);
                                    myBeginDelim = new List <string>();
                                    myEndDelim   = new List <string>();
                                    myBeginDelim.Add("\"");
                                    myEndDelim.Add("\"");
                                    delimParms = new FindDelimitedTextParms(myBeginDelim, myEndDelim);

                                    myQuote             = "\"";
                                    delimParms.lines[0] = myOrigEditPlusLine;


                                    myActions.FindDelimitedText(delimParms);
                                    intLastSlash = delimParms.strDelimitedTextFound.LastIndexOf('\\');
                                    if (intLastSlash < 1)
                                    {
                                        myActions.MessageBoxShow("Could not find last slash in in EditPlusLine - aborting");
                                        break;
                                    }
                                    strPathOnly     = delimParms.strDelimitedTextFound.SubstringBetweenIndexes(0, intLastSlash);
                                    strFileNameOnly = delimParms.strDelimitedTextFound.Substring(intLastSlash + 1);
                                    myBeginDelim.Clear();
                                    myEndDelim.Clear();
                                    myBeginDelim.Add("(");
                                    myEndDelim.Add(",");
                                    delimParms          = new FindDelimitedTextParms(myBeginDelim, myEndDelim);
                                    delimParms.lines[0] = myOrigEditPlusLine;
                                    myActions.FindDelimitedText(delimParms);
                                    strLineNumber = delimParms.strDelimitedTextFound;
                                    myActions.TypeText("{ESC}", 2000);
                                    myActions.TypeText("%(f)", 1000);
                                    myActions.TypeText("{DOWN}", 1000);
                                    myActions.TypeText("{RIGHT}", 1000);
                                    myActions.TypeText("f", 1000);
                                    // myActions.TypeText("^(o)", 2000);
                                    myActions.TypeText("%(d)", 1500);
                                    myActions.TypeText(strPathOnly, 1500);
                                    myActions.TypeText("{ENTER}", 500);
                                    myActions.TypeText("%(n)", 500);
                                    myActions.TypeText(strFileNameOnly, 1500);
                                    myActions.TypeText("{ENTER}", 1000);
                                    break;
                                }
                            }
                            if (boolVSMatchingSolutionFound == false)
                            {
                                System.Windows.Forms.DialogResult myResult = myActions.MessageBoxShowWithYesNo("I could not find the solution (" + strSolutionName + ") currently running.\n\r\n\r Do you want me to launch it in Visual Studio for you.\n\r\n\rTo go ahead and launch the solution, click yes, otherwise, click no to cancel");
                                if (myResult == System.Windows.Forms.DialogResult.No)
                                {
                                    return;
                                }
                                string strVSPath = myActions.GetValueByKeyGlobal("VS2013Path");
                                // C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\devenv.exe
                                if (strVSPath == "")
                                {
                                    List <ControlEntity> myListControlEntity = new List <ControlEntity>();

                                    ControlEntity myControlEntity = new ControlEntity();
                                    myControlEntity.ControlEntitySetDefaults();
                                    myControlEntity.ControlType = ControlType.Heading;
                                    myControlEntity.Text        = "Specify location of Visual Studio";
                                    myListControlEntity.Add(myControlEntity.CreateControlEntity());


                                    myControlEntity.ControlEntitySetDefaults();
                                    myControlEntity.ControlType  = ControlType.Label;
                                    myControlEntity.ID           = "myLabel";
                                    myControlEntity.Text         = "Visual Studio Executable:";
                                    myControlEntity.RowNumber    = 0;
                                    myControlEntity.ColumnNumber = 0;
                                    myListControlEntity.Add(myControlEntity.CreateControlEntity());

                                    myControlEntity.ControlEntitySetDefaults();
                                    myControlEntity.ControlType  = ControlType.TextBox;
                                    myControlEntity.ID           = "myAltExecutable";
                                    myControlEntity.Text         = "";
                                    myControlEntity.RowNumber    = 0;
                                    myControlEntity.ColumnNumber = 1;
                                    myListControlEntity.Add(myControlEntity.CreateControlEntity());

                                    myActions.WindowMultipleControls(ref myListControlEntity, 600, 500, 0, 0);
                                    string strAltExecutable = myListControlEntity.Find(x => x.ID == "myAltExecutable").Text;
                                    myActions.SetValueByKeyGlobal("VS2013Path", strAltExecutable);
                                    strVSPath = strAltExecutable;
                                }
                                myActions.Run(strVSPath, "\"" + strSolutionFullFileName + "\"");
                                myActions.Sleep(10000);
                                myActions.MessageBoxShow("When visual studio finishes loading, please click okay to continue");
                                myActions.TypeText("{ESCAPE}", 500);
                                boolSolutionFileFound = true;
                                strSolutionName       = currentTempName.Substring(currentTempName.LastIndexOf("\\") + 1).Replace(".sln", "");
                                myWindowTitles        = myActions.GetWindowTitlesByProcessName("devenv");
                                myWindowTitles.RemoveAll(vsItem => vsItem == "");
                                boolVSMatchingSolutionFound = false;
                                foreach (var vsTitle in myWindowTitles)
                                {
                                    if (vsTitle.StartsWith(strSolutionName + " - "))
                                    {
                                        boolVSMatchingSolutionFound = true;
                                        myActions.ActivateWindowByTitle(vsTitle, 3);
                                        myActions.Sleep(1000);
                                        myActions.TypeText("{ESCAPE}", 500);
                                        myBeginDelim = new List <string>();
                                        myEndDelim   = new List <string>();
                                        myBeginDelim.Add("\"");
                                        myEndDelim.Add("\"");
                                        delimParms = new FindDelimitedTextParms(myBeginDelim, myEndDelim);

                                        myQuote             = "\"";
                                        delimParms.lines[0] = myOrigEditPlusLine;


                                        myActions.FindDelimitedText(delimParms);
                                        intLastSlash = delimParms.strDelimitedTextFound.LastIndexOf('\\');
                                        if (intLastSlash < 1)
                                        {
                                            myActions.MessageBoxShow("Could not find last slash in in EditPlusLine - aborting");
                                            break;
                                        }
                                        strPathOnly     = delimParms.strDelimitedTextFound.SubstringBetweenIndexes(0, intLastSlash);
                                        strFileNameOnly = delimParms.strDelimitedTextFound.Substring(intLastSlash + 1);
                                        myBeginDelim.Clear();
                                        myEndDelim.Clear();
                                        myBeginDelim.Add("(");
                                        myEndDelim.Add(",");
                                        delimParms          = new FindDelimitedTextParms(myBeginDelim, myEndDelim);
                                        delimParms.lines[0] = myOrigEditPlusLine;
                                        myActions.FindDelimitedText(delimParms);
                                        strLineNumber = delimParms.strDelimitedTextFound;
                                        myActions.TypeText("{ESC}", 2000);
                                        myActions.TypeText("%(f)", 1000);
                                        myActions.TypeText("{DOWN}", 1000);
                                        myActions.TypeText("{RIGHT}", 1000);
                                        myActions.TypeText("f", 1000);
                                        // myActions.TypeText("^(o)", 2000);
                                        myActions.TypeText("%(d)", 1500);
                                        myActions.TypeText(strPathOnly, 1500);
                                        myActions.TypeText("{ENTER}", 500);
                                        myActions.TypeText("%(n)", 500);
                                        myActions.TypeText(strFileNameOnly, 1500);
                                        myActions.TypeText("{ENTER}", 1000);
                                        break;
                                    }
                                }
                            }
                            if (boolVSMatchingSolutionFound == false)
                            {
                                myActions.MessageBoxShow("Could not find visual studio for " + strSolutionName);
                            }
                            break;
                        }
                    } catch (UnauthorizedAccessException e) {
                        Console.WriteLine(e.Message);
                        continue;
                    } catch (System.IO.DirectoryNotFoundException e) {
                        Console.WriteLine(e.Message);
                        continue;
                    } catch (System.IO.PathTooLongException e) {
                        Console.WriteLine(e.Message);
                        continue;
                    } catch (Exception e) {
                        Console.WriteLine(e.Message);
                        continue;
                    }
                }
            }

            myActions.TypeText("^(g)", 500);
            myActions.TypeText(strLineNumber, 500);
            myActions.TypeText("{ENTER}", 500);
            goto myExit;


myExit:

            //myActions.MessageBoxShow("Script completed");
            myActions.ScriptEndedSuccessfullyUpdateStats();
            Application.Current.Shutdown();
        }
Exemplo n.º 30
0
 public bool Edit()
 {
     System.Windows.Forms.Form         frm    = Form;
     System.Windows.Forms.DialogResult result = frm.ShowDialog();
     return(result == System.Windows.Forms.DialogResult.OK);
 }
Exemplo n.º 31
0
        public void DoSettings()
        {
            //check control type
            if (Values[listBox.SelectedIndex].type != new Control())
            {
                ListViewItem lvi = listView.SelectedValue as ListViewItem;

                Values[listBox.SelectedIndex].SValue = lvi.Content.ToString();
                if (Values[listBox.SelectedIndex].SValue == "On")
                {
                    switch (Values[listBox.SelectedIndex].SettingName)
                    {
                    case "Overwrite Temp Folder":
                        Properties.Settings.Default.OverwriteTemp = true;
                        break;

                    case "Replace NP Title ID With PS2 Title ID":
                        Properties.Settings.Default.EnablePS2IDReplace = true;
                        break;

                    case "Enable Boot Logo":
                        Properties.Settings.Default.EnableBootScreen = true;
                        break;

                    case "Enable PS4 Ambient Music":
                        Properties.Settings.Default.EnableGuiMusic = true;

                        SoundClass.PlayPS4Sound(SoundClass.Sound.PS4_Music);

                        break;

                    case "Enable kozarovv Patches":
                        Properties.Settings.Default.EnableCustomConfigFetching = true;
                        break;

                    case "★ Use New PS2 Emulator":
                        Properties.Settings.Default.EnableNewEmu = true;
                        break;

                    case "★ Enable Widescreen (16:9)":
                        Properties.Settings.Default.Widescreen = true;
                        break;

                    case "★ Possible Game Loading Fix":
                        Properties.Settings.Default.LoadingFix = true;
                        break;

                    case "★ Possible Graphics & Glitches Fix":
                        Properties.Settings.Default.GraphicsFix = true;
                        break;

                    case "★ Save last Background Image":
                        Properties.Settings.Default.SaveBackground = true;
                        break;

                    case "★ Use ISO filename as Game Title":
                        Properties.Settings.Default.GetTitle = true;
                        break;
                    }
                    Properties.Settings.Default.Save();//save the settings
                }
                else
                {
                    switch (Values[listBox.SelectedIndex].SettingName)
                    {
                    case "Overwrite Temp Folder":
                        Properties.Settings.Default.OverwriteTemp = false;
                        break;

                    case "Replace NP Title ID With PS2 Title ID":
                        Properties.Settings.Default.EnablePS2IDReplace = false;
                        break;

                    case "Enable Boot Logo":
                        Properties.Settings.Default.EnableBootScreen = false;

                        break;

                    case "Enable PS4 Ambient Music":
                        Properties.Settings.Default.EnableGuiMusic = false;
                        if (SoundClass.PS4BGMDevice != null)
                        {
                            SoundClass.PS4BGMDevice.Stop();
                        }
                        break;

                    case "Enable kozarovv Patches":
                        Properties.Settings.Default.EnableCustomConfigFetching = false;
                        break;

                    case "★ Use New PS2 Emulator":
                        Properties.Settings.Default.EnableNewEmu = false;
                        break;

                    case "★ Enable Widescreen (16:9)":
                        Properties.Settings.Default.Widescreen = false;
                        break;

                    case "★ Possible Game Loading Fix":
                        Properties.Settings.Default.LoadingFix = false;
                        break;

                    case "★ Possible Graphics & Glitches Fix":
                        Properties.Settings.Default.GraphicsFix = false;
                        break;

                    case "★ Save last Background Image":
                        Properties.Settings.Default.SaveBackground = false;
                        break;

                    case "★ Use ISO filename as Game Title":
                        Properties.Settings.Default.GetTitle = false;
                        break;
                    }
                    Properties.Settings.Default.Save();//save the settings
                }
            }
            else
            {
                using (var dialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    System.Windows.Forms.DialogResult result = dialog.ShowDialog();
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        Properties.Settings.Default.TempPath = dialog.SelectedPath.ToString();
                    }
                    Values[listBox.SelectedIndex].SValue = Properties.Settings.Default.TempPath;
                }
                Properties.Settings.Default.Save();//save the settings
            }

            //close the options pannel
            MainWindowView.Opacity = 1.0f;
            OptionsView.Visibility = Visibility.Hidden;
            listBox.Background     = System.Windows.Media.Brushes.Transparent;

            ClearAndAddList();
        }
Exemplo n.º 32
0
        //Pack utility
        private void MenuItem_Click_6(object sender, RoutedEventArgs e)
        {
            if (!File.Exists("WinPack.exe"))
            {
                MessageBox.Show("I couldn't find WinPack.exe please copy it here. You can get it here https://github.com/fjay69/UndertaleTools");
                return;
            }
            //Extract Undertale
            var dialog = new System.Windows.Forms.FolderBrowserDialog();

            dialog.Description = "Select Undertale folder";

            if (Directory.Exists(Project.UndertalePath))
            {
                dialog.SelectedPath = Project.UndertalePath;
            }

            System.Windows.Forms.DialogResult result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                string up = System.IO.Path.Combine(dialog.SelectedPath, "data.win");
                if (!File.Exists(up))
                {
                    MessageBox.Show("This is not Undertale! YOU LITTLE LIAR!111");
                    return;
                }
                Project.UndertalePath = dialog.SelectedPath;

                var dialog2 = new System.Windows.Forms.FolderBrowserDialog();
                dialog2.Description = "Select project folder with translation.";
                if (Project.Loaded)
                {
                    dialog2.SelectedPath = Project.PrjPath;
                }
                result = dialog2.ShowDialog();
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    string dest = System.IO.Path.Combine(dialog2.SelectedPath);
                    if (!File.Exists(System.IO.Path.Combine(dest, "translate.txt")))
                    {
                        MessageBox.Show("This is not your translation folder! Choose folder, where you extact THE GAME");
                        return;
                    }

                    File.Copy(up, System.IO.Path.Combine(dialog.SelectedPath, "data_backup" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + ".win"), true);

                    File.WriteAllLines("lastpath.txt", new string[] { dest, dialog.SelectedPath });
                    Project.UndertalePath = dialog.SelectedPath;

                    var proc = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName               = "WinPack.exe",
                            Arguments              = dest + " " + up + " -tt",
                            UseShellExecute        = false,
                            RedirectStandardOutput = true,
                            CreateNoWindow         = true
                        }
                    };
                    if (System.Environment.OSVersion.Version.Major >= 6)
                    {
                        proc.StartInfo.Verb = "runas";
                    }
                    proc.Start();
                    string o    = "";
                    string line = "";
                    while (!proc.StandardOutput.EndOfStream)
                    {
                        line = proc.StandardOutput.ReadLine();
                        o   += line + "\n";
                    }
                    MessageBox.Show(o);
                }
                else
                {
                    MessageBox.Show("Please, select folder with translated text.");
                }
            }
            else
            {
                MessageBox.Show("Please, choose Undertale folder.");
            }
        }
Exemplo n.º 33
0
        public void GetInfo(object param)
        {
            try
            {
                List <CustomListItem> tiklanilanNoktadakiVeriler = new List <CustomListItem>();
                string x = Program.miApplication.EvalMapBasicCommand("commandinfo(1)").Replace(",", ".");
                string y = Program.miApplication.EvalMapBasicCommand("commandinfo(2)").Replace(",", ".");
                int    tiklanilanNoktadakiKayitSayisi = Convert.ToInt32(Program.miApplication.EvalMapBasicCommand("SearchPoint(frontwindow()," + x + "," + y + ")"));

                if (tiklanilanNoktadakiKayitSayisi > 0)
                {
                    for (int i = 1; i <= tiklanilanNoktadakiKayitSayisi; i++)
                    {
                        string tabloAdi = Program.miApplication.EvalMapBasicCommand("SearchInfo(" + i.ToString() + ",1)");
                        string rowId    = Program.miApplication.EvalMapBasicCommand("SearchInfo(" + i.ToString() + ",2)");
                        Program.miApplication.RunMapBasicCommand("Fetch rec " + rowId + " From " + tabloAdi);
                        if (!tabloAdi.StartsWith("Sel_"))
                        {
                            switch (tabloAdi)
                            {
                            case "SBK_OGHAT":
                                tiklanilanNoktadakiVeriler.Add(new CustomListItem()
                                {
                                    Text  = tabloAdi + " (" + Program.miApplication.EvalMapBasicCommand(tabloAdi + ".TIPI") + ")",
                                    Value = tabloAdi + "#" + rowId
                                });
                                break;

                            default:

                                break;
                            }
                        }
                    }
                }
                if (tiklanilanNoktadakiVeriler.Count <= 0)
                {
                    System.Windows.Forms.MessageBox.Show(" Tıklanılan Noktada Birşey Bulamadık.");
                }
                else if (tiklanilanNoktadakiVeriler.Count == 1)
                {
                    Program._form.ShowInfo(tiklanilanNoktadakiVeriler[0].Value.ToString());
                }
                else
                {
                    BilgiListe listeForm = new BilgiListe();
                    listeForm.Owner = Program._form;
                    listeForm.listBoxVeriler.Items.Clear();
                    for (int i = 0; i < tiklanilanNoktadakiVeriler.Count; i++)
                    {
                        listeForm.listBoxVeriler.Items.Add(tiklanilanNoktadakiVeriler[i]);
                    }
                    System.Windows.Forms.DialogResult res = listeForm.ShowDialog();
                    if (res == System.Windows.Forms.DialogResult.OK)
                    {
                        Program._form.ShowInfo(listeForm.SeciliKayit);
                    }
                }
            }
            catch (Exception)
            {
                System.Windows.Forms.MessageBox.Show("Beklenmeyen Bir Hata Oluştu");
            }
        }
        private void btnRedeemTickets_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                LogManager.WriteLog("Inside btnRedeemTickets_Click", LogManager.enumLogLevel.Info);
                txtAmount.Visibility = System.Windows.Visibility.Visible;
                txtCount.Visibility = System.Windows.Visibility.Visible;
                if (lvTickets.Items.Count > 0)
                {

                    txtErrorStatus.Clear();

                    btnRedeemTickets.Visibility = System.Windows.Visibility.Hidden;

                    btnClearRedeem.Visibility = System.Windows.Visibility.Hidden;



                    if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                    {
                        _diagResult = MessageBox.ShowBox("RedeemMultipleTicketConfirmationID1", BMC_Icon.Information, BMC_Button.YesNo);
                    }
                    else
                    {
                        _diagResult = System.Windows.Forms.DialogResult.Yes;
                    }

                    if (_diagResult == System.Windows.Forms.DialogResult.Yes)
                    {
                        try
                        {
                            LogManager.WriteLog("Initializing the Redeem Thread", LogManager.enumLogLevel.Info);
                            _AutoReset.Reset();
                            DisableRemoveVoucher(false);
                            //btnStopRedeem.Visibility = System.Windows.Visibility.Visible;
                            //btnStopRedeem.IsEnabled = true;
                            txtFinalStatus.Visibility = System.Windows.Visibility.Visible;
                            txtErrorStatus.Visibility = System.Windows.Visibility.Visible;
                            txtErrorStatus.Clear();
                            btnClearRedeem.Visibility = System.Windows.Visibility.Hidden;
                            btnRedeemTickets.Visibility = System.Windows.Visibility.Hidden;
                            //to open the redeem status window when the redemption starts
                            showModel(RedeemTickets);
                            LogManager.WriteLog("Redemptiom completed", LogManager.enumLogLevel.Info);
                        }

                        catch (Exception ex)
                        {
                            ExceptionManager.Publish(ex);
                        }
                    }
                    else
                    {

                        txtErrorStatus.Text = Application.Current.Resources["CRedeemMultipleTicketCancellation"].ToString();
                        btnClearRedeem.Visibility = System.Windows.Visibility.Visible;
                        btnRedeemTickets.Visibility = System.Windows.Visibility.Visible;
                        txtAmount.Visibility = System.Windows.Visibility.Visible;
                        txtCount.Visibility = System.Windows.Visibility.Visible;
                        dispTimer.Stop();
                    }

                }
                else
                {
                   txtErrorStatus.Text = Application.Current.Resources["CRedeemMultipleVoucherNoTicketFound"].ToString();
                   txtBarcodeVal.Focus();
                }
            }
            catch (Exception ex)
            {                
                ExceptionManager.Publish(ex);
            }

        }
Exemplo n.º 35
0
        private void button_Click(object sender, RoutedEventArgs e)
        {
            bool isValid = false;
            RTOnlineTicketDetail objTicketDetail = null;

            double redeemTicketAmount = 0;

            bool IsCashDispenseError = false;

            try
            {
                if (isScannerFired) //check done not to fire the verify event twice while verifying a ticket using scanner
                {
                    isScannerFired = false;
                    return;
                }
                ClearAll(true);
                TextBlock_11.Text   = string.Empty;
                txtAmount.Text      = string.Empty;
                btnVerify.IsEnabled = false;
                if ((sender is System.Windows.Controls.TextBox))
                {
                    isScannerFired = true;
                }
                else
                {
                    isScannerFired = false;
                }

                if (this.ucValueCalc.txtDisplay.Text.Trim().Length > 0)
                {
                    if (this.ucValueCalc.txtDisplay.Text.Trim().Length < 4)
                    {
                        MessageBox.ShowBox("MessageID403", BMC_Icon.Error);
                        this.txtStatus.Visibility        = Visibility.Hidden;
                        this.ucValueCalc.txtDisplay.Text = String.Empty;
                        return;
                    }

                    IRedeemOnlineTicket objCashDeskOper = RedeemOnlineTicketBusinessObject.CreateInstance();
                    objTicketDetail = new RTOnlineTicketDetail();

                    objTicketDetail.ClientSiteCode  = Settings.SiteCode;
                    objTicketDetail.TicketString    = this.ucValueCalc.txtDisplay.Text.Trim();
                    objTicketDetail.HostSiteCode    = objTicketDetail.TicketString.Substring(0, 4);
                    objTicketDetail.RedeemedMachine = System.Environment.MachineName;

                    objTicketDetail = objCashDeskOper.GetRedeemTicketAmount(objTicketDetail);

                    if (objTicketDetail.TicketStatusCode == -990) //TIS Error (If any)
                    {
                        MessageBox.ShowBox(objTicketDetail.TicketErrorMessage, BMC_Icon.Error, true);
                        disptimerRedeem.Stop();
                        this.txtStatus.Visibility = Visibility.Hidden;
                        return;
                    }

                    if (objTicketDetail.TicketStatusCode == -234) //Exception Occured
                    {
                        MessageBox.ShowBox("MessageID425", BMC_Icon.Error);
                        disptimerRedeem.Stop();
                        this.txtStatus.Visibility = Visibility.Hidden;
                        return;
                    }

                    if (objTicketDetail.TicketStatusCode == -99) //Included for Cross Ticketing
                    {
                        MessageBox.ShowBox("MessageID403", BMC_Icon.Error);
                        disptimerRedeem.Stop();
                        this.txtStatus.Visibility        = Visibility.Hidden;
                        this.ucValueCalc.txtDisplay.Text = String.Empty;
                        return;
                    }



                    if (objTicketDetail.TicketStatusCode == 250)     //Any/specific player card required for TIS
                    {
                        bool ValidCard       = false;
                        int  PlayerCardClose = 0;



                        if (objTicketDetail.CardRequired == 2)
                        {
                            PlayerCardValidation objPlayerCardValidation = new PlayerCardValidation(objTicketDetail.CardRequired);
                            objPlayerCardValidation.ShowDialogEx(this);
                            ValidCard       = objPlayerCardValidation.valid;
                            PlayerCardClose = objPlayerCardValidation.Close;

                            if (PlayerCardClose == 1)
                            {
                                this.ucValueCalc.txtDisplay.Text = String.Empty;
                                this.ucValueCalc.txtDisplay.Focus();
                                return;
                            }

                            else if (!ValidCard)
                            {
                                MessageBox.ShowBox("PlayerCardRedeem6", BMC_Icon.Error);
                                this.ucValueCalc.txtDisplay.Text = String.Empty;
                                this.ucValueCalc.txtDisplay.Focus();
                                return;
                            }
                        }
                        else if (objTicketDetail.CardRequired == 1)
                        {
                            PlayerCardValidation objPlayerCardValidation = new PlayerCardValidation(objTicketDetail.CardRequired, objTicketDetail.PlayerCardNumber);
                            objPlayerCardValidation.ShowDialogEx(this);
                            ValidCard       = objPlayerCardValidation.valid;
                            PlayerCardClose = objPlayerCardValidation.Close;
                            if (PlayerCardClose == 1)
                            {
                                this.ucValueCalc.txtDisplay.Text = String.Empty;
                                this.ucValueCalc.txtDisplay.Focus();
                                return;
                            }
                            else if (!ValidCard)
                            {
                                MessageBox.ShowBox("PlayerCardRedeem6", BMC_Icon.Error);
                                this.ucValueCalc.txtDisplay.Text = String.Empty;
                                this.ucValueCalc.txtDisplay.Focus();
                                return;
                            }
                        }

                        objTicketDetail.TicketStatusCode = 0;
                    }


                    int ticketAmount = Convert.ToInt32(objTicketDetail.RedeemedAmount);

                    redeemTicketAmount = ticketAmount / 100;

                    objTicketDetail.CustomerId = Custid;

                    this.txtStatus.Visibility = Visibility.Visible;
                    this.txtStatus.Text       = "VALIDATING.";
                    disptimerRedeem.IsEnabled = true;
                    disptimerRedeem.Start();


                    //if ((objCashDeskOper.CheckSDGTicket(objTicketDetail.TicketString) == 0) && (Settings.RedeemConfirm))
                    if (objTicketDetail.TicketStatusCode == 0 && (Settings.RedeemConfirm))
                    {
                        disptimerRedeem.Stop();
                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                        {
                            _diagResult = MessageBox.ShowBox("MessageID225", BMC_Icon.Question, BMC_Button.YesNo);
                        }
                        else
                        {
                            _diagResult = System.Windows.Forms.DialogResult.Yes;
                        }
                        if (_diagResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            #region ITALY CODE COMMENTED
                            //if (Settings.RegulatoryEnabled == true && Settings.RegulatoryType == "AAMS")
                            //{
                            //    ProcessCancelled = false;
                            //    if (ticketStatus == 0)
                            //    {
                            //        if (redeemTicketAmount >= Settings.RedeemTicketCustomer_Min && redeemTicketAmount <= Settings.RedeemTicketCustomer_Max)
                            //        {
                            //            customerDetails = new BMC.Presentation.POS.Views.CustomerDetails();
                            //            customerDetails.delCustomerUpdated += new BMC.Presentation.POS.Views.CustomerDetails.CustomerUpdateHandler(delCustomerUpdated);
                            //            customerDetails.delCustomerCancelled += new BMC.Presentation.POS.Views.CustomerDetails.CustomerCancelHandler(delCustomerCancelled);
                            //            Owner = Window.GetWindow(this);
                            //            customerDetails.ShowDialog();
                            //        }
                            //        else if (redeemTicketAmount >= Settings.RedeemTicketCustomer_BankAcctNo)
                            //        {
                            //            customerDetails = new BMC.Presentation.POS.Views.CustomerDetails(true);
                            //            customerDetails.delCustomerUpdated += new BMC.Presentation.POS.Views.CustomerDetails.CustomerUpdateHandler(delCustomerUpdated);
                            //            customerDetails.delCustomerCancelled += new BMC.Presentation.POS.Views.CustomerDetails.CustomerCancelHandler(delCustomerCancelled);
                            //            Owner = Window.GetWindow(this);
                            //            customerDetails.ShowDialog();
                            //        }

                            //        if (ProcessCancelled)
                            //        {
                            //            MessageBox.ShowBox("MessageID299", BMC_Icon.Information);
                            //            this.ucValueCalc.txtDisplay.Text = string.Empty;
                            //            return;
                            //        }
                            //    }
                            //}
                            #endregion

                            objTicketDetail = objCashDeskOper.RedeemOnlineTicket(objTicketDetail);
                            isValid         = objTicketDetail.ValidTicket;
                        }
                        else
                        {
                            disptimerRedeem.Start();
                            this.txtStatus.Visibility = Visibility.Hidden;
                            return;
                        }
                        disptimerRedeem.Start();
                    }
                    //else if ((objCashDeskOper.CheckSDGTicket(objTicketDetail.TicketString) == -3) && (Settings.RedeemConfirm)
                    else if (objTicketDetail.TicketStatusCode == -3 && (Settings.RedeemConfirm) && Settings.RedeemExpiredTicket)
                    {
                        disptimerRedeem.Stop();

                        CAuthorize objAuthorize = null;
                        //Manoj 26th Aug 2010. CR383384
                        //RedeemExpiredTicket functionality has been implmented for Winchells.
                        //So, in settings RedeemExpiredTicket will be True for Winchells, for rest it will be False.
                        //So we dont need the following if condition.
                        //if (Settings.Client != null && Settings.Client.ToLower() == "winchells")
                        //{
                        objAuthorize      = new CAuthorize("CashdeskOperator.Authorize.cs.ReedemExpiredTicket");
                        objAuthorize.User = Security.SecurityHelper.CurrentUser;
                        string Cur_User_Name = Security.SecurityHelper.CurrentUser.Last_Name + ", " + Security.SecurityHelper.CurrentUser.First_Name;
                        objTicketDetail.RedeemedUser = Cur_User_Name;

                        if (!Security.SecurityHelper.HasAccess("CashdeskOperator.Authorize.cs.ReedemExpiredTicket"))
                        {
                            objAuthorize.ShowDialogEx(this);

                            string Auth_User_Name = objAuthorize.User.UserName;
                            if (objAuthorize.User.Last_Name != null && objAuthorize.User.First_Name != null)
                            {
                                Auth_User_Name = objAuthorize.User.Last_Name + ", " + objAuthorize.User.First_Name;
                            }
                            else
                            {
                                Auth_User_Name = objAuthorize.User.UserName;
                            }

                            objTicketDetail.RedeemedUser = Auth_User_Name;

                            if (!objAuthorize.IsAuthorized)
                            {
                                ClearAll(false);
                                return;
                            }
                        }
                        else
                        {
                            objAuthorize.IsAuthorized = true;
                        }
                        //}

                        if (objAuthorize != null && objAuthorize.IsAuthorized)
                        {
                            objTicketDetail.AuthorizedUser_No = objAuthorize.User.SecurityUserID;
                            objTicketDetail.Authorized_Date   = DateTime.Now;

                            AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                            {
                                AuditModuleName    = ModuleName.Voucher,
                                Audit_Screen_Name  = "Vouchers|RedeemVoucher",
                                Audit_Desc         = "Voucher Number-" + objTicketDetail.TicketString,
                                AuditOperationType = OperationType.MODIFY,
                                Audit_Field        = "AuthorizedUser_No",
                                Audit_New_Vl       = Security.SecurityHelper.CurrentUser.SecurityUserID.ToString()
                            });
                        }
                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                        {
                            _diagResult = MessageBox.ShowBox("MessageID225", BMC_Icon.Question, BMC_Button.YesNo);
                        }
                        else
                        {
                            _diagResult = System.Windows.Forms.DialogResult.Yes;
                        }
                        if (_diagResult == System.Windows.Forms.DialogResult.Yes)
                        {
                            #region ITALY CODE COMMENTED
                            //if (Settings.RegulatoryEnabled == true && Settings.RegulatoryType == "AAMS")
                            //{
                            //    ProcessCancelled = false;
                            //    if (ticketStatus == 0)
                            //    {
                            //        if (redeemTicketAmount >= Settings.RedeemTicketCustomer_Min && redeemTicketAmount <= Settings.RedeemTicketCustomer_Max)
                            //        {
                            //            customerDetails = new BMC.Presentation.POS.Views.CustomerDetails();
                            //            customerDetails.delCustomerUpdated += new BMC.Presentation.POS.Views.CustomerDetails.CustomerUpdateHandler(delCustomerUpdated);
                            //            customerDetails.delCustomerCancelled += new BMC.Presentation.POS.Views.CustomerDetails.CustomerCancelHandler(delCustomerCancelled);
                            //            Owner = Window.GetWindow(this);
                            //            customerDetails.ShowDialog();
                            //        }
                            //        else if (redeemTicketAmount >= Settings.RedeemTicketCustomer_BankAcctNo)
                            //        {
                            //            customerDetails = new BMC.Presentation.POS.Views.CustomerDetails(true);
                            //            customerDetails.delCustomerUpdated += new BMC.Presentation.POS.Views.CustomerDetails.CustomerUpdateHandler(delCustomerUpdated);
                            //            customerDetails.delCustomerCancelled += new BMC.Presentation.POS.Views.CustomerDetails.CustomerCancelHandler(delCustomerCancelled);
                            //            Owner = Window.GetWindow(this);
                            //            customerDetails.ShowDialog();
                            //        }

                            //        if (ProcessCancelled)
                            //        {
                            //            MessageBox.ShowBox("MessageID299", BMC_Icon.Information);
                            //            this.ucValueCalc.txtDisplay.Text = string.Empty;
                            //            return;
                            //        }
                            //    }
                            //}

                            #endregion
                            objTicketDetail = objCashDeskOper.RedeemOnlineTicket(objTicketDetail);
                            isValid         = objTicketDetail.ValidTicket;
                        }
                        else
                        {
                            disptimerRedeem.Start();
                            this.txtStatus.Visibility = Visibility.Hidden;
                            return;
                        }
                        disptimerRedeem.Start();
                    }
                    else
                    {
                        objTicketDetail = objCashDeskOper.RedeemOnlineTicket(objTicketDetail);
                        isValid         = objTicketDetail.ValidTicket;
                    }

                    if (objTicketDetail.TicketStatus == "MessageID210")
                    {
                        objTicketDetail.TicketStatus = Application.Current.FindResource(objTicketDetail.TicketStatus).ToString() +
                                                       "(" + CommonUtilities.GetCurrency(Convert.ToDouble(objTicketDetail.TicketValue / 100)) + ")";
                    }
                    else
                    {
                        objTicketDetail.TicketStatus = Application.Current.FindResource(objTicketDetail.TicketStatus).ToString();
                    }

                    IsCashDispenseError = true;
                    if (isValid && objTicketDetail.RedeemedMachine != null && objTicketDetail.RedeemedMachine != string.Empty)
                    {
                        try
                        {
                            //DateTime PrintDate;
                            //string strbar_pos = objCashDeskOper.GetTicketPrintDevice(objTicketDetail.TicketString, out PrintDate);
                            DateTime PrintDate  = DateTime.Now;
                            string   strbar_pos = objCashDeskOper.GetTicketPrintDevice(objTicketDetail.TicketString, out PrintDate);
                            //TextBlock_11.Text = "#" + strbar_pos + PrintDate.ToString().Replace("/", "").Replace(":", "").Replace("AM", "0").Replace("PM", "1").Replace(" ", "");
                            //TextBlock_11.Text = "#" + objTicketDetail.PrintedDevice + objTicketDetail.PrintedDate.ToString().Replace("/", "").Replace(":", "").Replace("AM", "0").Replace("PM", "1").Replace(" ", "");
                            if (objTicketDetail.RedeemedDate == null || objTicketDetail.RedeemedDate.ToString().Trim().Equals(string.Empty))
                            {
                                TextBlock_11.Text = string.Empty;
                            }
                            else
                            {
                                TextBlock_11.Text = "#" + strbar_pos + objTicketDetail.RedeemedDate.ToString("ddMMyyyyHHmmss");
                            }

                            txtAmount.Text = objTicketDetail.RedeemedAmount.GetUniversalCurrencyFormat();
                            if (!objTicketDetail.TicketStatus.Trim().ToUpper().Equals("ALREADY CLAIMED"))
                            {
                                #region GCD
                                if (Settings.IsGloryCDEnabled && Settings.CashDispenserEnabled)
                                {
                                    LogManager.WriteLog(string.Format("Process Redeem Voucher: {2} for Bar Postion: {0} - Amount: {1} in cents", strbar_pos, ticketAmount, objTicketDetail.TicketString), LogManager.enumLogLevel.Info);

                                    //implement Cash Dispenser
                                    LogManager.WriteLog(string.Format("Amount: {0:0.00} Sending to Cash Dispenser ", ticketAmount), LogManager.enumLogLevel.Info);
                                    LoadingWindow ld = new LoadingWindow(Window.GetWindow(this), ModuleName.Voucher, TextBlock_11.Text, strbar_pos, ticketAmount);
                                    ld.Topmost = true;
                                    ld.ShowDialogEx(this);
                                    Result res = ld.Result;
                                    if (!res.IsSuccess)
                                    {
                                        IsCashDispenseError = false;
                                        this.txtStatus.Text = res.error.Message;
                                        LogManager.WriteLog(string.Format("Unable to Dispense Cash - Amount: {0}", ticketAmount), LogManager.enumLogLevel.Info);
                                        LogManager.WriteLog("Rollback Redeem Voucher Process", LogManager.enumLogLevel.Info);
                                        AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                                        {
                                            AuditModuleName    = ModuleName.Voucher,
                                            Audit_Screen_Name  = "Vouchers|RedeemVoucher",
                                            Audit_Desc         = "Rollback redeem voucher:" + objTicketDetail.TicketString + " due to cash dispenser error",
                                            AuditOperationType = OperationType.MODIFY,
                                            Audit_Old_Vl       = "iPayDeviceid:" + objTicketDetail.RedeemedDevice + ";dtPaid:" + objTicketDetail.RedeemedDate.GetUniversalDateTimeFormat() + ";Customerid:" + objTicketDetail.CustomerId.ToString()
                                        });
                                        objCashDeskOper.RollbackRedeemTicket(objTicketDetail.TicketString);
                                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                                        {
                                            BMC.Presentation.MessageBox.ShowBox(res.error.Message, res.error.MessageType.Equals("Error") ? BMC_Icon.Error : BMC_Icon.Information, true);
                                        }
                                    }
                                    else
                                    {
                                        LogManager.WriteLog(string.Format("Cash Dispensed Successfully - Amount: {0}", ticketAmount), LogManager.enumLogLevel.Info);

                                        IsCashDispenseError = true;
                                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                                        {
                                            BMC.Presentation.MessageBox.ShowBox(res.error.Message, res.error.MessageType.Equals("Error") ? BMC_Icon.Error : BMC_Icon.Information, true);
                                        }
                                    }
                                }
                                #endregion
                            }
                        }
                        catch (Exception Ex)
                        {
                            LogManager.WriteLog("Error showing Voucher Info :" + Ex.Message, LogManager.enumLogLevel.Error);
                        }
                    }

                    if (objTicketDetail.ShowOfflineTicketScreen)
                    {
                        int result;

                        if (objTicketDetail.HostSiteCode == Settings.SiteCode) // Offline Tickets redemption is valid only for local site code
                        {
                            result = objCashDeskOper.CheckSDGOfflineTicket(objTicketDetail.TicketString);
                        }
                        else
                        {
                            result = -14;
                        }

                        if (result == -14)// Site Code Mismatch
                        {
                            this.txtStatus.Visibility = Visibility.Visible;
                            this.txtStatus.Text       = Application.Current.FindResource("MessageID312") as string;
                            this.txtStatus.Background = System.Windows.Media.Brushes.Red;
                            return;
                        }
                        else
                        {
                            frmRedeemOffline = new BMC.Presentation.POS.Views.CRedeemOfflineTicket();
                            frmRedeemOffline.TicketNumber = ucValueCalc.txtDisplay.Text.Trim();
                            frmRedeemOffline.ShowDialogEx(this);
                            if (frmRedeemOffline.IsSuccessfull)
                            {
                                this.ucValueCalc.txtDisplay.Text = frmRedeemOffline.TicketNumber;
                                button_Click(sender, e);
                            }
                            else
                            {
                                this.ucValueCalc.txtDisplay.Text = string.Empty;
                                this.txtStatus.Clear();
                            }
                        }
                    }
                    else
                    {
                        if (Settings.IsGloryCDEnabled && (!IsCashDispenseError))
                        {
                            disptimerRedeem.Stop();
                            this.txtStatus.Visibility = Visibility.Visible;
                            this.txtStatus.Background = System.Windows.Media.Brushes.Red;
                            TextBlock_11.Text         = string.Empty;
                            txtAmount.Text            = string.Empty;
                            System.Threading.Thread.Sleep(100);
                            //System.Threading.Thread.CurrentThread
                            disptimerRedeem.Start();
                        }
                        else
                        {
                            this.txtStatus.Text = objTicketDetail.TicketStatus;
                            //"(" + CommonUtilities.GetCurrency(Convert.ToDouble(TicketDetail.TicketValue / 100)) + ")";
                            if (Application.Current.FindResource("MessageID219").ToString() == objTicketDetail.TicketStatus)
                            {
                                bisTicketExpired = true;
                            }
                            this.txtWarning.Text = objTicketDetail.TicketWarning;
                            if (!objTicketDetail.ValidTicket)
                            {
                                this.txtStatus.Background = System.Windows.Media.Brushes.Red;

                                AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                                {
                                    AuditModuleName    = ModuleName.Voucher,
                                    Audit_Screen_Name  = "Vouchers|RedeemVoucher",
                                    Audit_Desc         = "Invalid Voucher Redemption Attempt",
                                    AuditOperationType = OperationType.MODIFY,
                                    Audit_Field        = "Voucher Number",
                                    Audit_New_Vl       = objTicketDetail.TicketString
                                });
                            }
                            else
                            {
                                this.txtStatus.Background = System.Windows.Media.Brushes.White;

                                AuditViewerBusiness.InsertAuditData(new Audit.Transport.Audit_History
                                {
                                    AuditModuleName    = ModuleName.Voucher,
                                    Audit_Screen_Name  = "Vouchers|RedeemVoucher",
                                    Audit_Desc         = "Voucher Number-" + objTicketDetail.TicketString,
                                    AuditOperationType = OperationType.ADD,
                                    Audit_Field        = "Voucher Status",
                                    Audit_New_Vl       = objTicketDetail.TicketStatus
                                });

                                //Cross Ticketing- Insert Local Record
                                if (!string.IsNullOrEmpty(objTicketDetail.VoucherXMLData))
                                {
                                    objTicketDetail.RedeemedUser = Security.SecurityHelper.CurrentUser.UserName;
                                    objCashDeskOper.ImportVoucherDetails(objTicketDetail);
                                }

                                if (objTicketDetail.TicketStatus.Contains(Application.Current.FindResource("MessageID210").ToString()))
                                {
                                    //disptimerRedeem.Stop();

                                    Action act = new Action(() =>
                                    {
                                        if (Convert.ToBoolean(AppSettings.REDEEM_TICKET_POP_UP_ALERT_VISIBILITY))
                                        {
                                            if (IsCashDispenseError)
                                            {
                                                if (Settings.IsGloryCDEnabled)
                                                {
                                                    disptimerRedeem.Stop();
                                                    this.txtStatus.Visibility = Visibility.Visible;
                                                }
                                                else
                                                {
                                                    this.ClearAll(false);
                                                }
                                                MessageBox.ShowBox("MessageID377", BMC_Icon.Information);
                                            }
                                        }
                                        else
                                        {
                                            this.txtStatus.Text       = Application.Current.FindResource("MessageID377").ToString();
                                            txtAmount.Text            = Convert.ToDecimal(objTicketDetail.TicketValue / 100).GetUniversalCurrencyFormat();
                                            bisTicketExpired          = false;
                                            this.txtStatus.Background = System.Windows.Media.Brushes.GreenYellow;
                                        }
                                        if (!Settings.IsGloryCDEnabled)
                                        {
                                            this.dispenserStatus.LoadItemsAysnc();
                                        }
                                    });

                                    if (!Settings.IsGloryCDEnabled)
                                    {
                                        _worker.Dispense("Voucher Number", objTicketDetail.TicketString, objTicketDetail.RedeemedAmount, act);
                                    }
                                    else
                                    {
                                        act();
                                        disptimerRedeem.Start();
                                    }
                                }
                            }
                            if (objTicketDetail.EnableTickerPrintDetails)
                            {
                                this.gridRedeemedTicket.Visibility = Visibility.Visible;
                                this.txtPrintedMachine.Text        = objTicketDetail.RedeemedMachine;
                                this.txtClaimedDevice.Text         = objTicketDetail.RedeemedDevice;
                                this.txtTickAmount.Text            = objTicketDetail.RedeemedAmount.GetUniversalCurrencyFormatWithSymbol();
                                this.txtClaimedDate.Text           = objTicketDetail.RedeemedDate.GetUniversalDateTimeFormat();
                            }
                            else
                            {
                                this.gridRedeemedTicket.Visibility = Visibility.Hidden;
                            }
                            this.ucValueCalc.txtDisplay.Focus();
                        }
                    }
                }
                else
                {
                    MessageBox.ShowBox("MessageID105", BMC_Icon.Warning);
                    this.ucValueCalc.txtDisplay.Focus();
                }
            }
            catch (Exception ex)
            {
                BMC.Common.ExceptionManagement.ExceptionManager.Publish(ex);
            }
            finally
            {
                btnVerify.IsEnabled = true;
            }
        }
 public System.Windows.Forms.DialogResult ShowDialog(IWin32Window owner)
 {
     if (owner == this)
     {
         throw new ArgumentException(System.Windows.Forms.SR.GetString("OwnsSelfOrOwner", new object[] { "showDialog" }), "owner");
     }
     if (base.Visible)
     {
         throw new InvalidOperationException(System.Windows.Forms.SR.GetString("ShowDialogOnVisible", new object[] { "showDialog" }));
     }
     if (!base.Enabled)
     {
         throw new InvalidOperationException(System.Windows.Forms.SR.GetString("ShowDialogOnDisabled", new object[] { "showDialog" }));
     }
     if (!this.TopLevel)
     {
         throw new InvalidOperationException(System.Windows.Forms.SR.GetString("ShowDialogOnNonTopLevel", new object[] { "showDialog" }));
     }
     if (this.Modal)
     {
         throw new InvalidOperationException(System.Windows.Forms.SR.GetString("ShowDialogOnModal", new object[] { "showDialog" }));
     }
     if (!SystemInformation.UserInteractive)
     {
         throw new InvalidOperationException(System.Windows.Forms.SR.GetString("CantShowModalOnNonInteractive"));
     }
     if (((owner != null) && ((((int) System.Windows.Forms.UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, Control.GetSafeHandle(owner)), -20)) & 8) == 0)) && (owner is Control))
     {
         owner = ((Control) owner).TopLevelControlInternal;
     }
     this.CalledOnLoad = false;
     this.CalledMakeVisible = false;
     this.CloseReason = System.Windows.Forms.CloseReason.None;
     IntPtr capture = System.Windows.Forms.UnsafeNativeMethods.GetCapture();
     if (capture != IntPtr.Zero)
     {
         System.Windows.Forms.UnsafeNativeMethods.SendMessage(new HandleRef(null, capture), 0x1f, IntPtr.Zero, IntPtr.Zero);
         System.Windows.Forms.SafeNativeMethods.ReleaseCapture();
     }
     IntPtr activeWindow = System.Windows.Forms.UnsafeNativeMethods.GetActiveWindow();
     IntPtr handle = (owner == null) ? activeWindow : Control.GetSafeHandle(owner);
     base.Properties.SetObject(PropDialogOwner, owner);
     Form ownerInternal = this.OwnerInternal;
     if ((owner is Form) && (owner != ownerInternal))
     {
         this.Owner = (Form) owner;
     }
     try
     {
         base.SetState(0x20, true);
         this.dialogResult = System.Windows.Forms.DialogResult.None;
         base.CreateControl();
         if ((handle != IntPtr.Zero) && (handle != base.Handle))
         {
             if (System.Windows.Forms.UnsafeNativeMethods.GetWindowLong(new HandleRef(owner, handle), -8) == base.Handle)
             {
                 throw new ArgumentException(System.Windows.Forms.SR.GetString("OwnsSelfOrOwner", new object[] { "showDialog" }), "owner");
             }
             System.Windows.Forms.UnsafeNativeMethods.GetWindowLong(new HandleRef(this, base.Handle), -8);
             System.Windows.Forms.UnsafeNativeMethods.SetWindowLong(new HandleRef(this, base.Handle), -8, new HandleRef(owner, handle));
         }
         try
         {
             if (this.dialogResult == System.Windows.Forms.DialogResult.None)
             {
                 Application.RunDialog(this);
             }
         }
         finally
         {
             if (!System.Windows.Forms.UnsafeNativeMethods.IsWindow(new HandleRef(null, activeWindow)))
             {
                 activeWindow = handle;
             }
             if (System.Windows.Forms.UnsafeNativeMethods.IsWindow(new HandleRef(null, activeWindow)) && System.Windows.Forms.SafeNativeMethods.IsWindowVisible(new HandleRef(null, activeWindow)))
             {
                 System.Windows.Forms.UnsafeNativeMethods.SetActiveWindow(new HandleRef(null, activeWindow));
             }
             else if (System.Windows.Forms.UnsafeNativeMethods.IsWindow(new HandleRef(null, handle)) && System.Windows.Forms.SafeNativeMethods.IsWindowVisible(new HandleRef(null, handle)))
             {
                 System.Windows.Forms.UnsafeNativeMethods.SetActiveWindow(new HandleRef(null, handle));
             }
             this.SetVisibleCore(false);
             if (base.IsHandleCreated)
             {
                 if ((this.OwnerInternal != null) && this.OwnerInternal.IsMdiContainer)
                 {
                     this.OwnerInternal.Invalidate(true);
                     this.OwnerInternal.Update();
                 }
                 this.DestroyHandle();
             }
             base.SetState(0x20, false);
         }
     }
     finally
     {
         this.Owner = ownerInternal;
         base.Properties.SetObject(PropDialogOwner, null);
     }
     return this.DialogResult;
 }
Exemplo n.º 37
0
        /// <summary>
        /// Will read entries from a specific view in Glasshouse. For all matching columns names, entries will be updated or added at the end of excel list
        /// </summary>
        public void ReadGH()
        {
            if (_curview.Equals("__GHALLDATA__"))
            {
                // not supported
                System.Windows.Forms.DialogResult dlg2 = System.Windows.Forms.MessageBox.Show("We do not support reading from " + _curviewname + " in project " + _curprojname, "Read from Glasshouse", System.Windows.Forms.MessageBoxButtons.OK);
                return;
            }

            System.Windows.Forms.DialogResult dlg = System.Windows.Forms.MessageBox.Show("Are you sure you want to read from view " + _curviewname + " in project " + _curprojname,
                                                                                         "Read from Glasshouse", System.Windows.Forms.MessageBoxButtons.YesNo);
            if (dlg == System.Windows.Forms.DialogResult.No)
            {
                return;
            }

            // allways read  - glasshousejournalguid, short description
            Range rngid = FindGUIDCell();

            if (rngid == null)
            {
                System.Windows.Forms.MessageBox.Show("glasshousejournalguid not found in the first 10 by 10 cells");
                return;
            }
            int idrow = rngid.Row;
            int idcol = rngid.Column;

            var removehcols = new[] { "glasshousejournalguid", "BIM Objects count", "BIM Objects quantity" };
            //            var removehcols = new[] { "glasshousejournalguid", "short description" };

            var   activeSheet = _excel.ActiveSheet as Worksheet;
            Range usedRange   = activeSheet.UsedRange;
            int   maxr        = usedRange.Rows[1].Row + usedRange.Rows.Count - 1;
            int   maxc        = usedRange.Columns[1].Column + usedRange.Columns.Count - 1;
            // Make dictinary of columns
            List <gColumns> headers = new List <gColumns>();

            for (int c = idcol; c <= maxc; c++)
            {
                if (activeSheet.Cells[idrow, c].Value2 == null)
                {
                    continue;
                }
                string sc = activeSheet.Cells[idrow, c].Value2 as string;
                if (sc.Length > 0)
                {
                    gColumns gc = new gColumns();
                    gc.headerName   = sc.Trim();
                    gc.headerNameLC = gc.headerName.ToLower();
                    gc.colNo        = c;
                    gc.sync2gh      = false;

                    //
                    if (removehcols.Any(gc.headerNameLC.Contains))
                    {
                        headers.Add(gc);
                        continue;
                    }

                    if (activeSheet.Cells[idrow + 1, c].Value2 == null)
                    {
                        headers.Add(gc);
                        continue;
                    }

                    string syncway = (activeSheet.Cells[idrow + 1, c].Value2 as string).ToLower().Trim();
                    if (syncway.Equals("update"))
                    {
                        gc.sync2gh = true;
                    }

                    headers.Add(gc);
                }
            }

            System.Data.DataTable table = null;

            string s       = "Contacting server...";
            string caption = "Getting View Entries";

            using (View.WaitingForm pf = new View.WaitingForm(caption, s))
            {
                table = JournalEntries.GetViewEntries(Utils.apiKey, _curproj, _curview);
            }

            var removecols = new[] { "BIM Objects count", "BIM Objects quantity" };

            int updateno = 0;
            int newno    = 0;

            maxr = Math.Max(maxr, idrow + 2);

            int n = table.Rows.Count;

            s       = "{0} of " + n.ToString() + " rows processed...";
            caption = "Getting Data From Glasshouse";

            List <string> guidsexist = new List <string>();


            //write to excel
            // Initialize the array.
            Range range   = activeSheet.Range(activeSheet.Cells[idrow, idcol], activeSheet.Cells[maxr, maxc]);
            var   myArray = (object[, ])range.Value2;

            int resultRows = myArray.GetLength(0);
            int resultCols = myArray.GetLength(1);

            using (ProgressForm pf = new ProgressForm(caption, s, n))
            {
                foreach (System.Data.DataRow row in table.Rows)
                {
                    string rguid = (string)row[0];
                    guidsexist.Add(rguid);
                    int foundrow = -1;
                    for (int r = 3; r <= resultRows; r++)
                    {
                        //var guid = activeSheet.Cells[r, idcol].Value2;
                        var guid = myArray[r, 1];

                        if (guid == null)
                        {
                            continue;
                        }
                        string sguid = guid as string;
                        if (sguid.Length == 0)
                        {
                            continue;
                        }


                        if (rguid.Equals(sguid) == true)
                        {
                            foundrow = r;
                            break;
                        }
                    }

                    int colno     = 0;
                    int activerow = foundrow;
                    if (foundrow == -1)
                    {
                        maxr++; // new line
                        newno++;
                        resultRows++;
                        activerow = resultRows;
                        myArray   = AddRow(myArray);
                    }
                    else
                    {
                        updateno++;
                    }
                    foreach (object col in row.ItemArray)
                    {
                        string colname = table.Columns[colno].ColumnName.ToLower().Trim();
                        colno++;
                        //if (removecols.Any(colname.Contains)) continue;

                        gColumns match = headers.Find(v => v.headerNameLC.Equals(colname));

                        if (match == null)
                        {
                            continue;
                        }
                        if (match.sync2gh == true)
                        {
                            continue;
                        }
                        //activeSheet.Cells[activerow, match.colNo].Value = col;
                        myArray[activerow, match.colNo - idcol + 1] = col;
                    }
                    pf.Increment();
                }
            }


            //int resultRows = myArray.GetLength(0);
            //int resultCols = myArray.GetLength(1);

            ExcelReference sheet2 = (ExcelReference)XlCall.Excel(XlCall.xlSheetId, activeSheet.Name);
            ExcelReference target = new ExcelReference(idrow - 1, maxr - 1, idcol - 1, maxc - 1, sheet2.SheetId);

            _excel.ScreenUpdating = false;
            _excel.EnableEvents   = false;
            ExcelAsyncUtil.QueueAsMacro(() => { target.SetValue(myArray); });
            //_excel.ScreenUpdating = true;
            //_excel.EnableEvents = true;


            //_excel.Interactive = false;
            //_excel.ScreenUpdating = false;
            //_excel.EnableEvents = false;


            // check not valid rows
            List <int> notfoundrow = new List <int>();
            int        notfound    = 0;

            for (int r = idrow + 2; r <= maxr; r++)
            {
                var guid = activeSheet.Cells[r, idcol].Value2;
                if (guid == null)
                {
                    continue;
                }
                string sguid = guid as string;
                if (sguid.Length == 0)
                {
                    continue;
                }

                if (guidsexist.Contains(sguid) == false)
                {
                    activeSheet.Cells[r, idcol].Font.Strikethrough = true;
                    notfound++;
                }
                else
                {
                    activeSheet.Cells[r, idcol].Font.Strikethrough = false;
                }
            }

            //_excel.Interactive = true;
            _excel.ScreenUpdating = true;
            _excel.EnableEvents   = true;

            table = null;

            System.Windows.Forms.MessageBox.Show("Updated " + updateno + " entries, " + notfound + " obsolete and added " + newno + " new entries ", "Read From Glasshouse");
        }
 internal bool CheckCloseDialog(bool closingOnly)
 {
     if ((this.dialogResult == System.Windows.Forms.DialogResult.None) && base.Visible)
     {
         return false;
     }
     try
     {
         FormClosingEventArgs e = new FormClosingEventArgs(this.closeReason, false);
         if (!this.CalledClosing)
         {
             this.OnClosing(e);
             this.OnFormClosing(e);
             if (e.Cancel)
             {
                 this.dialogResult = System.Windows.Forms.DialogResult.None;
             }
             else
             {
                 this.CalledClosing = true;
             }
         }
         if (!closingOnly && (this.dialogResult != System.Windows.Forms.DialogResult.None))
         {
             FormClosedEventArgs args2 = new FormClosedEventArgs(this.closeReason);
             this.OnClosed(args2);
             this.OnFormClosed(args2);
             this.CalledClosing = false;
         }
     }
     catch (Exception exception)
     {
         this.dialogResult = System.Windows.Forms.DialogResult.None;
         if (NativeWindow.WndProcShouldBeDebuggable)
         {
             throw;
         }
         Application.OnThreadException(exception);
     }
     if (this.dialogResult == System.Windows.Forms.DialogResult.None)
     {
         return !base.Visible;
     }
     return true;
 }
Exemplo n.º 39
0
        public void WriteGH(bool csv = false)
        {
            bool   viewexport = true;
            string curview    = _curview;

            if (_curview.Equals("__GHALLDATA__"))
            {
                // not supported
                System.Windows.Forms.DialogResult dlg = System.Windows.Forms.MessageBox.Show("We do not support reading from " + _curviewname + " in project " + _curprojname,
                                                                                             "Read from Glasshouse", System.Windows.Forms.MessageBoxButtons.OK);
                return;
            }

            if (csv == false)
            {
                System.Windows.Forms.DialogResult dlg = System.Windows.Forms.MessageBox.Show("Are you sure you want to write data to Glasshouse project " + _curprojname,
                                                                                             "Write to Glasshouse", System.Windows.Forms.MessageBoxButtons.YesNo);
                if (dlg == System.Windows.Forms.DialogResult.No)
                {
                    return;
                }

                dlg = System.Windows.Forms.MessageBox.Show("Do you want to only update parameters in view " + _curviewname + "?",
                                                           "Write to Glasshouse - by specific view", System.Windows.Forms.MessageBoxButtons.YesNo);

                if (dlg == System.Windows.Forms.DialogResult.No)
                {
                    // limitation in API means data is dumped by "All Entries" view.
                    // API needs change so ALL info can be updated, ignoring whats in specific view
                    curview    = "all_entries";
                    viewexport = false;
                }
            }
            else
            {
                // limitation in API means data is dumped by "All Entries" view.
                // API needs change so ALL info can be updated, ignoring whats in specific view
                curview    = "all_entries";
                viewexport = false;
            }

            // allway read  - glasshousejournalguid, short description
            Range rngid = FindGUIDCell();

            if (rngid == null)
            {
                System.Windows.Forms.MessageBox.Show("glasshousejournalguid not found in the first 10 by 10 cells");
                return;
            }
            int idrow = rngid.Row;
            int idcol = rngid.Column;


            var removehcols = new[] { "glasshousejournalguid", "BIM Objects count", "BIM Objects quantity" };
            //            var removehcols = new[] { "glasshousejournalguid", "short description" };



            var   activeSheet = _excel.ActiveSheet as Worksheet;
            Range usedRange   = activeSheet.UsedRange;
            int   maxr        = usedRange.Rows[1].Row + usedRange.Rows.Count - 1;
            int   maxc        = usedRange.Columns[1].Column + usedRange.Columns.Count - 1;

            System.Data.DataTable table    = null;
            System.Data.DataRow   tablerow = null;
            if (curview != null)
            {
                using (View.WaitingForm wf = new View.WaitingForm("Getting Entries For Update", "Contacting server..."))
                {
                    table = JournalEntries.GetViewEntries(Utils.apiKey, _curproj, curview);
                }
                if (table.Rows.Count > 0)
                {
                    tablerow = table.Rows[0];
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Did not find any good data in view " + _curviewname);
                    return;
                }
            }
            else
            {
                // should never happen!?
                System.Windows.Forms.MessageBox.Show("Error - view undefined");
                return;
            }

            // Make dictinary of columns
            List <gColumns> headers       = new List <gColumns>();
            List <string>   updates       = new List <string>();
            List <string>   updatesheader = new List <string>();

            updatesheader.Add("GlassHouseJournalGUID");
            for (int c = idcol; c <= maxc; c++)
            {
                if (activeSheet.Cells[idrow, c].Value2 == null)
                {
                    continue;
                }
                string sc = activeSheet.Cells[idrow, c].Value2 as string;
                if (sc.Length > 0)
                {
                    gColumns gc = new gColumns();
                    gc.headerName   = sc.Trim();
                    gc.headerNameLC = gc.headerName.ToLower();
                    gc.colNo        = c;
                    gc.sync2gh      = false;

                    if (tablerow != null)
                    {
                        int colno = 0;
                        foreach (object col in tablerow.ItemArray)
                        {
                            string colname = table.Columns[colno].ColumnName.ToLower().Trim();
                            colno++;
                            if (colname.Equals(gc.headerNameLC))
                            {
                                gc.GHcolNo = colno;
                                break;
                            }
                        }
                    }
                    //
                    if (activeSheet.Cells[idrow + 1, c].Value2 == null)
                    {
                        headers.Add(gc);
                        continue;
                    }
                    string syncway = (activeSheet.Cells[idrow + 1, c].Value2 as string).ToLower().Trim();
                    if (removehcols.Any(gc.headerNameLC.Contains))
                    {
                        headers.Add(gc);
                        continue;
                    }
                    if (syncway.Equals("update"))
                    {
                        gc.sync2gh = true;
                        updatesheader.Add(gc.headerName);
                    }

                    headers.Add(gc);
                }
            }
            if (updatesheader.Count < 2)
            {
                System.Windows.Forms.MessageBox.Show("No parameters selected for updating");
                return;
            }


            List <string> newupdatesheader = new List <string>();

            if (viewexport == true)
            {
                headers = headers.OrderBy(o => o.GHcolNo).ToList();
                foreach (gColumns gc in headers)
                {
                    if (updatesheader.Any(gc.headerName.Contains))
                    {
                        newupdatesheader.Add(gc.headerName);
                    }
                }
                updates.Add(String.Join(",", newupdatesheader.Select(x => x.ToString()).ToArray()));
            }
            else
            {
                updates.Add(String.Join(",", updatesheader.Select(x => x.ToString()).ToArray()));
            }



            var removecols = new[] { "BIM Objects count", "BIM Objects quantity" };

            maxr = Math.Max(maxr, idrow + 2);

            int    n       = table.Rows.Count;
            string s       = "{0} of " + n.ToString() + " rows processed...";
            string caption = "Preparing Data For Glasshouse";

            using (ProgressForm pf = new ProgressForm(caption, s, n))
            {
                foreach (System.Data.DataRow row in table.Rows)
                {
                    string rguid    = (string)row[0];
                    int    foundrow = -1;
                    for (int r = idrow + 2; r <= maxr; r++)
                    {
                        var guid = activeSheet.Cells[r, idcol].Value2;
                        if (guid == null)
                        {
                            continue;
                        }
                        string sguid = guid as string;
                        if (sguid.Length == 0)
                        {
                            continue;
                        }


                        if (rguid.Equals(sguid) == true)
                        {
                            foundrow = r;
                            break;
                        }
                    }

                    int colno     = 0;
                    int activerow = foundrow;
                    if (foundrow == -1)
                    {
                        continue;
                    }

                    List <string> updatescol = new List <string>();

                    if (viewexport == true)
                    {
                        foreach (object col in row.ItemArray)
                        {
                            string colname = table.Columns[colno].ColumnName.ToLower().Trim();
                            colno++;
                            if (removecols.Any(colname.Contains))
                            {
                                continue;
                            }

                            gColumns match = headers.Find(v => v.headerNameLC.Equals(colname));

                            if (match == null)
                            {
                                continue;
                            }
                            if (match.sync2gh == false && match.headerNameLC.Equals("glasshousejournalguid") == false)
                            {
                                continue;
                            }

                            //add to update
                            var    val  = activeSheet.Cells[foundrow, match.colNo].Value2;
                            string sval = "-";
                            if (val != null)
                            {
                                sval = Utils.FormatWithQuotes(val.ToString());
                            }
                            updatescol.Add(sval as string);
                        }
                    }
                    else
                    {
                        foreach (gColumns gc in headers)
                        {
                            if (removecols.Any(gc.headerName.Contains))
                            {
                                continue;
                            }
                            if (gc.sync2gh == false && gc.headerNameLC.Equals("glasshousejournalguid") == false)
                            {
                                continue;
                            }
                            //add to update
                            var    val  = activeSheet.Cells[foundrow, gc.colNo].Value2;
                            string sval = "-";
                            if (val != null)
                            {
                                sval = Utils.FormatWithQuotes(val.ToString());
                            }
                            updatescol.Add(sval as string);
                        }
                    }
                    updates.Add(String.Join(",", updatescol.Select(x => x.ToString()).ToArray()));
                    //updates.Add(updatescol.Aggregate("", (string agg, string it) => agg += string.Format("{0} \"{1}\"", agg == "" ? "" : ",", it)));
                    pf.Increment();
                }
            }
            if (updates.Count < 2)
            {
                System.Windows.Forms.MessageBox.Show("Nothing to update");
                return;
            }

            var    tempdir = System.IO.Path.GetTempPath();
            string path    = Path.Combine(tempdir, System.IO.Path.GetFileNameWithoutExtension(_excel.ActiveWorkbook.Name) + "_updateglasshouse.csv");

            n       = updates.Count;
            s       = "{0} of " + n.ToString() + " rows processed...";
            caption = "Writing Data For Glasshouse";

            using (ProgressForm pf = new ProgressForm(caption, s, n))
            {
                using (var w = new StreamWriter(path, false, Encoding.UTF8))
                {
                    foreach (string us in updates)
                    {
                        w.WriteLine(us);
                        w.Flush();
                    }
                }
            }

            if (csv == false)
            {
                if (UpdateJournalCVS(_curproj, path) == true)
                {
                    System.Windows.Forms.MessageBox.Show("Glashouse updated", "Write To Glasshouse");
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show("Hmmm...something went wrong!", "Write To Glasshouse");
                }
            }
            else
            {
                System.Windows.Forms.MessageBox.Show("CSV dumped at " + path, "Write To CSV File");
            }

            updates       = null;
            updatesheader = null;
            headers       = null;
            table         = null;
        }
Exemplo n.º 40
0
 public void DoAfterEdit(object newValue, System.Windows.Forms.DialogResult result, string editType)
 {
     if (result != System.Windows.Forms.DialogResult.OK)
     {
         m_EditObject = null;
         return;
     }
     if (m_EditObject is System.Windows.Forms.ListViewItem.ListViewSubItem)
     {
         System.Windows.Forms.ListViewItem.ListViewSubItem subItem =
             m_EditObject as System.Windows.Forms.ListViewItem.ListViewSubItem;
         if (subItem.Name.Contains("Range"))//范围编辑
         {
             #region Range
             //更新当前编辑对象(Range)的值
             subItem.Tag  = newValue;
             subItem.Text = subItem.Text.Split('-')[0] + "-" + newValue.ToString();
             //更新对应的Label的值
             string nameIndex = subItem.Name.Replace("Range", "");
             System.Windows.Forms.ListViewItem item = listValueItem.Items[Convert.ToInt32(nameIndex)];
             item.SubItems[2].Text = subItem.Text;
             //更新下一条记录的Range和Label的值
             if (item.Index + 1 < listValueItem.Items.Count)
             {
                 System.Windows.Forms.ListViewItem nextItem = listValueItem.Items[item.Index + 1];
                 nextItem.SubItems[1].Text = newValue.ToString() + "-" + nextItem.SubItems[1].Tag.ToString();
                 nextItem.SubItems[2].Text = newValue.ToString() + "-" + nextItem.SubItems[1].Tag.ToString();
             }
             #endregion
         }
         else if (subItem.Name.Contains("Label"))//标签编辑
         {
             if (newValue.ToString() != "")
             {
                 subItem.Tag  = newValue;
                 subItem.Text = newValue.ToString();
             }
         }
     }
     if (m_EditObject is System.Windows.Forms.ListViewItem)
     {
         System.Windows.Forms.ListViewItem item = m_EditObject as System.Windows.Forms.ListViewItem;
         item.Tag = newValue;
         listValueItem.SmallImageList.Images.RemoveByKey("Symbol" + item.Index.ToString());
         listValueItem.SmallImageList.Images.Add("Symbol" + item.Index.ToString(),
                                                 ModuleCommon.Symbol2Picture(newValue as ISymbol, ModuleCommon.ImageWidth, ModuleCommon.ImageHeight));
         item.ImageKey = "Symbol" + item.Index.ToString();
     }
     if (m_EditObject is DevComponents.DotNetBar.LabelX)
     {
         DevComponents.DotNetBar.LabelX label = m_EditObject as DevComponents.DotNetBar.LabelX;
         switch (label.Name)
         {
         case "labelPreviewFore":
             if (label.Image != null)
             {
                 label.Image.Dispose();
                 label.Image = null;
             }
             label.Tag   = newValue;
             label.Image = ModuleCommon.Symbol2Picture(newValue as ISymbol, ModuleCommon.ImageWidth, ModuleCommon.ImageHeight);
             RefreshSymbol();
             break;
         }
     }
     m_EditObject = null;
 }
Exemplo n.º 41
0
        public async void DeepAnalysisButton_Click(object sender, RoutedEventArgs e)
        {
            bool skipCache = false;

            if (CachedUnturnedFiles?.Count() > 0)
            {
                MessageBoxResult res = MessageBox.Show(LocalizationManager.Current.Interface["DeepAnalysis_Cache_Update"], "", MessageBoxButton.YesNoCancel);
                if (res == MessageBoxResult.Cancel)
                {
                    MainWindow.Instance.blockActionsOverlay.Visibility = Visibility.Collapsed;
                    return;
                }
                if (res == MessageBoxResult.No)
                {
                    skipCache = true;
                }
            }
            if (!skipCache)
            {
                MainWindow.Instance.blockActionsOverlay.Visibility = Visibility.Visible;
                using (System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog()
                {
                    ShowNewFolderButton = false
                })
                {
                    System.Windows.Forms.DialogResult res = fbd.ShowDialog();
                    if (res == System.Windows.Forms.DialogResult.Cancel || !PathUtility.IsUnturnedPath(fbd.SelectedPath))
                    {
                        MainWindow.Instance.blockActionsOverlay.Visibility = Visibility.Collapsed;
                        return;
                    }
                    await CacheFiles(fbd.SelectedPath);
                }
                MainWindow.Instance.blockActionsOverlay.Visibility = Visibility.Collapsed;
            }
            MistakesManager.FindMistakes();
            foreach (NPCDialogue dialogue in MainWindow.CurrentProject.data.dialogues)
            {
                if (CachedUnturnedFiles != null && CachedUnturnedFiles.Any(d => d.Type == UnturnedFile.EAssetType.Dialogue && d.Id == dialogue.id))
                {
                    MainWindow.Instance.lstMistakes.Items.Add(new Mistake()
                    {
                        MistakeDesc = LocalizationManager.Current.Mistakes.Translate("deep_dialogue", dialogue.id),
                        Importance  = IMPORTANCE.WARNING
                    });
                }
                await Task.Yield();
            }
            foreach (NPCVendor vendor in MainWindow.CurrentProject.data.vendors)
            {
                if (CachedUnturnedFiles != null && CachedUnturnedFiles.Any(d => d.Type == UnturnedFile.EAssetType.Vendor && d.Id == vendor.id))
                {
                    MainWindow.Instance.lstMistakes.Items.Add(new Mistake()
                    {
                        MistakeDesc = LocalizationManager.Current.Mistakes.Translate("deep_vendor", vendor.id),
                        Importance  = IMPORTANCE.WARNING
                    });
                }
                foreach (VendorItem it in vendor.items)
                {
                    if (it.type == ItemType.VEHICLE && !CachedUnturnedFiles.Any(d => d.Type == UnturnedFile.EAssetType.Vehicle && d.Id == it.id))
                    {
                        MainWindow.Instance.lstMistakes.Items.Add(new Mistake()
                        {
                            MistakeDesc = LocalizationManager.Current.Mistakes.Translate("deep_vehicle", it.id),
                            Importance  = IMPORTANCE.WARNING
                        });
                        continue;
                    }
                    if (it.type == ItemType.ITEM && !CachedUnturnedFiles.Any(d => d.Type == UnturnedFile.EAssetType.Item && d.Id == it.id))
                    {
                        MainWindow.Instance.lstMistakes.Items.Add(new Mistake()
                        {
                            MistakeDesc = LocalizationManager.Current.Mistakes.Translate("deep_item", it.id),
                            Importance  = IMPORTANCE.WARNING
                        });
                        continue;
                    }
                }
                await Task.Yield();
            }
            foreach (NPCQuest quest in MainWindow.CurrentProject.data.quests)
            {
                if (CachedUnturnedFiles != null && CachedUnturnedFiles.Any(d => d.Type == UnturnedFile.EAssetType.Quest && d.Id == quest.id))
                {
                    MainWindow.Instance.lstMistakes.Items.Add(new Mistake()
                    {
                        MistakeDesc = LocalizationManager.Current.Mistakes.Translate("deep_quest", quest.id),
                        Importance  = IMPORTANCE.WARNING
                    });
                }
                await Task.Yield();
            }
            foreach (NPCCharacter character in MainWindow.CurrentProject.data.characters)
            {
                if (character.id > 0)
                {
                    if (CachedUnturnedFiles != null && CachedUnturnedFiles.Any(d => d.Type == UnturnedFile.EAssetType.NPC && d.Id == character.id))
                    {
                        MainWindow.Instance.lstMistakes.Items.Add(new Mistake()
                        {
                            MistakeDesc = LocalizationManager.Current.Mistakes.Translate("deep_char", character.id),
                            Importance  = IMPORTANCE.WARNING
                        });
                    }
                }
            }
            MainWindow.Instance.blockActionsOverlay.Visibility = Visibility.Collapsed;
            if (MainWindow.Instance.lstMistakes.Items.Count == 0)
            {
                MainWindow.Instance.lstMistakes.Visibility   = Visibility.Collapsed;
                MainWindow.Instance.noErrorsLabel.Visibility = Visibility.Visible;
            }
            else
            {
                MainWindow.Instance.lstMistakes.Visibility   = Visibility.Visible;
                MainWindow.Instance.noErrorsLabel.Visibility = Visibility.Collapsed;
            }
        }
Exemplo n.º 42
0
        private void DeleteRecordButton_Click(object sender, System.EventArgs e)
        {
            if (foodStoreDataGridView.Rows.Count >= 1)
            {
                System.Windows.Forms.DialogResult dialogResult =
                    Mbb.Windows.Forms.MessageBox.Show
                        (text: $"{foodStoreDataGridView.CurrentRow.Cells[0].Value} حذف گردد؟!",
                        caption: "هشدار",
                        icon: Mbb.Windows.Forms.MessageBoxIcon.Warning,
                        button: Mbb.Windows.Forms.MessageBoxButtons.YesNo);

                if (dialogResult == System.Windows.Forms.DialogResult.Yes)                //----جهت حذف مشترک
                {
                    string foodName = foodStoreDataGridView.CurrentRow.Cells[0].Value.ToString();

                    using (Models.DataBaseContext dataBaseContext = new Models.DataBaseContext())
                    {
                        Models.Food food =
                            dataBaseContext.Foods
                            .Where(current => string.Compare(current.FoodName, foodName) == 0)
                            .FirstOrDefault();
                        if (food != null)
                        {
                            var entry = dataBaseContext.Entry(food);

                            if (entry.State == EntityState.Detached)
                            {
                                dataBaseContext.Foods.Attach(food);
                            }
                        }

                        #region EventLog
                        Username   = Program.AuthenticatedUser.Username;
                        FullName   = $"{Program.AuthenticatedUser.First_Name} {Program.AuthenticatedUser.Last_Name}";
                        EventDate  = $"{Infrastructure.Utility.PersianCalendar(System.DateTime.Now)}";
                        EventTime  = $"{Infrastructure.Utility.ShowTime()}";
                        EventTitle = $"{foodName} حذف گردید.";

                        Infrastructure.Utility.EventLog
                            (username: Username,
                            fullName: FullName,
                            eventDate: EventDate,
                            eventTime: EventTime,
                            eventTitle: EventTitle);
                        #endregion /EventLog

                        dataBaseContext.Foods.Remove(food);
                        dataBaseContext.SaveChanges();
                        FoodLoader();
                    }

                    Infrastructure.Utility.WindowsNotification
                        (message: "کد مورد نظر حذف گردید!",
                        caption: Infrastructure.PopupNotificationForm.Caption.موفقیت);
                }
            }
            else
            {
                Mbb.Windows.Forms.MessageBox.Show
                    (text: $"موردی برای حذف وجود ندارد!",
                    caption: "اطلاع",
                    icon: Mbb.Windows.Forms.MessageBoxIcon.Information,
                    button: Mbb.Windows.Forms.MessageBoxButtons.Ok);
                return;
            }
        }
Exemplo n.º 43
0
        public override Object EditValue(ITypeDescriptorContext context, IServiceProvider provider, Object value)
        {
            Debug.Assert(context.Instance is Control, "Expected control");
            Control ctrl = (Control)context.Instance;

            IServiceProvider serviceProvider;
            ISite            site = ctrl.Site;

            if (site == null && ctrl.Page != null)
            {
                site = ctrl.Page.Site;
            }
            if (site != null)
            {
                serviceProvider = site;
            }
            else
            {
                serviceProvider = provider;
            }
            Debug.Assert(serviceProvider != null,
                         "Failed to get the serviceProvider");

            IComponentChangeService changeService =
                (IComponentChangeService)serviceProvider.GetService(typeof(IComponentChangeService));

            IDesignerHost designerHost =
                (IDesignerHost)serviceProvider.GetService(typeof(IDesignerHost));

            Debug.Assert(designerHost != null,
                         "Must always have access to IDesignerHost service");

            IDeviceSpecificDesigner dsDesigner =
                designerHost.GetDesigner(ctrl) as IDeviceSpecificDesigner;

            Debug.Assert(dsDesigner != null,
                         "Expected component designer to implement IDeviceSpecificDesigner");

            IMobileWebFormServices wfServices =
                (IMobileWebFormServices)serviceProvider.GetService(typeof(IMobileWebFormServices));

            DialogResult result = DialogResult.Cancel;

            DesignerTransaction transaction = designerHost.CreateTransaction(_propertyOverridesDescription);

            try
            {
                if (changeService != null)
                {
                    try
                    {
                        changeService.OnComponentChanging(ctrl, null);
                    }
                    catch (CheckoutException ce)
                    {
                        if (ce == CheckoutException.Canceled)
                        {
                            return(value);
                        }
                        throw;
                    }
                }

                try
                {
                    PropertyOverridesDialog dialog = new PropertyOverridesDialog(
                        dsDesigner,
                        MobileControlDesigner.MergingContextProperties
                        );
                    IWindowsFormsEditorService edSvc =
                        (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
                    result = edSvc.ShowDialog(dialog);
                }
                catch (InvalidChoiceException e)
                {
                    Debug.Fail(e.ToString());
                }
                finally
                {
                    if (changeService != null && result != DialogResult.Cancel)
                    {
                        changeService.OnComponentChanged(ctrl, null, null, null);
                    }
                }
            }
            finally
            {
                if (transaction != null)
                {
                    if (result == DialogResult.OK)
                    {
                        transaction.Commit();
                    }
                    else
                    {
                        transaction.Cancel();
                    }
                }
            }

            return(value);
        }
Exemplo n.º 44
0
        private void PlaySound(SaveFile.Sound Item)
        {
            foreach (System.Windows.Forms.TreeNode DeviceNode in this.treeView1.Nodes)
            {
                if (DeviceNode.Checked && DeviceNode.Tag != null && ((SaveFile.Device)DeviceNode.Tag).CurrentDevice != null)
                {
                    try
                    {
                        NAudio.Wave.WaveStream Stream;
                        if (Item.SndFormat == SoundFormat.OGG)
                        {
                            Stream = new NAudio.Vorbis.VorbisWaveReader(Item.FilePath);
                        }
                        else if (Item.SndFormat == SoundFormat.WAV)
                        {
                            Stream = new NAudio.Wave.WaveFileReader(Item.FilePath);
                        }
                        else if (Item.SndFormat == SoundFormat.MP3)
                        {
                            Stream = new NAudio.Wave.Mp3FileReader(Item.FilePath);
                        }
                        else if (Item.SndFormat == SoundFormat.AIFF)
                        {
                            Stream = new NAudio.Wave.AiffFileReader(Item.FilePath);
                        }
                        else
                        {
                            throw new System.NotSupportedException();
                        }

                        if (this.UserData.LoopEnabled)
                        {
                            Stream = new LoopStream(Stream);
                        }

                        NAudio.Wave.WasapiOut PlayAudio = new NAudio.Wave.WasapiOut((NAudio.CoreAudioApi.MMDevice)((SaveFile.Device)DeviceNode.Tag).CurrentDevice, NAudio.CoreAudioApi.AudioClientShareMode.Shared, true, 100);
                        this.CurrentlyPlaying.Add(PlayAudio);
                        {
                            PlayAudio.Init(Stream);
                            PlayAudio.Play();
                        }

                        PlayAudio.PlaybackStopped += this.WaveOut_PlaybackStopped;
                    }
                    catch (System.FormatException Ex)
                    {
                        LucasStuff.Message.Show(Ex.Message, "An error occured while playing", LucasStuff.Message.Buttons.OK, LucasStuff.Message.Icon.Error);
                        return;
                    }
                    catch (System.IO.InvalidDataException Ex)
                    {
                        LucasStuff.Message.Show(Ex.Message, "An error occured while playing", LucasStuff.Message.Buttons.OK, LucasStuff.Message.Icon.Error);
                        return;
                    }
                    catch (System.IO.FileNotFoundException Ex)
                    {
                        System.Windows.Forms.DialogResult Result = LucasStuff.Message.Show(Ex.Message + "\n\nShould this file be removed from your audio listing?", "An error occured while playing", LucasStuff.Message.Buttons.YesNo, LucasStuff.Message.Icon.Error);
                        if (Result == System.Windows.Forms.DialogResult.Yes)
                        {
                            //this.DeleteSounds(); // HACK: fix this before PC 1.0 Update #1
                        }
                        return;
                    }
                }
            }
        }
 private void m_cmdHuyBo_Click(System.Object sender, System.EventArgs e)
 {
     m_MsgResult = System.Windows.Forms.DialogResult.Cancel;
     DongForm();
 }
        private async void ButtonExport_OnClick(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog SaveDialog = new System.Windows.Forms.SaveFileDialog
            {
                Filter = "STAR Files|*.star"
            };
            System.Windows.Forms.DialogResult ResultSave = SaveDialog.ShowDialog();

            if (ResultSave.ToString() == "OK")
            {
                ExportPath = SaveDialog.FileName;
            }
            else
            {
                return;
            }

            bool DoAverage        = (bool)RadioAverage.IsChecked;
            bool DoStack          = (bool)RadioStack.IsChecked;
            bool DoDenoisingPairs = (bool)RadioDenoising.IsChecked;
            bool DoOnlyStar       = (bool)RadioStar.IsChecked;

            bool Invert    = (bool)CheckInvert.IsChecked;
            bool Normalize = (bool)CheckNormalize.IsChecked;
            bool Preflip   = (bool)CheckPreflip.IsChecked;

            float AngPix = (float)Options.Tasks.InputPixelSize;

            bool Relative = (bool)CheckRelative.IsChecked;

            bool Filter = (bool)CheckFilter.IsChecked;
            bool Manual = (bool)CheckManual.IsChecked;

            int BoxSize      = (int)Options.Tasks.Export2DBoxSize;
            int NormDiameter = (int)Options.Tasks.Export2DParticleDiameter;

            ProgressWrite.Visibility      = Visibility.Visible;
            ProgressWrite.IsIndeterminate = true;
            PanelButtons.Visibility       = Visibility.Collapsed;
            PanelRemaining.Visibility     = Visibility.Visible;

            foreach (var element in DisableWhileProcessing)
            {
                element.IsEnabled = false;
            }

            await Task.Run(async() =>
            {
                #region Get all movies that can potentially be used

                List <Movie> ValidMovies = Movies.Where(v =>
                {
                    if (!Filter && v.UnselectFilter && v.UnselectManual == null)
                    {
                        return(false);
                    }
                    if (!Manual && v.UnselectManual != null && (bool)v.UnselectManual)
                    {
                        return(false);
                    }
                    if (v.OptionsCTF == null)
                    {
                        return(false);
                    }
                    return(true);
                }).ToList();
                List <string> ValidMovieNames = ValidMovies.Select(m => m.RootName).ToList();

                if (ValidMovies.Count == 0)
                {
                    await Dispatcher.Invoke(async() =>
                    {
                        await((MainWindow)Application.Current.MainWindow).ShowMessageAsync("Oopsie",
                                                                                           "No items were found to extract particles from.\n" +
                                                                                           "Please make sure the names match, estimate the CTF for all items, and review your filtering thresholds.");
                    });
                }

                #endregion

                #region Read table and intersect its micrograph set with valid movies

                Star TableIn;

                if (Options.Tasks.InputOnePerItem)
                {
                    List <Star> Tables = new List <Star>();
                    foreach (var item in Movies)
                    {
                        string StarPath = InputFolder + item.RootName + InputSuffix + ".star";
                        if (File.Exists(StarPath))
                        {
                            Star TableItem = new Star(StarPath);
                            if (!TableItem.HasColumn("rlnMicrographName"))
                            {
                                TableItem.AddColumn("rlnMicrographName", item.Name);
                            }

                            if (item.PickingThresholds.ContainsKey(InputSuffix) && TableItem.HasColumn("rlnAutopickFigureOfMerit"))
                            {
                                float Threshold   = (float)item.PickingThresholds[InputSuffix];
                                float[] Scores    = TableItem.GetColumn("rlnAutopickFigureOfMerit").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                                int[] InvalidRows = Helper.ArrayOfSequence(0, TableItem.RowCount, 1).Where(i => Scores[i] < Threshold).ToArray();
                                TableItem.RemoveRows(InvalidRows);
                            }

                            Tables.Add(TableItem);
                        }
                    }

                    TableIn = new Star(Tables.ToArray());
                }
                else
                {
                    TableIn = new Star(ImportPath);
                }

                if (!TableIn.HasColumn("rlnMicrographName"))
                {
                    throw new Exception("Couldn't find rlnMicrographName column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateX"))
                {
                    throw new Exception("Couldn't find rlnCoordinateX column.");
                }
                if (!TableIn.HasColumn("rlnCoordinateY"))
                {
                    throw new Exception("Couldn't find rlnCoordinateY column.");
                }

                Dictionary <string, List <int> > Groups = new Dictionary <string, List <int> >();
                {
                    string[] ColumnMicNames = TableIn.GetColumn("rlnMicrographName");
                    for (int r = 0; r < ColumnMicNames.Length; r++)
                    {
                        if (!Groups.ContainsKey(ColumnMicNames[r]))
                        {
                            Groups.Add(ColumnMicNames[r], new List <int>());
                        }
                        Groups[ColumnMicNames[r]].Add(r);
                    }
                    Groups = Groups.ToDictionary(group => Helper.PathToName(group.Key), group => group.Value);

                    Groups = Groups.Where(group => ValidMovieNames.Contains(group.Key)).ToDictionary(group => group.Key, group => group.Value);
                }

                bool[] RowsIncluded = new bool[TableIn.RowCount];
                foreach (var group in Groups)
                {
                    foreach (var r in group.Value)
                    {
                        RowsIncluded[r] = true;
                    }
                }
                List <int> RowsNotIncluded = new List <int>();
                for (int r = 0; r < RowsIncluded.Length; r++)
                {
                    if (!RowsIncluded[r])
                    {
                        RowsNotIncluded.Add(r);
                    }
                }

                ValidMovies = ValidMovies.Where(v => Groups.ContainsKey(v.RootName)).ToList();

                if (ValidMovies.Count == 0)     // Exit if there is nothing to export, otherwise errors will be thrown below
                {
                    return;
                }

                #endregion

                #region Make sure all columns are there

                if (!TableIn.HasColumn("rlnMagnification"))
                {
                    TableIn.AddColumn("rlnMagnification", "10000.0");
                }
                else
                {
                    TableIn.SetColumn("rlnMagnification", Helper.ArrayOfConstant("10000.0", TableIn.RowCount));
                }

                if (!TableIn.HasColumn("rlnDetectorPixelSize"))
                {
                    TableIn.AddColumn("rlnDetectorPixelSize", Options.GetProcessingParticleExport().BinnedPixelSizeMean.ToString("F5", CultureInfo.InvariantCulture));
                }
                else
                {
                    TableIn.SetColumn("rlnDetectorPixelSize", Helper.ArrayOfConstant(Options.GetProcessingParticleExport().BinnedPixelSizeMean.ToString("F5", CultureInfo.InvariantCulture), TableIn.RowCount));
                }

                if (!TableIn.HasColumn("rlnVoltage"))
                {
                    TableIn.AddColumn("rlnVoltage", "300.0");
                }

                if (!TableIn.HasColumn("rlnSphericalAberration"))
                {
                    TableIn.AddColumn("rlnSphericalAberration", "2.7");
                }

                if (!TableIn.HasColumn("rlnAmplitudeContrast"))
                {
                    TableIn.AddColumn("rlnAmplitudeContrast", "0.07");
                }

                if (!TableIn.HasColumn("rlnPhaseShift"))
                {
                    TableIn.AddColumn("rlnPhaseShift", "0.0");
                }

                if (!TableIn.HasColumn("rlnDefocusU"))
                {
                    TableIn.AddColumn("rlnDefocusU", "0.0");
                }

                if (!TableIn.HasColumn("rlnDefocusV"))
                {
                    TableIn.AddColumn("rlnDefocusV", "0.0");
                }

                if (!TableIn.HasColumn("rlnDefocusAngle"))
                {
                    TableIn.AddColumn("rlnDefocusAngle", "0.0");
                }

                if (!TableIn.HasColumn("rlnCtfMaxResolution"))
                {
                    TableIn.AddColumn("rlnCtfMaxResolution", "999.0");
                }

                if (!TableIn.HasColumn("rlnImageName"))
                {
                    TableIn.AddColumn("rlnImageName", "None");
                }

                if (!TableIn.HasColumn("rlnMicrographName"))
                {
                    TableIn.AddColumn("rlnMicrographName", "None");
                }

                #endregion

                int NDevices                   = GPU.GetDeviceCount();
                List <int> UsedDevices         = Options.MainWindow.GetDeviceList();
                List <int> UsedDeviceProcesses = Helper.Combine(Helper.ArrayOfFunction(i => UsedDevices.Select(d => d + i *NDevices).ToArray(), MainWindow.GlobalOptions.ProcessesPerDevice)).ToList();

                if (IsCanceled)
                {
                    return;
                }

                #region Create worker processes

                WorkerWrapper[] Workers = new WorkerWrapper[GPU.GetDeviceCount() * MainWindow.GlobalOptions.ProcessesPerDevice];
                foreach (var gpuID in UsedDeviceProcesses)
                {
                    Workers[gpuID] = new WorkerWrapper(gpuID);
                    Workers[gpuID].SetHeaderlessParams(new int2(Options.Import.HeaderlessWidth, Options.Import.HeaderlessHeight),
                                                       Options.Import.HeaderlessOffset,
                                                       Options.Import.HeaderlessType);

                    if (!string.IsNullOrEmpty(Options.Import.GainPath) && Options.Import.CorrectGain)
                    {
                        Workers[gpuID].LoadGainRef(Options.Import.CorrectGain ? Options.Import.GainPath : "",
                                                   Options.Import.GainFlipX,
                                                   Options.Import.GainFlipY,
                                                   Options.Import.GainTranspose,
                                                   Options.Import.CorrectDefects ? Options.Import.DefectsPath : "");
                    }
                }

                #endregion

                #region Load gain reference if needed

                //Image[] ImageGain = new Image[NDevices];
                //if (!string.IsNullOrEmpty(Options.Import.GainPath) && Options.Import.CorrectGain && File.Exists(Options.Import.GainPath))
                //    for (int d = 0; d < NDevices; d++)
                //    {
                //        GPU.SetDevice(d);
                //        ImageGain[d] = MainWindow.LoadAndPrepareGainReference();
                //    }

                #endregion

                bool Overwrite = true;
                if (DoAverage || DoStack)
                {
                    foreach (var movie in ValidMovies)
                    {
                        bool FileExists = File.Exists((DoAverage ? movie.ParticlesDir : movie.ParticleMoviesDir) + movie.RootName + Options.Tasks.OutputSuffix + ".mrcs");
                        if (FileExists)
                        {
                            await Dispatcher.Invoke(async() =>
                            {
                                var DialogResult = await((MainWindow)Application.Current.MainWindow).ShowMessageAsync("Some particle files already exist. Overwrite them?",
                                                                                                                      "",
                                                                                                                      MessageDialogStyle.AffirmativeAndNegative,
                                                                                                                      new MetroDialogSettings()
                                {
                                    AffirmativeButtonText = "Yes",
                                    NegativeButtonText    = "No"
                                });
                                if (DialogResult == MessageDialogResult.Negative)
                                {
                                    Overwrite = false;
                                }
                            });
                            break;
                        }
                    }
                }

                Star TableOut = null;
                {
                    Dictionary <string, Star> MicrographTables = new Dictionary <string, Star>();

                    #region Get coordinates

                    float[] PosX   = TableIn.GetColumn("rlnCoordinateX").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] PosY   = TableIn.GetColumn("rlnCoordinateY").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray();
                    float[] ShiftX = TableIn.HasColumn("rlnOriginX") ? TableIn.GetColumn("rlnOriginX").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    float[] ShiftY = TableIn.HasColumn("rlnOriginY") ? TableIn.GetColumn("rlnOriginY").Select(v => float.Parse(v, CultureInfo.InvariantCulture)).ToArray() : new float[TableIn.RowCount];
                    for (int r = 0; r < TableIn.RowCount; r++)
                    {
                        PosX[r] -= ShiftX[r];
                        PosY[r] -= ShiftY[r];
                    }

                    if (TableIn.HasColumn("rlnOriginX"))
                    {
                        TableIn.RemoveColumn("rlnOriginX");
                    }
                    if (TableIn.HasColumn("rlnOriginY"))
                    {
                        TableIn.RemoveColumn("rlnOriginY");
                    }

                    #endregion

                    Dispatcher.Invoke(() => ProgressWrite.MaxValue = ValidMovies.Count);

                    Helper.ForEachGPU(ValidMovies, (movie, gpuID) =>
                    {
                        if (IsCanceled)
                        {
                            return;
                        }

                        Stopwatch ItemTime = new Stopwatch();
                        ItemTime.Start();

                        MapHeader OriginalHeader = MapHeader.ReadFromFile(movie.Path);

                        #region Set up export options

                        ProcessingOptionsParticlesExport ExportOptions = Options.GetProcessingParticleExport();
                        ExportOptions.DoAverage        = DoAverage;
                        ExportOptions.DoDenoisingPairs = DoDenoisingPairs;
                        ExportOptions.DoStack          = DoStack;
                        ExportOptions.Invert           = Invert;
                        ExportOptions.Normalize        = Normalize;
                        ExportOptions.PreflipPhases    = Preflip;
                        ExportOptions.Dimensions       = OriginalHeader.Dimensions.MultXY((float)Options.PixelSizeMean);
                        ExportOptions.BoxSize          = BoxSize;
                        ExportOptions.Diameter         = NormDiameter;

                        #endregion

                        bool FileExists = File.Exists((DoAverage ? movie.ParticlesDir : movie.ParticleMoviesDir) + movie.RootName + ExportOptions.Suffix + ".mrcs");

                        #region Load and prepare original movie

                        //Image OriginalStack = null;
                        decimal ScaleFactor = 1M / (decimal)Math.Pow(2, (double)ExportOptions.BinTimes);

                        if (!DoOnlyStar && (!FileExists || Overwrite))
                        {
                            Workers[gpuID].LoadStack(movie.Path, ScaleFactor, ExportOptions.EERGroupFrames);
                        }
                        //MainWindow.LoadAndPrepareHeaderAndMap(movie.Path, ImageGain[gpuID], ScaleFactor, out OriginalHeader, out OriginalStack);

                        if (IsCanceled)
                        {
                            //foreach (Image gain in ImageGain)
                            //    gain?.Dispose();
                            //OriginalStack?.Dispose();

                            return;
                        }

                        #endregion

                        #region Figure out relative or absolute path to particle stack

                        string PathStack      = (ExportOptions.DoStack ? movie.ParticleMoviesDir : movie.ParticlesDir) + movie.RootName + ExportOptions.Suffix + ".mrcs";
                        string PathMicrograph = movie.Path;
                        if (Relative)
                        {
                            Uri UriStar    = new Uri(ExportPath);
                            PathStack      = UriStar.MakeRelativeUri(new Uri(PathStack)).ToString();
                            PathMicrograph = UriStar.MakeRelativeUri(new Uri(PathMicrograph)).ToString();
                        }

                        #endregion

                        #region Update row values

                        List <int> GroupRows    = Groups[movie.RootName];
                        List <float2> Positions = new List <float2>();

                        float Astigmatism  = (float)movie.CTF.DefocusDelta / 2;
                        float PhaseShift   = movie.OptionsCTF.DoPhase ? movie.GridCTFPhase.GetInterpolated(new float3(0.5f)) * 180 : 0;
                        int ImageNameIndex = TableIn.GetColumnID("rlnImageName");

                        foreach (var r in GroupRows)
                        {
                            float3 Position = new float3(PosX[r] * AngPix / ExportOptions.Dimensions.X,
                                                         PosY[r] * AngPix / ExportOptions.Dimensions.Y,
                                                         0.5f);
                            float LocalDefocus = movie.GridCTFDefocus.GetInterpolated(Position);

                            TableIn.SetRowValue(r, "rlnDefocusU", ((LocalDefocus + Astigmatism) * 1e4f).ToString("F1", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnDefocusV", ((LocalDefocus - Astigmatism) * 1e4f).ToString("F1", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnDefocusAngle", movie.CTF.DefocusAngle.ToString("F1", CultureInfo.InvariantCulture));

                            TableIn.SetRowValue(r, "rlnVoltage", movie.CTF.Voltage.ToString("F1", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnSphericalAberration", movie.CTF.Cs.ToString("F4", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnAmplitudeContrast", movie.CTF.Amplitude.ToString("F3", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnPhaseShift", PhaseShift.ToString("F1", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnCtfMaxResolution", movie.CTFResolutionEstimate.ToString("F1", CultureInfo.InvariantCulture));

                            TableIn.SetRowValue(r, "rlnCoordinateX", (PosX[r] * AngPix / (float)ExportOptions.BinnedPixelSizeMean).ToString("F2", CultureInfo.InvariantCulture));
                            TableIn.SetRowValue(r, "rlnCoordinateY", (PosY[r] * AngPix / (float)ExportOptions.BinnedPixelSizeMean).ToString("F2", CultureInfo.InvariantCulture));

                            TableIn.SetRowValue(r, "rlnImageName", PathStack);

                            TableIn.SetRowValue(r, "rlnMicrographName", PathMicrograph);

                            Positions.Add(new float2(PosX[r] * AngPix,
                                                     PosY[r] * AngPix));
                        }

                        #endregion

                        #region Populate micrograph table with rows for all exported particles

                        Star MicrographTable = new Star(TableIn.GetColumnNames());

                        int StackDepth = (ExportOptions.DoAverage || ExportOptions.DoDenoisingPairs || DoOnlyStar)
                                             ? 1
                                             : (OriginalHeader.Dimensions.Z - ExportOptions.SkipFirstN - ExportOptions.SkipLastN) /
                                         ExportOptions.StackGroupSize;

                        int pi = 0;
                        for (int i = 0; i < StackDepth; i++)
                        {
                            foreach (var r in GroupRows)
                            {
                                List <string> Row   = TableIn.GetRow(r).ToList();
                                Row[ImageNameIndex] = (++pi).ToString("D7") + "@" + Row[ImageNameIndex];
                                MicrographTable.AddRow(Row);
                            }
                        }

                        #endregion

                        #region Finally, process and export the actual particles

                        if (!DoOnlyStar && (!FileExists || Overwrite))
                        {
                            Workers[gpuID].MovieExportParticles(movie.Path, ExportOptions, Positions.ToArray());
                            //movie.ExportParticles(OriginalStack, Positions.ToArray(), ExportOptions);
                            //OriginalStack.Dispose();
                        }

                        #endregion

                        #region Add this micrograph's table to global collection, update remaining time estimate

                        lock (MicrographTables)
                        {
                            MicrographTables.Add(movie.RootName, MicrographTable);

                            Timings.Add(ItemTime.ElapsedMilliseconds / (float)NDevices);

                            int MsRemaining        = (int)(MathHelper.Mean(Timings) * (ValidMovies.Count - MicrographTables.Count));
                            TimeSpan SpanRemaining = new TimeSpan(0, 0, 0, 0, MsRemaining);

                            Dispatcher.Invoke(() => TextRemaining.Text = SpanRemaining.ToString((int)SpanRemaining.TotalHours > 0 ? @"hh\:mm\:ss" : @"mm\:ss"));

                            Dispatcher.Invoke(() =>
                            {
                                ProgressWrite.IsIndeterminate = false;
                                ProgressWrite.Value           = MicrographTables.Count;
                            });
                        }

                        #endregion
                    }, 1, UsedDeviceProcesses);

                    if (MicrographTables.Count > 0)
                    {
                        TableOut = new Star(MicrographTables.Values.ToArray());
                    }
                }

                Thread.Sleep(10000);    // Writing out particle stacks is async, so if workers are killed immediately they may not write out everything

                foreach (var worker in Workers)
                {
                    worker?.Dispose();
                }

                //foreach (Image gain in ImageGain)
                //    gain?.Dispose();

                if (IsCanceled)
                {
                    return;
                }

                TableOut.Save(ExportPath);
            });

            DataContext = null;
            Close?.Invoke();
        }
Exemplo n.º 47
0
 private void btn_compare_with_td_Click(object sender, RoutedEventArgs e)
 {
     MessageBox.Show("Please select a top-down results file.");
     System.Windows.Forms.OpenFileDialog openFileDialog = new System.Windows.Forms.OpenFileDialog();
     openFileDialog.Title       = "Top-Down Results";
     openFileDialog.Filter      = "Excel Files (*.xlsx) | *.xlsx";
     openFileDialog.Multiselect = false;
     System.Windows.Forms.DialogResult dr = openFileDialog.ShowDialog();
     if (dr == System.Windows.Forms.DialogResult.OK)
     {
         MessageBox.Show("Save comparison results file.");
         System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
         saveFileDialog.Title  = "Top-Down Comparison Results";
         saveFileDialog.Filter = "Text Files (*.tsv) | *.tsv";
         System.Windows.Forms.DialogResult sdr = saveFileDialog.ShowDialog();
         if (sdr == System.Windows.Forms.DialogResult.OK)
         {
             InputFile                     file           = new InputFile(openFileDialog.FileName, Purpose.TopDown);
             TopDownReader                 reader         = new TopDownReader();
             List <TopDownHit>             hits           = reader.ReadTDFile(file);
             List <TopDownProteoform>      td_proteoforms = Sweet.lollipop.aggregate_td_hits(hits, 0, true, true);
             List <ExperimentalProteoform> experimentals  = Sweet.lollipop.target_proteoform_community.experimental_proteoforms.Where(p => p.linked_proteoform_references != null && (Sweet.lollipop.count_adducts_as_identifications || !p.adduct) && !p.topdown_id).ToList();
             experimentals = Sweet.lollipop.add_topdown_proteoforms(experimentals, td_proteoforms);
             using (var writer = new System.IO.StreamWriter(saveFileDialog.FileName))
             {
                 writer.WriteLine("Experimental Accession\tExperimental Mass\tExperimental Retention Time\tTheoretical Accession\tTheoretical Description\tTheoretical Begin\tTheoretical End\tTheoretical PTM Description\tTop-Down Accession\tTop-Down Begin\tTop-Down End\tTop-Down PTM Description\tTop-Down Observed Mass\tTop-Down Retention Time\tTop Top-Down C-Score");
                 foreach (ExperimentalProteoform ep in experimentals)
                 {
                     if (ep.topdown_id)
                     {
                         TopDownProteoform tdp = ep as TopDownProteoform;
                         if (tdp.matching_experimental != null)
                         {
                             ExperimentalProteoform exp = tdp.matching_experimental;
                             string exp_ptm             = exp.ptm_set.ptm_combination.Count == 0 ? "Unmodified" : String.Join(", ", exp.ptm_set.ptm_combination.Select(ptm => Sweet.lollipop.theoretical_database.unlocalized_lookup.TryGetValue(ptm.modification, out UnlocalizedModification x) ? x.id : ptm.modification.OriginalId).OrderBy(p => p));
                             string td_ptm = tdp.topdown_ptm_set.ptm_combination.Count == 0 ? "Unmodified" : String.Join(", ", tdp.topdown_ptm_set.ptm_combination.Select(ptm => Sweet.lollipop.theoretical_database.unlocalized_lookup.TryGetValue(ptm.modification, out UnlocalizedModification x) ? x.id : ptm.modification.OriginalId).OrderBy(p => p));
                             writer.WriteLine(exp.accession + "\t" + exp.agg_mass + "\t" + exp.agg_rt + "\t" + exp.linked_proteoform_references.First().accession.Split('_')[0] + "\t" + (exp.linked_proteoform_references.First() as TheoreticalProteoform).description + "\t" + exp.begin + "\t" + exp.end + "\t" + exp_ptm
                                              + "\t" + tdp.accession.Split('_')[0] + "\t" + tdp.topdown_begin + "\t" + tdp.topdown_end + "\t" + td_ptm + "\t" + tdp.modified_mass + "\t" + tdp.agg_rt + "\t" + tdp.topdown_hits.Max(h => h.score));
                         }
                     }
                     else
                     {
                         string exp_ptm          = ep.ptm_set.ptm_combination.Count == 0 ? "Unmodified" : String.Join(", ", ep.ptm_set.ptm_combination.Select(ptm => Sweet.lollipop.theoretical_database.unlocalized_lookup.TryGetValue(ptm.modification, out UnlocalizedModification x) ? x.id : ptm.modification.OriginalId).OrderBy(p => p));
                         TheoreticalProteoform t = ep.linked_proteoform_references.First() as TheoreticalProteoform;
                         writer.WriteLine(ep.accession + "\t" + ep.agg_mass + "\t" + ep.agg_rt + "\t" + t.accession.Split('_')[0] + "\t" + t.description + "\t" + t.begin + "\t" + t.end + "\t" + exp_ptm
                                          + "\t" + "N\\A" + "\t" + "N\\A" + "\t" + "N\\A" + "\t" + "N\\A" + "\t" + "N\\A" + "\t" + "N\\A" + "\t" + "N\\A");
                     }
                 }
             }
             MessageBox.Show("Successfully saved top-down comparison results.");
         }
         else
         {
             return;
         }
     }
     else
     {
         return;
     }
 }
Exemplo n.º 48
0
        public bool SwapNewROMData(byte[] newROMData, string name, Undo.UndoData undodata)
        {
            //0x0が壊されていないかチェックする
            byte[] romheader = Program.ROM.getBinaryData(0, 0x100);
            if (U.memcmp(U.subrange(newROMData, 0, 0x100), romheader) != 0)
            {
                System.Windows.Forms.DialogResult dr = R.ShowYesNo("event_assemblerが、0x0 - 0x100 の領域を書き換えました。\r\nこの領域への書き込みは危険です。\r\nこの内容を本当に適応してもよろしいですか?\r\n\r\n「はい」ならば適応します。\r\nそれ以外ならば変更を破棄します。");
                if (dr != System.Windows.Forms.DialogResult.Yes)
                {
                    return(false);
                }
            }

            //データが大きくなるので差分だけundoバッファに登録する
            const int RecoverMissMatch = 10;
            int       checkpoint;
            int       length = Math.Min(this.Data.Length, newROMData.Length);

            for (int i = 0; i < length; i++)
            {
                if (this.Data[i] == newROMData[i])
                {
                    continue;
                }

                checkpoint = i;

                i++;
                int missCount = 0;
                for (; i < length; i++)
                {
                    if (this.Data[i] != newROMData[i])
                    {
                        missCount = 0;
                        continue;
                    }

                    if (missCount >= RecoverMissMatch)
                    {
                        i -= missCount;
                        break;
                    }

                    missCount++;
                }

                uint size = (uint)(i - checkpoint);

                //checkpoint ~ i の間を相違点として記録.
                undodata.list.Add(new Undo.UndoPostion((uint)checkpoint, size));
                //この範囲にコメントがある場合は再定義するので消す
                Program.CommentCache.RemoveRange((uint)checkpoint, (uint)checkpoint + size);
            }

            if (newROMData.Length != this.Data.Length)
            {//長さが増える場合、ROMを増設する.
                bool isResizeSuccess = this.write_resize_data((uint)newROMData.Length);
                if (isResizeSuccess == false)
                {
                    return(false);
                }
            }
            this.write_range(0, newROMData);

            return(true);
        }
        /// <summary>
        /// Launch third party utilities.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Launch_Third(object sender, RoutedEventArgs e)
        {
            try
            {
                string target       = "";
                string downloadlink = "";
                string installexe   = "";

                switch (((Button)sender).Name)
                {
                case "Launch_WDP":
                    target       = "\\WeaponDeliveryPlanner.exe";
                    downloadlink = "http://www.weapondeliveryplanner.nl/";
                    installexe   = Properties.Settings.Default.Third_WDP + target;
                    if (File.Exists(installexe) == false)
                    {
                        System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();

                        fbd.Description         = "Select Install Directory";
                        fbd.RootFolder          = Environment.SpecialFolder.MyComputer;
                        fbd.ShowNewFolderButton = false;
                        System.Windows.Forms.DialogResult dirResult = fbd.ShowDialog();

                        installexe = fbd.SelectedPath + target;
                        if (File.Exists(installexe))
                        {
                            Properties.Settings.Default.Third_WDP = fbd.SelectedPath;
                        }
                        else
                        {
                            System.Diagnostics.Process.Start(downloadlink);
                            return;
                        }
                    }
                    System.Diagnostics.Process.Start(installexe);
                    break;

                case "Launch_MC":
                    target       = "\\Mission Commander.exe";
                    downloadlink = "http://www.weapondeliveryplanner.nl/";
                    installexe   = Properties.Settings.Default.Third_MC + target;
                    if (File.Exists(installexe) == false)
                    {
                        System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();

                        fbd.Description         = "Select Install Directory";
                        fbd.RootFolder          = Environment.SpecialFolder.MyComputer;
                        fbd.ShowNewFolderButton = false;
                        System.Windows.Forms.DialogResult dirResult = fbd.ShowDialog();

                        installexe = fbd.SelectedPath + target;
                        if (File.Exists(installexe))
                        {
                            Properties.Settings.Default.Third_MC = fbd.SelectedPath;
                        }
                        else
                        {
                            System.Diagnostics.Process.Start(downloadlink);
                            return;
                        }
                    }
                    System.Diagnostics.Process.Start(installexe);
                    break;

                case "Launch_WC":
                    target       = "\\Weather Commander.exe";
                    downloadlink = "http://www.weapondeliveryplanner.nl/";
                    installexe   = Properties.Settings.Default.Third_WC + target;
                    if (File.Exists(installexe) == false)
                    {
                        System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();

                        fbd.Description         = "Select Install Directory";
                        fbd.RootFolder          = Environment.SpecialFolder.MyComputer;
                        fbd.ShowNewFolderButton = false;
                        System.Windows.Forms.DialogResult dirResult = fbd.ShowDialog();

                        installexe = fbd.SelectedPath + target;
                        if (File.Exists(installexe))
                        {
                            Properties.Settings.Default.Third_WC = fbd.SelectedPath;
                        }
                        else
                        {
                            System.Diagnostics.Process.Start(downloadlink);
                            return;
                        }
                    }
                    System.Diagnostics.Process.Start(installexe);
                    break;

                case "Launch_F4WX":
                    target       = "\\F4Wx.exe";
                    downloadlink = "https://www.benchmarksims.org/forum/showthread.php?29203";
                    installexe   = Properties.Settings.Default.Third_F4WX + target;
                    if (File.Exists(installexe) == false)
                    {
                        System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog
                        {
                            Description         = "Select Install Directory",
                            RootFolder          = Environment.SpecialFolder.MyComputer,
                            ShowNewFolderButton = false
                        };

                        System.Windows.Forms.DialogResult dirResult = fbd.ShowDialog();

                        installexe = fbd.SelectedPath + target;
                        if (File.Exists(installexe))
                        {
                            Properties.Settings.Default.Third_F4WX = fbd.SelectedPath;
                        }
                        else
                        {
                            System.Diagnostics.Process.Start(downloadlink);
                            return;
                        }
                    }
                    System.Diagnostics.Process.Start(installexe);
                    break;
                }
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine(ex.Message);

                StreamWriter sw = new StreamWriter(appReg.GetInstallDir() + "\\Error.txt", false, System.Text.Encoding.GetEncoding("shift_jis"));
                sw.Write(ex.Message);
                sw.Close();

                MessageBox.Show("Error Log Saved To " + appReg.GetInstallDir() + "\\Error.txt", "WARNING", MessageBoxButton.OK, MessageBoxImage.Information);

                Close();
            }
        }
Exemplo n.º 50
0
        public bool DataValidation()
        {
            ErrorMessage = string.Empty;

            if (firstNameTextEdit.Text == string.Empty && lastNameTextEdit.Text == string.Empty)
            {
                ErrorMessage = "نام و نام خانوادگی، هردو نمی توانند خالی باشند";
            }

            if (mobileTextEdit.Text == string.Empty &&
                phoneNumberTextEdit.Text == string.Empty &&
                addressRichText.Text == string.Empty)
            {
                ErrorMessage += System.Environment.NewLine +
                                "حداقل یکی از سه فیلد شماره ثابت، شماره تلفن و آدرس باید پر شود";
            }

            if (mobileTextEdit.Text.Length != 11)
            {
                if (mobileTextEdit.Text.Length != 0 && phoneNumberTextEdit.Text == string.Empty)
                {
                    ErrorMessage += System.Environment.NewLine +
                                    "شماره موبایل باید 11 رقم باشد";
                }
            }

            if (phoneNumberTextEdit.Text.Length != 11)
            {
                if (phoneNumberTextEdit.Text.Length != 0 && mobileTextEdit.Text == string.Empty)
                {
                    ErrorMessage += System.Environment.NewLine +
                                    "شماره ثابت باید 11 رقم باشد";
                }
            }
            if (phoneNumberTextEdit.Text != string.Empty && mobileTextEdit.Text != string.Empty)
            {
                if (phoneNumberTextEdit.Text.Length != 0 && mobileTextEdit.Text.Length != 11)
                {
                    ErrorMessage += System.Environment.NewLine +
                                    "شماره ثابت باید 11 رقم باشد";
                }
                if (mobileTextEdit.Text.Length != 0 && phoneNumberTextEdit.Text.Length != 11)
                {
                    ErrorMessage += System.Environment.NewLine +
                                    "شماره موبایل باید 11 رقم باشد";
                }
            }
            if (ErrorMessage != string.Empty)
            {
                System.Windows.Forms.DialogResult dialogResult =
                    DevExpress.XtraEditors.XtraMessageBox.Show(ErrorMessage,
                                                               caption: "اخطار",
                                                               buttons: System.Windows.Forms.MessageBoxButtons.OK,
                                                               icon: System.Windows.Forms.MessageBoxIcon.Warning
                                                               );

                return(false);
            }
            else
            {
                return(true);
            }
        }
            protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
            {
                switch (e.KeyCode)
                {
                    case System.Windows.Forms.Keys.D:
                        if (e.Alt)
                        {
                            m_MsgResult = System.Windows.Forms.DialogResult.Yes;
                            DongForm();
                        }
                        break;
                    case System.Windows.Forms.Keys.K:
                        if (e.Alt)
                        {
                            m_MsgResult = System.Windows.Forms.DialogResult.No;
                            DongForm();
                        }
                        break;

                }
            }