private void btnTim_Click(object sender, EventArgs e)
        {
            int       tieuchi = cbTieuChi.SelectedIndex;
            DataTable table;

            DataView view = dgrdDSNVTrgPhg.DataSource as DataView;

            if (view != null)
            {
                table = view.Table;
            }
            else
            {
                table = dgrdDSNVTrgPhg.DataSource as DataTable;
            }
            if (table == null || table.Rows.Count == 0)
            {
                return;
            }

            if (tieuchi == 0)               // tìm theo mã cc
            {
                string manv = tbSearch.Text;
                if (string.IsNullOrWhiteSpace(manv))
                {
                    return;
                }
                else
                {
                    DataView newview = new DataView(table, "UserFullCode like '%" + manv + "%'", "UserFullCode asc", DataViewRowState.CurrentRows);

                    if (newview.Count == 0)
                    {
                        AutoClosingMessageBox.Show("Không tìm được nhân viên này.", "Thông báo", 2000);
                        return;
                    }
                    else
                    {
                        dgrdDSNVTrgPhg.DataSource = newview;
                    }
                }
            }
            else               // tìm theo tên nv
            {
                string tennv = tbSearch.Text;
                if (string.IsNullOrWhiteSpace(tennv))
                {
                    return;
                }
                else
                {
                    DataView newview = new DataView(table, "UserFullName like '%" + tennv + "%'", "UserEnrollNumber asc", DataViewRowState.CurrentRows);

                    if (newview.Count == 0)
                    {
                        AutoClosingMessageBox.Show("Không tìm được nhân viên này.", "Thông báo", 2000);
                        return;
                    }
                    else
                    {
                        dgrdDSNVTrgPhg.DataSource = newview;
                    }
                }
            }
        }
Ejemplo n.º 2
0
        private void btnXacNhan_Click(object sender, EventArgs e)
        {
            if (SqlDataAccessHelper.TestConnection(SqlDataAccessHelper.ConnectionString) == false)
            {
                AutoClosingMessageBox.Show("Mất kết nối với CSDL. Vui lòng thử lại sau.", "Lỗi", 2000);
                return;
            }

            var loai = 0;
            var temp = string.Empty;

            if (radKhongPC50.Checked)
            {
                loai = -1;
            }
            else if (radPC50.Checked)
            {
                loai = 1;
            }

            #region hỏi lại trước khi thực hiện

            if (loai == -1)
            {
                if (
                    MessageBox.Show("Bạn muốn huỷ xác nhận tính phụ cấp tăng cường 50%?", Resources.capXacNhan,
                                    MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }
            }
            else
            {
                if (
                    MessageBox.Show("Bạn muốn xác nhận các ngày làm việc vừa chọn tính phụ cấp tăng cường 50% nếu làm làm việc trên 8 tiếng?",
                                    Resources.capXacNhan, MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }
            }

            #endregion

            IsReload = true;

            foreach (var row in m_arrRecd)
            {
                var nhanvien = (cUserInfo)row["cUserInfo"];
                var ngay     = (DateTime)row["TimeStrNgay"];
                if (ngay <= XL2.ThangKetCong && XL2.ThangKetCong != DateTime.MinValue)
                {
                    continue;                                                                                   // ko thực hiện đối với các ngày trong tháng đã kết công
                }
                if (loai == -1)
                {
                    XL.CheckTinhPC50(nhanvien, ngay, false);
                }
                else
                {
                    XL.CheckTinhPC50(nhanvien, ngay, true);
                }
                XL.TinhLaiPhuCapTC(nhanvien.DSXNPhuCap50, nhanvien.DSNgayCong);
                XL.TinhLaiPhuCapDB(nhanvien.DSXNPhuCapDB, nhanvien.DSNgayCong);
            }
            this.Close();
        }
 private void btnTransfer_Click(object sender, EventArgs e)
 {
     AutoClosingMessageBox.Show("Successfully Transfered Webs", "Caption", 1000, MessageTypes.Success);
     this.RefToMenu.Show();
     this.Close();
 }
Ejemplo n.º 4
0
        private void SendMail()
        {
            bool _blnFlg = false;

            dsetRep = objFLRep.Get_Rep_Documents(ObjBLFD);
            if (dsetRep != null && dsetRep.Tables[0].Rows.Count != 0)
            {
                if (dsetRep.Tables[0].Rows.Count == 1)
                {
                    ConvertToPdf(ObjBLFD.HTMAIN[ObjBLFD.Primary_id].ToString(), ObjBLFD.Code, dsetRep.Tables[0].Rows[0]["sp_nm"].ToString().Trim(), dsetRep.Tables[0].Rows[0]["rep_nm"].ToString().Trim(), dsetRep.Tables[0].Rows[0]["desc"].ToString().Trim());
                }
                else
                {
                    foreach (Control c in panel1.Controls)
                    {
                        if (c is GroupBox)
                        {
                            foreach (Control c1 in ((GroupBox)c).Controls)
                            {
                                if (c1 is DataGridView)
                                {
                                    foreach (DataGridViewRow r in ((DataGridView)c1).Rows)
                                    {
                                        if (((DataGridView)c1).Columns.Count != 2 && !flgCopy && r.Cells["sel"].Value != null && bool.Parse(r.Cells["sel"].Value.ToString()))
                                        {
                                            objBLFD.ObjCompany.Copy_nm = "Original For Buyer";
                                            ConvertToPdf(ObjBLFD.HTMAIN[ObjBLFD.Primary_id].ToString(), ObjBLFD.Code, r.Cells["sp_nm"].Value.ToString(), r.Cells["rep_nm"].Value.ToString(), r.Cells["rep_desc"].Value.ToString());
                                        }
                                        else
                                        {
                                            if (((DataGridView)c1).Columns.Count == 2 && r.Cells["sel"].Value != null && bool.Parse(r.Cells["sel"].Value.ToString()))
                                            {
                                                foreach (DataGridViewRow row in dgv.Rows)
                                                {
                                                    //if (row.Cells["sel"].Value != null && bool.Parse(row.Cells["sel"].Value.ToString()))
                                                    //{
                                                    if (row.Cells["sel"].Value != null && row.Cells["sel"].Value.ToString() != "")
                                                    {
                                                        if (row.Cells["sel"].Value.ToString() == "1")
                                                        {
                                                            _blnFlg = true;
                                                        }
                                                        else if (row.Cells["sel"].Value.ToString() == "0")
                                                        {
                                                            _blnFlg = false;
                                                        }
                                                    }
                                                    if (_blnFlg)
                                                    {
                                                        objBLFD.ObjCompany.Copy_nm = r.Cells["copy_nm"].Value.ToString();
                                                        ConvertToPdf(ObjBLFD.HTMAIN[ObjBLFD.Primary_id].ToString(), ObjBLFD.Code, row.Cells["sp_nm"].Value.ToString(), row.Cells["rep_nm"].Value.ToString(), row.Cells["rep_desc"].Value.ToString());
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                DataSet dsetCM = objDL_ADAPTER.dsquery("select * from CM_MAST where ac_id='" + objBLFD.HTMAIN["ac_id"].ToString() + "' and ac_nm='" + objBLFD.HTMAIN["ac_nm"].ToString() + "'");
                if (dsetCM != null && dsetCM.Tables.Count != 0 && dsetCM.Tables[0].Rows.Count != 0)
                {
                    if (dsetCM.Tables[0].Columns.Contains("email") && dsetCM.Tables[0].Rows[0]["email"] != null && dsetCM.Tables[0].Rows[0]["email"].ToString() != "")
                    {
                        Outlook.Application oApp = new Outlook.Application();

                        Outlook.Accounts accounts = oApp.Session.Accounts;

                        Outlook._MailItem oMailItem = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
                        oMailItem.To = dsetCM.Tables[0].Rows[0]["email"].ToString();
                        //oMailItem.CC = "*****@*****.**";
                        oMailItem.Subject = objBLFD.Code + "-Attachment(s) ";
                        if (_hashSendMailAttachements != null && _hashSendMailAttachements.Count != 0)
                        {
                            foreach (DictionaryEntry entry in _hashSendMailAttachements)
                            {
                                oMailItem.Attachments.Add(entry.Value, Outlook.OlAttachmentType.olByValue, 1, entry.Value);
                            }
                        }
                        if (objBLFD.HASHTABLES != null && objBLFD.HASHTABLES.HashFileUpload != null && objBLFD.HASHTABLES.HashFileUpload.Count != 0)
                        {
                            foreach (DictionaryEntry entry in objBLFD.HASHTABLES.HashFileUpload)
                            {
                                if (((Hashtable)entry.Value).Count != 0)
                                {
                                    oMailItem.Attachments.Add(((Hashtable)entry.Value)["file_path"].ToString(), Outlook.OlAttachmentType.olByValue, 1, ((Hashtable)entry.Value)["file_path"].ToString());
                                }
                            }
                        }

                        string mailbody = "";
                        mailbody           = mailbody + "<BR/><BR/>" + ReadSignature();
                        oMailItem.HTMLBody = mailbody;

                        oMailItem.Display(true);
                    }
                    else
                    {
                        AutoClosingMessageBox.Show("Please Provide Valid Email id");
                        this.Close();
                    }
                }
                else
                {
                    AutoClosingMessageBox.Show("Please Provide Valid Customer");
                    this.Close();
                }
            }
            this.Close();
        }
Ejemplo n.º 5
0
        private void frmPrintPreview_Load(object sender, EventArgs e)
        {
            objFLRep.objCompany      = objBLFD.ObjCompany;
            objFl_Gen_Inv.objCompany = objBLFD.ObjCompany;

            if (flgDocorReport)
            {
                dsetRep = objFLRep.Get_Rep_Documents(ObjBLFD);
                if (dsetRep != null && dsetRep.Tables[0].Rows.Count != 0)
                {
                    if (dsetRep.Tables[0].Rows.Count == 1)
                    {
                        if (flgPreviewOrSendMail)
                        {
                            frmPrint objfrmPrint = new frmPrint(true);
                            objfrmPrint.ObjBLFD    = ObjBLFD;
                            objfrmPrint.tran_cd    = ObjBLFD.Code;
                            objfrmPrint.tran_id    = ObjBLFD.HTMAIN[ObjBLFD.Primary_id].ToString();
                            objfrmPrint.sp_name    = dsetRep.Tables[0].Rows[0]["sp_nm"].ToString().Trim();
                            objfrmPrint.rep_nm     = dsetRep.Tables[0].Rows[0]["rep_nm"].ToString().Trim();
                            objfrmPrint.rep_nmshow = dsetRep.Tables[0].Rows[0]["desc"].ToString().Trim();
                            // objfrmPrint.objComp = objBLFD.ObjCompany;
                            objfrmPrint.Show();
                            this.Close();
                        }
                        else
                        {
                            SendMail();
                        }
                    }
                    else
                    {
                        GroupBox grpbxreports = new GroupBox();
                        grpbxreports.Text = "Reports Details";

                        dgv.Name = "dgvRep";
                        dgv.Dock = DockStyle.Fill;
                        dgv.RowHeadersVisible  = false;
                        dgv.AllowUserToAddRows = false;

                        DataGridViewCheckBoxColumn chkcol = new DataGridViewCheckBoxColumn();
                        chkcol.HeaderText = "Select";
                        chkcol.Name       = "sel";
                        dgv.Columns.Add(chkcol);
                        dgv.Columns["sel"].Width = ctrlwid * 22 / 100;

                        DataGridViewTextBoxColumn txtcol = new DataGridViewTextBoxColumn();
                        txtcol.HeaderText = "Report Name";
                        txtcol.Name       = "rep_desc";
                        dgv.Columns.Add(txtcol);
                        dgv.Columns["rep_desc"].Width = ctrlwid * 75 / 100;

                        DataGridViewTextBoxColumn txtcol1 = new DataGridViewTextBoxColumn();
                        txtcol1.HeaderText = "Procedure Name";
                        txtcol1.Name       = "sp_nm";
                        dgv.Columns.Add(txtcol1);
                        dgv.Columns["sp_nm"].Visible = false;

                        DataGridViewTextBoxColumn txtcol2 = new DataGridViewTextBoxColumn();
                        txtcol2.HeaderText = "Report Name";
                        txtcol2.Name       = "rep_nm";
                        dgv.Columns.Add(txtcol2);
                        dgv.Columns["rep_nm"].Visible = false;

                        dgv.Rows.Clear();
                        int i = 0;
                        foreach (DataRow row in dsetRep.Tables[0].Rows)
                        {
                            dgv.Rows.Add(1);
                            dgv.Rows[i].Cells[1].Value = row["desc"].ToString();
                            dgv.Rows[i].Cells[2].Value = row["sp_nm"].ToString();
                            dgv.Rows[i].Cells[3].Value = row["rep_nm"].ToString();
                            i++;
                        }
                        //dgv.Bounds = new Rectangle(5, hgt + 5, (ctrlwid), ctrlhgt * 75 / 100);
                        grpbxreports.Bounds = new Rectangle(5, hgt + 5, (ctrlwid) - 10, ctrlhgt / 2);
                        hgt += ctrlhgt / 2 + (ctrlhgt * 5 / 100);
                        grpbxreports.Controls.Add(dgv);
                        //    dgv.Rows.RemoveAt(dgv.Rows.Count-1);
                        panel1.Controls.Add(grpbxreports);


                        if (objBLFD.Copies_nm != "" && objBLFD.Copies_nm != null)
                        {
                            GroupBox grpbxreports1 = new GroupBox();
                            grpbxreports1.Text = "Copy Details";

                            //  DataGridView dgv1 = new DataGridView();
                            dgv1.Name = "dgvRepCopy";
                            dgv1.Dock = DockStyle.Fill;
                            //  dgv1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                            //dgv.Height = panel1.Size.Height * 70 / 100;
                            dgv1.RowHeadersVisible  = false;
                            dgv1.AllowUserToAddRows = false;

                            DataGridViewCheckBoxColumn chkcol1 = new DataGridViewCheckBoxColumn();
                            chkcol1.HeaderText = "Select";
                            chkcol1.Name       = "sel";
                            dgv1.Columns.Add(chkcol1);
                            dgv1.Columns["sel"].Width = ctrlwid * 22 / 100;

                            DataGridViewTextBoxColumn txtcolcopy = new DataGridViewTextBoxColumn();
                            txtcolcopy.HeaderText = "Copy Name";
                            txtcolcopy.Name       = "copy_nm";
                            dgv1.Columns.Add(txtcolcopy);
                            dgv1.Columns["copy_nm"].Width = ctrlwid * 75 / 100;

                            dgv1.Rows.Clear();
                            //DataSet dsetcopy = objFl_Gen_Inv.GET_TBL_VAL("Copy_mast", "", ObjBLFD.ObjCompany.Compid.ToString());

                            String strCopy = objBLFD.Copies_nm;

                            int j = 0;

                            //foreach (DataRow row in dsetcopy.Tables[0].Rows)
                            //{
                            //    dgv1.Rows.Add(1);
                            //    dgv1.Rows[j].Cells[1].Value = row["copy_nm"].ToString();
                            //    j++;
                            //}

                            foreach (String str in strCopy.Split(','))
                            {
                                dgv1.Rows.Add(1);
                                dgv1.Rows[j].Cells[1].Value = str;
                                j++;
                            }

                            dgv1.CellContentClick += new DataGridViewCellEventHandler(dgv1_CellContent_click);
                            grpbxreports1.Bounds   = new Rectangle(5, hgt, (ctrlwid) - 10, ctrlhgt / 2);
                            hgt += ctrlhgt / 2 + (ctrlhgt * 5 / 100);
                            grpbxreports1.Controls.Add(dgv1);
                            panel1.Controls.Add(grpbxreports1);
                        }

                        Button btn = new Button();
                        btn.Name   = "Proceed";
                        btn.Text   = "&Proceed";
                        btn.Click += new EventHandler(btnProceed_Click);
                        btn.Bounds = new Rectangle((ctrlwid / 2) * 15 / 100, hgt, (ctrlwid / 2) * 70 / 100, ctrlhgt * 10 / 100);

                        //  btn.TextAlign = ContentAlignment.MiddleCenter;
                        this.panel1.Controls.Add(btn);
                        Button btn1 = new Button();
                        btn1.Name   = "Cancel";
                        btn1.Text   = "&Cancel";
                        btn1.Click += new EventHandler(btnCancel_Click);
                        btn1.Bounds = new Rectangle(((ctrlwid / 2) * 15 / 100) + (ctrlwid / 2), hgt, (ctrlwid / 2) * 70 / 100, ctrlhgt * 10 / 100);
                        hgt        += ctrlhgt * 15 / 100;
                        //  btn1.TextAlign = ContentAlignment.MiddleCenter;
                        this.panel1.Controls.Add(btn1);

                        // this.panel1.Height = hgt;
                        this.Width  = ctrlwid;
                        this.Height = hgt;
                    }
                }
                else
                {
                    AutoClosingMessageBox.Show("No documents exist", "Error", 3000);
                    this.Close();
                }
            }
            else
            {
                frmPrint objfrmPrint = new frmPrint(false);
                objfrmPrint.ObjBLFD    = ObjBLFD;
                objfrmPrint.sp_name    = HTFilter["sp_nm"].ToString();
                objfrmPrint.rep_nm     = HTFilter["rep_nm"].ToString();
                objfrmPrint.rep_nmshow = HTFilter["rep_gr"].ToString();
                objfrmPrint.HTFilter   = this.HTFilter;
                // objfrmPrint.objComp = objBLFD.ObjCompany;
                objfrmPrint.Show();
                this.Close();
            }
            ucToolBar1.Width1 = this.Width;
            this.Height       = hgt;
            AddThemesToTitleBar((Form)this, ucToolBar1, objBLFD, "Report");
            ucToolBar1.Titlebar = "Print Preview";
        }
        private void btnXacNhan_Click(object sender, EventArgs e)
        {
            if (SqlDataAccessHelper.TestConnection(SqlDataAccessHelper.ConnectionString) == false)
            {
                AutoClosingMessageBox.Show("Mất kết nối với CSDL. Vui lòng thử lại sau.", "Lỗi", 2000);
                return;
            }

            var loai   = 0;
            var pcngay = 0;
            var pcdem  = 0;
            var temp   = string.Empty;

            if (radKhongPC.Checked)
            {
                loai = -1;
            }
            else if (radPCNgayNghi.Checked)
            {
                loai   = 200;
                pcngay = XL2.PC100;
                pcdem  = XL2.PC160;
                temp   = "ngày nghỉ 100% (ban ngày), 150% (ban đêm)";
            }
            else if (radPCNgayLe.Checked)
            {
                loai   = 300;
                pcngay = XL2.PC200;
                pcdem  = XL2.PC290;
                temp   = "ngày lễ 200% (ban ngày), 250% (ban đêm), chưa kể công lễ, tết";
            }
            else if (radPCCus1.Checked)
            {
                loai   = 1;
                pcngay = (int)(numPCCus1.Value);
                temp   = "tuỳ chỉnh " + pcngay + "% cho giờ làm trên 8 tiếng";
            }
            else if (radPCCus2.Checked)
            {
                loai   = 2;
                pcngay = (int)(numPCCus2.Value);
                temp   = "tuỳ chỉnh " + pcngay + "% cho giờ làm";
            }

            #region hỏi lại trước khi thực hiện

            if (loai == -1)
            {
                if (MessageBox.Show(string.Format("Bạn muốn huỷ xác nhận tính phụ cấp {0}?", temp), Resources.capXacNhan,
                                    MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }
            }
            else
            {
                if (MessageBox.Show(string.Format("Bạn muốn xác nhận các ngày làm việc vừa chọn tính phụ cấp {0}?", temp),
                                    Resources.capXacNhan, MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    return;
                }
            }

            #endregion

            IsReload = true;

            foreach (var row in m_arrRecd)
            {
                var nhanvien = (cUserInfo)row["cUserInfo"];
                var ngay     = (DateTime)row["TimeStrNgay"];
                if (ngay <= XL2.ThangKetCong && XL2.ThangKetCong != DateTime.MinValue)
                {
                    continue;                                                                                   // ko thực hiện đối với các ngày trong tháng đã kết công
                }
                if (loai == -1)
                {
                    XL.HuyBo_TinhPCDB(nhanvien, ngay);
                }
                else
                {
                    XL.TinhPCDB(nhanvien, ngay, loai, pcngay, pcdem);
                }
            }
            this.Close();
        }
Ejemplo n.º 7
0
        //Below function handles what occurs when the "Okay" button is clicked, this can be triggered anywhere in the application
        //by the enter key and indicates that the user is satisfied with their selection.
        private void button1_Click(object sender, EventArgs e)
        {
            String Domain = comboBox1.Text;
            //String Machine = Environment.MachineName;
            //Is selected domain NOT the local machine name?
            string User = comboBox2.Text;

            if (IsNullOrWhiteSpace(User.ToString()) == false)
            {
                if (Domain != Environment.MachineName.ToString())
                {
                    string Result = (Domain.ToString() + "\\" + User.ToString());
                    string uID    = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                    if ((uID.Split('\\')[0]) == Environment.MachineName)

                    {
                        //          MessageBox.Show("Current user is a local user, \ntherefore we can not run a Directory Services check to determine if the selected network account exists");
                        DialogResult dr  = new DialogResult();
                        Form2        frm = new Form2();
                        dr = frm.ShowDialog(this);
                        if (dr == DialogResult.OK)
                        {
                            EditReg(User, Domain);
                            this.Hide();
                            AutoClosingMessageBox.Show("Login will default to: " + Result, "Next user:"******"Login will default to: " + Result, "Next user:"******"Cannot confirm that user exists in this domain, \nVerify network connection or check spelling.");
                        }
                    }
                }
                else
                {
                    //  MessageBox.Show("Selected domain is the local computer, no manual entries accepted, no check verifications possible.");
                    string Result = (Domain.ToString() + "\\" + User.ToString());
                    EditReg(User, Domain);
                    this.Hide();
                    AutoClosingMessageBox.Show("Login will default to: " + Result, "Next user:"******"Please select or type a username.");
            }
        }
Ejemplo n.º 8
0
        public static void SavePDF(bool isHtml, string bookPath, int totalPage, float width, float height, string UserAccount, string bookId, string dbPath, string thumbsPath_Msize, string thumbsPath_Lsize, int counter = 0)
        {
            //把參數存起來
            if (counter == 0)
            {
                PDFFactoryParameter pdfParameter = new PDFFactoryParameter();
                pdfParameter.isHtml           = isHtml;
                pdfParameter.bookPath         = bookPath;
                pdfParameter.totalPage        = totalPage;
                pdfParameter.width            = width;
                pdfParameter.height           = height;
                pdfParameter.UserAccount      = UserAccount;
                pdfParameter.bookId           = bookId;
                pdfParameter.dbPath           = dbPath;
                pdfParameter.thumbsPath_Msize = thumbsPath_Msize;
                pdfParameter.thumbsPath_Lsize = thumbsPath_Lsize;

                DataTable dt = MSCE.GetDataTable("select ID from FileRow where userid=@1 and id=@2"
                                                 , UserAccount.Replace("_Sync", "")
                                                 , bookId);

                if (dt.Rows.Count > 0)
                {
                    string ID      = dt.Rows[0]["ID"].ToString();
                    string SQL     = @"update  FileRow set PDFFactoryParameterJson=@1 where userid=@2 and id=@3";
                    int    success = MSCE.ExecuteNonQuery(SQL
                                                          , JsonConvert.SerializeObject(pdfParameter)
                                                          , UserAccount.Replace("_Sync", "")
                                                          , bookId);
                    if (success < 1)
                    {
                        LogTool.Debug(new Exception(@"DB失敗: " + SQL));
                    }
                }
            }


            string fileName = System.IO.Path.Combine(bookPath, @"PDFFactory\PDF.pdf");
            string PDFFactoryDirectoryName = Path.GetDirectoryName(fileName);
            string FinalFilePath           = System.IO.Path.Combine(bookPath, "PDF.pdf");

            Directory.CreateDirectory(PDFFactoryDirectoryName);
            //using (StreamWriter sw = new StreamWriter(fileName))
            //{
            //}
            //File.Create(fileName).Dispose();
            //string srcPDF = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "pdf.pdf");
            //File.Copy(srcPDF, fileName, true);
            //Thread th = new Thread(()=>
            Task.Factory.StartNew(() =>
            {
                try
                {
                    Singleton_PDFFactory.AddBookInPDFWork(bookId);
                    BookManager bookManager = new BookManager(dbPath);
                    float thinWidth         = 0.0f;
                    float thinHeight        = 0.0f;
                    float fatWidth          = 0.0f;
                    float fatHeight         = 0.0f;

                    if (width > height)
                    {
                        fatWidth   = width;
                        fatHeight  = height;
                        thinWidth  = fatHeight;
                        thinHeight = fatWidth;
                    }
                    else
                    {
                        thinWidth  = width;
                        thinHeight = height;
                        fatWidth   = thinHeight;
                        fatHeight  = thinWidth;
                    }



                    iTextSharp.text.Rectangle rect = new iTextSharp.text.Rectangle(width, height);
                    //將圖檔加入到PDF
                    Document myDoc = new Document(rect);
                    FileStream fs  = null;
                    //string fileName = System.IO.Path.Combine(bookPath, "PDFFactory/PDF.pdf");
                    //string PDFFactoryDirectoryName = Path.GetDirectoryName(fileName);
                    //string FinalFilePath = System.IO.Path.Combine(bookPath, "PDF.pdf");
                    try
                    {
                        fs = new FileStream(fileName, FileMode.Create);
                        PdfWriter writer = PdfWriter.GetInstance(myDoc, fs);
                        string[] files   = Directory.GetFiles(PDFFactoryDirectoryName, "*.bmp");

                        // sort them by creation time
                        Array.Sort <string>(files, delegate(string a, string b)
                        {
                            int fi_a = int.Parse(new FileInfo(a).Name.Split('.')[0]);
                            int fi_b = int.Parse(new FileInfo(b).Name.Split('.')[0]);

                            return(fi_a.CompareTo(fi_b));
                        });

                        myDoc.Open();
                        int i = 0;
                        //Full path to the Unicode Arial file
                        //string fontPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "kaiu.ttf");
                        ////Create a base font object making sure to specify IDENTITY-H
                        //BaseFont bf = BaseFont.CreateFont(fontPath,
                        //                                          BaseFont.IDENTITY_H, //橫式中文
                        //                                          BaseFont.NOT_EMBEDDED
                        //                                      );

                        //Create a specific font object
                        //iTextSharp.text.Font f = new iTextSharp.text.Font(bf, 12, iTextSharp.text.Font.NORMAL);

                        string fontPath = Environment.GetFolderPath(Environment.SpecialFolder.System) +
                                          @"\..\Fonts\kaiu.ttf";
                        BaseFont bfChinese = BaseFont.CreateFont(
                            fontPath,
                            BaseFont.IDENTITY_H, //橫式中文
                            BaseFont.NOT_EMBEDDED
                            );
                        iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 16f, iTextSharp.text.Font.NORMAL);

                        string pdfPath = "";
                        if (isHtml == false)
                        {
                            pdfPath = Path.Combine(bookPath, "hyweb");
                        }
                        else
                        {
                            pdfPath = Path.Combine(bookPath, "data");
                        }
                        string thumbsPath = "";
                        //string thumbsPath_Msize = Path.Combine(bookPath, "hyweb", "mthumbs");
                        //string thumbsPath_Lsize = Path.Combine(bookPath, "hyweb", "mthumbs\\Larger");
                        if (Directory.Exists(thumbsPath_Lsize) == true)
                        {
                            thumbsPath = thumbsPath_Lsize;
                        }
                        else
                        {
                            thumbsPath = thumbsPath_Msize;
                        }
                        string[] pdfFiles = Directory.GetFiles(pdfPath, "*.pdf");
                        string pdfPrefix  = "";
                        if (pdfFiles.Length > 0)
                        {
                            string fName = new FileInfo(pdfFiles[0]).Name;
                            pdfPrefix    = fName.Split(new char[] { '_' })[0];
                        }

                        for (int count = 1; count <= totalPage; count++)
                        {
                            try
                            {
                                string pdf = Path.Combine(pdfPath, pdfPrefix + "_" + count + ".pdf");
                                string thumb;
                                string extension = ".jpg";
                                if (isHtml == true)
                                {
                                    extension = ".png";
                                }
                                if (isHtml == false)
                                {
                                    thumb = Path.Combine(thumbsPath, pdfPrefix + "_" + count + extension);
                                }
                                else
                                {
                                    thumb = Path.Combine(thumbsPath, "Slide" + count + extension);
                                }
                                string imgPath = Path.Combine(PDFFactoryDirectoryName, count + ".bmp");

                                Directory.CreateDirectory(Path.GetDirectoryName(thumb));
                                if (File.Exists(thumb) == false)
                                {
                                    //GhostscriptWrapper.GeneratePageThumbs(pdf, thumb, 1, 1, 96, 96);

                                    //consolePDFtoJPG.exe
                                    //在背景執行,無DOS視窗閃爍問題
                                    //System.Diagnostics.Process p = new System.Diagnostics.Process();
                                    //p.StartInfo.FileName = "consolePDFtoJPG.exe";
                                    //p.StartInfo.Arguments = string.Format(" {0} {1} " ,pdf,thumb);
                                    //p.StartInfo.UseShellExecute = false;
                                    //p.StartInfo.RedirectStandardInput = true;
                                    //p.StartInfo.RedirectStandardOutput = true;
                                    //p.StartInfo.RedirectStandardError = true;
                                    //p.StartInfo.CreateNoWindow = true;
                                    //p.Start();
                                }

                                //畫面拍攝
                                //if (File.Exists(imgPath) == false)
                                //圖形標註
                                if (1 == 1 || File.Exists(imgPath) == false)
                                {
                                    //GetPdfThumbnail(pdf, imgPath);
                                    //ConvertPDF2Image(pdf, imgPath, 1, 1, ImageFormat.Bmp, Definition.Ten);
                                    if (File.Exists(thumb) == true)
                                    {
                                        File.Copy(thumb, imgPath, true);
                                    }
                                    else
                                    {
                                        //thumb = Path.Combine(thumbsPath_Msize, pdfPrefix + "_" + count + ".jpg");
                                        thumb = Path.Combine(thumbsPath, pdfPrefix + "_" + count + extension);
                                        if (File.Exists(thumb) == true)
                                        {
                                            File.Copy(thumb, imgPath, true);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTool.Debug(ex);
                            }
                        }

                        foreach (string file in files)
                        {
                            try
                            {
                                i++;
                                FileInfo fileInfo = new FileInfo(file);
                                if (fileInfo.Extension.ToLower().Equals(".bmp"))
                                {
                                    //myDoc.NewPage();
                                    string cmd = string.Format(@"SELECT page,status,alpha,canvasHeight,canvasWidth,color,points,width
                                                        FROM bookStrokesDetail as a inner join bookinfo as b on a.userbook_sno=b.sno 
                                                        where bookid='{0}' and page={1}  and account='{2}'"
                                                               , bookId, (i - 1).ToString(), UserAccount);

                                    QueryResult rs = bookManager.sqlCommandQuery(cmd);
                                    float xWidth   = 0;
                                    float xHeight  = 0;
                                    if (rs != null && rs.fetchRow())
                                    {
                                        xWidth  = rs.getFloat("canvasWidth");
                                        xHeight = rs.getFloat("canvasHeight");

                                        if (xWidth > 0 && xHeight > 0)
                                        {
                                            if (xWidth > xHeight)
                                            {
                                                if (fatWidth <= 0 || fatHeight <= 0)
                                                {
                                                    fatWidth   = width;
                                                    fatHeight  = height;
                                                    thinWidth  = fatHeight;
                                                    thinHeight = fatWidth;
                                                }
                                            }
                                            else
                                            {
                                                if (thinWidth <= 0 || thinHeight <= 0)
                                                {
                                                    thinWidth  = width;
                                                    thinHeight = height;
                                                    fatWidth   = thinHeight;
                                                    fatHeight  = thinWidth;
                                                }
                                            }
                                        }
                                        //myDoc.SetPageSize(new iTextSharp.text.Rectangle(xWidth, xHeight));
                                    }
                                    //else
                                    //{


                                    //    if (penMemoCanvasWidth > 0 && penMemoCanvasHeight > 0)
                                    //    {
                                    //        if (penMemoCanvasWidth > penMemoCanvasHeight)
                                    //        {
                                    //            if (penMemoCanvasWidth <= 0 || penMemoCanvasHeight <= 0)
                                    //            {
                                    //                fatWidth = penMemoCanvasWidth;
                                    //                fatHeight = penMemoCanvasHeight;
                                    //                thinWidth = fatHeight;
                                    //                thinHeight = fatWidth;
                                    //            }
                                    //        }
                                    //        else
                                    //        {
                                    //            if (penMemoCanvasWidth <= 0 || penMemoCanvasHeight <= 0)
                                    //            {
                                    //                thinWidth = penMemoCanvasWidth;
                                    //                thinHeight = penMemoCanvasHeight;
                                    //                fatWidth = thinHeight;
                                    //                fatHeight = thinWidth;
                                    //            }
                                    //        }
                                    //    }
                                    //}


                                    //


                                    //加入影像
                                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(file);
                                    float WidthRatio          = 1;
                                    float HeightRatio         = 1;


                                    if (img.Width > img.Height)
                                    {
                                        if (fatWidth > 0 && fatHeight > 0)
                                        {
                                            rect = new iTextSharp.text.Rectangle(fatWidth, fatHeight);
                                        }
                                        else
                                        {
                                            rect = new iTextSharp.text.Rectangle(thinHeight, thinWidth);
                                        }
                                    }
                                    else
                                    {
                                        if (thinWidth > 0 && thinHeight > 0)
                                        {
                                            rect = new iTextSharp.text.Rectangle(thinWidth, thinHeight);
                                        }
                                        else
                                        {
                                            rect = new iTextSharp.text.Rectangle(fatHeight, fatHeight);
                                        }
                                    }

                                    if (xWidth > 0 && xHeight > 0)
                                    {
                                        WidthRatio  = (rect.Width / xWidth);   /// (rect.Height / xHeight);
                                        HeightRatio = (rect.Height / xHeight); /// (rect.Width / xWidth);
                                    }

                                    myDoc.SetPageSize(rect);
                                    myDoc.NewPage();
                                    img.SetDpi(300, 300);
                                    img.ScaleToFit(rect.Width, rect.Height);
                                    //img.SetAbsolutePosition(0, rect.Height - img.Height);
                                    img.SetAbsolutePosition(0, 0);
                                    //if (xWidth > 0 && xHeight > 0)
                                    //{
                                    //    img.ScaleToFit(xWidth, xHeight);
                                    //    img.SetAbsolutePosition(0, rect.Height - xHeight);
                                    //}
                                    //else
                                    //{
                                    //    img.ScaleToFit(width, height);
                                    //    //img.SetAbsolutePosition(0, rect.Height - img.Height);
                                    //    img.SetAbsolutePosition(0, rect.Height - img.Height);
                                    //}
                                    myDoc.Add(img);

                                    //myDoc.Add(new iTextSharp.text.Paragraph("第 " + i.ToString() + " 頁", fontChinese));


                                    //加註記
                                    cmd = string.Format("select notes from booknoteDetail as a inner join bookInfo as b on a.userbook_sno=b.sno   where bookid='{0}' and page='{1}' and account='{2}'"
                                                        , bookId
                                                        , (i - 1).ToString()
                                                        , UserAccount);
                                    rs = bookManager.sqlCommandQuery(cmd);

                                    if (rs != null && rs.fetchRow())
                                    {
                                        //myDoc.Add(new iTextSharp.text.Paragraph(rs.getString("notes"), fontChinese));
                                        myDoc.Add(new iTextSharp.text.Paragraph("\r\n"));
                                        //myDoc.Add(new Annotation("作者", rs.getString("notes")));
                                        myDoc.Add(new Annotation("註解", rs.getString("notes")));
                                    }



                                    //小畫家
                                    cmd = string.Format(@"SELECT page,status,alpha,canvasHeight,canvasWidth,color,points,width
                                                        FROM bookStrokesDetail as a inner join bookinfo as b on a.userbook_sno=b.sno 
                                                        where bookid='{0}' and page={1} and status='0' and account='{2}'"
                                                        , bookId
                                                        , (i - 1).ToString()
                                                        , UserAccount);



                                    try
                                    {
                                        rs = bookManager.sqlCommandQuery(cmd);
                                    }
                                    catch (Exception ex)
                                    {
                                        LogTool.Debug(ex);
                                    }
                                    if (rs != null)
                                    {
                                        while (rs.fetchRow())
                                        {
                                            //float imgWidth = rs.getFloat("canvasWidth");
                                            //float imgHeight = rs.getFloat("canvasHeight");
                                            //img.ScaleToFit(imgWidth, imgHeight);
                                            //myDoc.Add(img);

                                            string color   = rs.getString("color");
                                            float alpha    = rs.getFloat("alpha");
                                            int red        = Convert.ToInt32(color.Substring(1, 2), 16);
                                            int green      = Convert.ToInt32(color.Substring(3, 2), 16);
                                            int blue       = Convert.ToInt32(color.Substring(5, 2), 16);
                                            float PenWidth = rs.getFloat("width");

                                            //PdfContentByte content = writer.DirectContent;
                                            //PdfGState state = new PdfGState();
                                            //state.StrokeOpacity = rs.getFloat("alpha");
                                            // Stroke where the red box will be drawn
                                            //content.NewPath();

                                            string points      = rs.getString("points");
                                            string[] pointsAry = points.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                                            int ii   = 0;
                                            float x1 = 0.0f;
                                            float y1 = 0.0f;

                                            List <float[]> fff = new List <float[]>();
                                            List <float> fList = new List <float>();

                                            foreach (string xy in pointsAry)
                                            {
                                                ++ii;


                                                string x = xy.Split(new char[] { '{', ',', '}' }, StringSplitOptions.RemoveEmptyEntries)[0];
                                                string y = xy.Split(new char[] { '{', ',', '}' }, StringSplitOptions.RemoveEmptyEntries)[1];

                                                //x1 = int.Parse(x);
                                                //y1 = int.Parse(y);
                                                x1 = int.Parse(x) * WidthRatio;
                                                y1 = int.Parse(y) * HeightRatio;

                                                //if (ii == 1)
                                                //    content.MoveTo(x1, y1);
                                                //else
                                                //{
                                                //    content.LineTo(x1, y1);
                                                //}


                                                fList.Add(x1);
                                                fList.Add(rect.Height - y1);
                                            }



                                            fff.Add(fList.ToArray());

                                            PdfAnnotation annotation = PdfAnnotation.CreateInk(writer, rect, "", fff.ToArray());
                                            annotation.Color         = new iTextSharp.text.BaseColor(red, green, blue, int.Parse(alpha.ToString()));
                                            annotation.BorderStyle   = new PdfBorderDictionary(PenWidth, PdfBorderDictionary.STYLE_SOLID);
                                            //隱藏註釋符號
                                            annotation.Flags = PdfAnnotation.FLAGS_PRINT;
                                            writer.AddAnnotation(annotation);

                                            //content.SetGState(state);
                                            //content.SetRGBColorStroke(red, green, blue);
                                            //content.SetLineWidth(PenWidth);
                                            //content.Stroke();
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTool.Debug(ex);
                            }
                        }
                        myDoc.AddTitle("電子書");    //文件標題
                        myDoc.AddAuthor("Hyweb"); //文件作者
                    }
                    catch (Exception ex)
                    {
                        LogTool.Debug(ex);
                    }
                    finally
                    {
                        try
                        {
                            try
                            {
                                if (myDoc.IsOpen())
                                {
                                    myDoc.Close();
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTool.Debug(ex);
                            }

                            try
                            {
                                if (fs != null)
                                {
                                    fs.Dispose();
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTool.Debug(ex);
                            }
                        }
                        catch (Exception ex)
                        {
                            LogTool.Debug(ex);
                        }
                    }

                    if (File.Exists(fileName) == true)
                    {
                        File.Copy(fileName, FinalFilePath, true);
                    }
                    //Singleton_PDFFactory.RemoveBookInPDFWork(bookId);

                    counter++;
                    if (counter <= 3)
                    {
                        Singleton_PDFFactory.SavePDF(isHtml, bookPath, totalPage, width, height, UserAccount, bookId, thumbsPath_Msize, thumbsPath_Lsize, dbPath, counter);
                    }
                    else
                    {
                        if (File.Exists(fileName) == true)
                        {
                            File.Copy(fileName, FinalFilePath, true);
                        }
                        Singleton_PDFFactory.RemoveBookInPDFWork(bookId);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    LogTool.Debug(ex);
                    if (counter > 3)
                    {
                        AutoClosingMessageBox.Show("轉檔失敗,請稍後再試");
                    }
                    //Singleton_PDFFactory.RemoveBookInPDFWork(bookId);
                }
            });

            //th.IsBackground = false;
            //th.Start();
        }
Ejemplo n.º 9
0
        private void btnThucHien_Click(object sender, EventArgs e)
        {
            if (SqlDataAccessHelper.TestConnection(SqlDataAccessHelper.ConnectionString) == false)
            {
                AutoClosingMessageBox.Show("Mất kết nối với CSDL. Vui lòng thử lại sau.", "Lỗi", 2000);
                return;
            }

            // kiểm tra chọn ca làm việc chưa? chưa thì báo
            cCaAbs ca = cbCa.SelectedItem as cCaAbs;

            if (ca == null || cbCa.SelectedIndex == 0)
            {
                AutoClosingMessageBox.Show("Bạn chưa chọn ca làm việc.", "Thông báo", 1500);
                return;
            }

            //đã chọn ca làm việc
            var      ngay       = dtpNgay.Value.Date;
            TimeSpan timespanBD = dtpBDLam.Value.TimeOfDay;
            TimeSpan timeSpanKT = dtpKTLam.Value.TimeOfDay;
            var      timeBD     = ngay.Add(timespanBD);
            var      timeKT     = ngay.Add(timeSpanKT);

            if (timespanBD > timeSpanKT)
            {
                timeKT = timeKT.AddDays(1d);
            }

            var sophutOT     = (checkXNLamThem.Checked && numSoPhutOT.Value > 0) ? (int)numSoPhutOT.Value : 0;
            var TinhPCTC     = (checkTinhPC150.Checked);
            var TreSomTinhCV = checkTreSomTinhCV.Checked;
            var giolam       = TimeSpan.Zero;
            var Cong         = 0d;
            var PhuCap       = 0d;

            if (ca.QuaDem && timespanBD < timeSpanKT && timespanBD < XL2._04h30)
            {
                timeBD = timeBD.AddDays(1d);
                timeKT = timeKT.AddDays(1d);
            }
            if (TinhToan(ngay, ca.ID, ca.WorkingTimeTS, ca.Workingday, ca.LunchMin, ngay.Add(ca.OnnTS), ngay.Add(ca.OffTS), ngay.Add(ca.chophepTreTS), ngay.Add(ca.chophepSomTS),
                         timeBD, timeKT, sophutOT, TinhPCTC, out giolam, out Cong, out PhuCap) == false)
            {
                tbGioLam.Text = giolam.TotalHours.ToString("#0.##");
                tbCong.Text   = Cong.ToString("0.0#");
                tbPC.Text     = PhuCap.ToString("0.0#");
                return;
            }

            #region hỏi lại trước khi thực hiện

            if (
                MessageBox.Show(
                    "Bạn muốn thêm các giờ chấm công tay cho các nhân viên?\nVui lòng kiểm tra kỹ thời gian nhập để không làm sai lệch công của nhân viên.",
                    Resources.capXacNhan, MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            #endregion


            // kiểm tra chọn NV chưa, chưa thì báo
            DataView tableCheckNV = dgrdDSNVTrgPhg.DataSource as DataView;
            if (tableCheckNV == null)
            {
                return;
            }
            DataRow[] arrRows = tableCheckNV.Table.Select("check = true", "UserEnrollNumber asc");
            if (arrRows.Length == 0)
            {
                AutoClosingMessageBox.Show("Bạn chưa chọn nhân viên.", "Thông báo", 1500);
                return;
            }

            // đã chọn NV, lấy ds mã CC đã chọn
            string lydo   = (cbLyDo.SelectedItem != null) ? cbLyDo.SelectedItem.ToString() : cbLyDo.SelectedText;
            string ghichu = tbGhiChu.Text;

            bool flag = true;

            try {
                foreach (DataRow row in arrRows)
                {
                    //dsNVcheck.Add((int)row["UserEnrollNumber"]);
                    int iUserEnrollNumber = (int)row["UserEnrollNumber"];
                    if (ca.ID == int.MinValue)
                    {
                        XL.TaoCaTuDo((cCaTuDo)ca, timeBD, XL2._08gio, XL2.ChoPhepTre, XL2.ChoPhepSom, XL2.LamThemAfterOT, 1f, "8");
                    }
                    else if (ca.ID == int.MinValue + 1)
                    {
                        XL.TaoCaTuDo((cCaTuDo)ca, timeBD, XL2._12gio, XL2.ChoPhepTre, XL2.ChoPhepSom, XL2.LamThemAfterOT, 1.5f, "D");
                    }

                    if (checkXNLamThem.Checked || TinhPCTC || TreSomTinhCV)                     //1.có XN làm thêm --> thêm giờ XN,  2.không xác nhận làm thêm thì thêm giờ A
                    {
                        var nv = new cUserInfo {
                            MaCC = iUserEnrollNumber, NgayCongBD_Bef2D = ngay.Date.AddDays(-2d), NgayCongKT_Aft2D = ngay.Date.AddDays(2d)
                        };
                        var chkinn = new cChkInn_A {
                            Time = timeBD, Type = "I", MachineNo = 21, Source = "PC", PhucHoi = new cPhucHoi {
                                Them = true, IDGioGoc = -1, Xoaa = false
                            }
                        };

                        var chkout = new cChkOut_A {
                            Time = timeKT, Type = "O", MachineNo = 22, Source = "PC", PhucHoi = new cPhucHoi {
                                Them = true, IDGioGoc = -1, Xoaa = false
                            }
                        };
                        var cio_a = new cChkInOut_A {
                            Vao           = chkinn,
                            Raa           = chkout,
                            HaveINOUT     = 1,
                            ThuocCa       = ca,
                            TimeDaiDien   = chkinn.Time,
                            ThuocNgayCong = XL.ThuocNgayCong(chkinn.Time),
                            TD            = new ThoiDiem()
                        };
                        if (cio_a.ThuocNgayCong <= XL2.ThangKetCong && XL2.ThangKetCong != DateTime.MinValue)
                        {
                            continue;                                                                                                           //tbd temp patch
                        }
                        nv.DS_CIO_A.Add(cio_a);
                        XL.ThemGioChoNV(chkinn, nv, XL2.currUserID, lydo, ghichu);
                        XL.ThemGioChoNV(chkout, nv, XL2.currUserID, lydo, ghichu);
                        if (ca.TachCa)
                        {
                            XL.XacNhanCoTachCa(nv, cio_a, ca, sophutOT, TinhPCTC, TreSomTinhCV);
                        }
                        else
                        {
                            XL.XacNhanKoTachCa(nv, cio_a, ca, sophutOT, TinhPCTC, TreSomTinhCV);
                        }
                    }
                    else                      //2.không xác nhận làm thêm thì thêm giờ A
                    {
                        if (timeBD.Date <= XL2.ThangKetCong && XL2.ThangKetCong != DateTime.MinValue)
                        {
                            continue;                                                                                                   //tbd temp patch
                        }
                        var nv = new cUserInfo {
                            MaCC = iUserEnrollNumber, NgayCongBD_Bef2D = ngay.Date.AddDays(-2d), NgayCongKT_Aft2D = ngay.Date.AddDays(2d)
                        };
                        XL.ThemGioChoNV(new cChkInn_A {
                            Time = timeBD, Type = "I", MachineNo = 21, Source = "PC", PhucHoi = new cPhucHoi {
                                Them = true, IDGioGoc = -1, Xoaa = false
                            }
                        }, new cUserInfo {
                            MaCC = iUserEnrollNumber
                        }, XL2.currUserID, lydo, ghichu);
                        XL.ThemGioChoNV(new cChkOut_A {
                            Time = timeKT, Type = "O", MachineNo = 22, Source = "PC", PhucHoi = new cPhucHoi {
                                Them = true, IDGioGoc = -1, Xoaa = false
                            }
                        }, new cUserInfo {
                            MaCC = iUserEnrollNumber
                        }, XL2.currUserID, lydo, ghichu);
                        XL.CheckTinhPC50(nv, (timeBD.TimeOfDay < XL2._04h30 ? timeBD.Date.AddDays(-1) : timeBD.Date), TinhPCTC);
                    }
                }
            } catch (Exception exception) {
                lg.Error("", exception);
            }
            if (flag)
            {
                AutoClosingMessageBox.Show("Thêm giờ chấm công tay cho các nhân viên thành công.", "Thông báo", 2000);
            }
        }
Ejemplo n.º 10
0
        private void CheckLogin(User user)
        {
            try
            {
                if (user != null)
                {
                    switch (user.State)
                    {
                    case "0":
                    {
                        string text  = JsonConvert.SerializeObject(user.EnableButtonList);
                        string text2 = (user.UTC == null) ? DateTool.GetCurrentTimeInUnixMillis().ToString() : user.UTC.ToString();
                        long   num   = 0L;
                        try
                        {
                            num = DateTool.GetCurrentTimeInUnixMillis() - long.Parse(text2);
                        }
                        catch (Exception ex)
                        {
                            LogTool.Debug(ex);
                        }
                        string   text3 = "Update NowLogin set UserID=@1,UserName=@2,UserPWD=@3,MeetingListDate=getdate(),HomeUserButtonAryJSON=@4,UserEmail=@5,UTC=@6,DeltaUTC=@7,RemeberLogin=@8";
                        string[] array = new string[8]
                        {
                            user.ID,
                            user.Name,
                            tbUserPWD.Password.Trim(),
                            text,
                            user.Email,
                            text2,
                            num.ToString(),
                            null
                        };
                        bool?isChecked = cbRemeberLogin.IsChecked;
                        array[7] = ((isChecked.GetValueOrDefault() && isChecked.HasValue) ? "true" : "false");
                        int num2 = MSCE.ExecuteNonQuery(text3, array);
                        if (num2 < 1)
                        {
                            LogTool.Debug(new Exception("DB失敗: " + text3));
                            return;
                        }
                        try
                        {
                            DataTable dataTable = MSCE.GetDataTable("select UserID from LoginInfo where UserID =@1", user.ID);
                            if (dataTable.Rows.Count > 0)
                            {
                                MSCE.ExecuteNonQuery("UPDATE [LoginInfo] SET \r\n                                                 [UserID] = @1\r\n\t\t                                        ,[UserPWD] = @2\r\n                                                ,UserJson = @3\r\n\t\t                                         where UserID=@4", user.ID, tbUserPWD.Password.Trim(), JsonConvert.SerializeObject(user), user.ID);
                            }
                            else
                            {
                                MSCE.ExecuteNonQuery("INSERT INTO [LoginInfo] ([UserID],[UserPWD],UserJson)\r\n                                                            VALUES (@1,@2,@3)", user.ID, tbUserPWD.Password.Trim(), JsonConvert.SerializeObject(user));
                            }
                            dataTable = MSCE.GetDataTable("select ListDate from UserData where UserID =@1 and ListDate =@2", user.ID, DateTool.MonthFirstDate(DateTime.Now).ToString("yyyyMMdd"));
                            if (dataTable.Rows.Count > 0)
                            {
                                MSCE.ExecuteNonQuery("UPDATE [UserData] SET \r\n                                                             [ListDate] = @1\r\n\t\t                                                    ,[UserJson] = @2\r\n\t\t                                                     where UserID = @3 and ListDate =@4", DateTool.MonthFirstDate(DateTime.Now).ToString("yyyyMMdd"), JsonConvert.SerializeObject(user), user.ID, DateTool.MonthFirstDate(DateTime.Now).ToString("yyyyMMdd"));
                            }
                            else
                            {
                                MSCE.ExecuteNonQuery("INSERT INTO [UserData] ([UserID],[ListDate],UserJson)\r\n                                                                        VALUES (@1,@2,@3)", user.ID, DateTool.MonthFirstDate(DateTime.Now).ToString("yyyyMMdd"), JsonConvert.SerializeObject(user));
                            }
                        }
                        catch (Exception ex2)
                        {
                            LogTool.Debug(ex2);
                        }
                        Hide();
                        Home home = new Home(user, tbUserPWD.Password.Trim());
                        home.Show();
                        Close();
                        break;
                    }

                    case "1":
                        AutoClosingMessageBox.Show("無此使用者帳號,請重新輸入");
                        break;

                    case "2":
                        AutoClosingMessageBox.Show("帳號密碼錯誤或帳號已被鎖定");
                        break;
                    }
                }
            }
            catch (Exception ex3)
            {
                LogTool.Debug(ex3);
            }
            canLogin = true;
            MouseTool.ShowArrow();
        }
Ejemplo n.º 11
0
 private static void _003CCallLigon_003Eb__11()
 {
     AutoClosingMessageBox.Show("登入失敗");
 }
Ejemplo n.º 12
0
        private void CallLigon()
        {
            Action <HttpWebResponse> action = null;

            canLogin = false;
            MouseTool.ShowLoading();
            try
            {
                string text  = tbUserID.Text.Trim();
                string text2 = tbUserPWD.Password.Trim();
                string text3 = DateTool.MonthFirstDate(DateTime.Today).ToString("yyyyMMdd");
                string text4 = DateTool.MonthFirstDate(DateTime.Today.AddMonths(1)).ToString("yyyyMMdd");
                if (NetworkTool.CheckNetwork() > 0)
                {
                    string url    = WsTool.GetUrl();
                    string format = "<?xml version=\"1.0\"?><UserInfo><UserID><![CDATA[{0}]]></UserID><UserPW><![CDATA[{1}]]></UserPW><UserDevice>1</UserDevice><UserDateBegin>{2}</UserDateBegin><UserDateEnd>{3}</UserDateEnd></UserInfo>";
                    format = string.Format(format, text, text2, text3, text4);
                    Dictionary <string, string> dictionary = new Dictionary <string, string>();
                    dictionary["XmlDoc"] = format;
                    HttpWebRequest httpWebRequest = HttpTool.GetHttpWebRequest(url + "/UserData", "POST", dictionary);
                    if (action == null)
                    {
                        action = new Action <HttpWebResponse>(_003CCallLigon_003Eb__10);
                    }
                    DoWithResponse(httpWebRequest, action);
                }
                else
                {
                    DataTable dataTable = MSCE.GetDataTable("select UserID from LoginInfo where UserID =@1", text);
                    if (dataTable.Rows.Count > 0)
                    {
                        dataTable = MSCE.GetDataTable("select UserJson from LoginInfo where UserID =@1 and UserPWD=@2", text, text2);
                        if (dataTable.Rows.Count > 0)
                        {
                            User   user  = JsonConvert.DeserializeObject <User>(dataTable.Rows[0]["UserJson"].ToString());
                            string text5 = JsonConvert.SerializeObject(user.EnableButtonList);
                            string s     = user.UTC.ToString();
                            long   num   = 0L;
                            try
                            {
                                num = DateTool.GetCurrentTimeInUnixMillis() - long.Parse(s);
                            }
                            catch (Exception ex)
                            {
                                LogTool.Debug(ex);
                            }
                            string   text6 = "Update NowLogin set UserID=@1,UserName=@2,UserPWD=@3,MeetingListDate=getdate(),HomeUserButtonAryJSON=@4,UserEmail=@5,UTC=@6,DeltaUTC=@7,RemeberLogin=@8";
                            string[] array = new string[8]
                            {
                                user.ID,
                                user.Name,
                                tbUserPWD.Password.Trim(),
                                text5,
                                user.Email,
                                DateTool.GetCurrentTimeInUnixMillis().ToString(),
                                num.ToString(),
                                null
                            };
                            bool?isChecked = cbRemeberLogin.IsChecked;
                            array[7] = ((isChecked.GetValueOrDefault() && isChecked.HasValue) ? "true" : "false");
                            int num2 = MSCE.ExecuteNonQuery(text6, array);
                            if (num2 < 1)
                            {
                                LogTool.Debug(new Exception("DB失敗: " + text6));
                            }
                            else
                            {
                                base.Dispatcher.BeginInvoke(new Action <User>(CheckLogin), user);
                            }
                        }
                        else
                        {
                            MouseTool.ShowArrow();
                            AutoClosingMessageBox.Show("您的密碼錯誤");
                            canLogin = true;
                        }
                    }
                    else
                    {
                        MouseTool.ShowArrow();
                        AutoClosingMessageBox.Show("無此使用者帳號,請重新輸入");
                        canLogin = true;
                    }
                }
            }
            catch (Exception)
            {
                MouseTool.ShowArrow();
                AutoClosingMessageBox.Show("登入失敗");
                canLogin = true;
            }
        }
Ejemplo n.º 13
0
        private void calc_cost_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            #region 10c
            cost_nic_level.Text      = cost_nic_level.Text.Replace(",", ".");
            cost_booster_bottle.Text = cost_booster_bottle.Text.Replace(",", ".");
            double Targetml, Targetlvl, boosterlvl, cost_bottle;
            try
            {
                Targetml = Convert.ToDouble(cost_Target_ml.Text);
            }
            catch (Exception ex)
            {
                title = "Error";
                AutoClosingMessageBox.Show(cost_Target_ml + "\n" + ex.Message, title, autotimeout);
                return;
            }
            try
            {
                Targetlvl = Convert.ToDouble(cost_nic_level.Text);
            }
            catch (Exception ex)
            {
                title = "Error";
                AutoClosingMessageBox.Show(cost_nic_level + "\n" + ex.Message, title, autotimeout);
                return;
            }
            try
            {
                boosterlvl = Convert.ToDouble(nic_booster_level.Text);
            }
            catch (Exception ex)
            {
                title = "Error ";
                AutoClosingMessageBox.Show(nic_booster_level.Text + "\n" + ex.Message, title, autotimeout);
                return;
            }
            try
            {
                cost_bottle = Convert.ToDouble(cost_booster_bottle.Text);
            }
            catch (Exception ex)
            {
                title = "Error";
                AutoClosingMessageBox.Show(cost_booster_bottle.Text + "\n" + ex.Message, title, autotimeout);
                return;
            }
            if (Targetml == 0 || Targetlvl == 0 || boosterlvl == 0 || cost_bottle == 0)
            {
                return;
            }
            if (Targetlvl > boosterlvl)
            {
                title   = "Error";
                message = $"{Targetlvl} < {boosterlvl}";
                AutoClosingMessageBox.Show(message, title, autotimeout);
                return;
            }
            gb_base.Visibility    = Visibility.Visible;
            gb_nicml.Visibility   = Visibility.Visible;
            gb_nicbtl.Visibility  = Visibility.Visible;
            gb_totcost.Visibility = Visibility.Visible;
            double tbl_10b, tbl_10c, tbl_10e, tbl_10f;

            if ((cost_nic_level.Text != "") && (nic_booster_level.Text != ""))
            {
                double temp      = Targetlvl / boosterlvl;
                double costperml = cost_bottle / 10;

                //--10ml--
                tbl_10c                  = temp * Targetml;
                tbl_10b                  = Targetml - tbl_10c;
                tbl_10e                  = Math.Ceiling((tbl_10c * 1) / 10);
                tbl_10f                  = tbl_10e * cost_bottle;
                tbl_Baseml.Text          = Convert.ToString(Math.Round(tbl_10b, 2));
                tbl_NicotineMl.Text      = Convert.ToString(Math.Round(tbl_10c, 2));
                tbl_NicotineBottles.Text = Convert.ToString(Math.Round(tbl_10e, 2));
                tbl_BoosterCost.Text     = Convert.ToString(Math.Round(tbl_10f, 2));
                #endregion
            }
        }
        private void EditLogUpdateButton_Click(object sender, RoutedEventArgs e)
        {
            if (
                string.IsNullOrEmpty(Edit_LogRecipeName.Text) ||
                string.IsNullOrEmpty(Edit_LogAmount.Text) ||
                string.IsNullOrEmpty(Edit_LogPGRatio.Text) ||
                string.IsNullOrEmpty(Edit_LogVGRatio.Text) ||
                string.IsNullOrEmpty(editlog_date.cmbYear.Text) ||
                string.IsNullOrEmpty(editlog_date.cmbMonths.Text) ||
                string.IsNullOrEmpty(editlog_date.cmbDays.Text)
                )
            {
                return;
            }
            //Do Something Here

            try
            {
                using (dbConn = new SQLiteConnection(connectionString))
                {
                    string months, days;
                    int    month = (editlog_date.cmbMonths.SelectedIndex + 1);
                    int    day   = (editlog_date.cmbDays.SelectedIndex + 1);
                    if (month <= 9)
                    {
                        months = "0" + month.ToString();
                    }
                    else
                    {
                        months = month.ToString();
                    }
                    if (day <= 9)
                    {
                        days = "0" + day.ToString();
                    }
                    else
                    {
                        days = day.ToString();
                    }
                    string logPGVG = Edit_LogPGRatio.Text + "/" + Edit_LogVGRatio.Text;
                    string logDate = editlog_date.cmbYear.Text + "/" + months + "/" + days;
                    dbConn.Open();
                    //Insert Command
                    string query;
                    query = $"UPDATE [RecipeLog] SET" +
                            $" Name = '{Edit_LogRecipeName.Text.Replace("'", "''")}'," +
                            $" Amount = '{Edit_LogAmount.Text}'," +
                            $" Ratio = '{logPGVG}'," +
                            $" Date = '{logDate}'," +
                            $" Notes = '{Edit_LogNotes.Text.Replace("'", "''")}'" +
                            $" where id = " + Int32.Parse(this.EditItemIdBox.Text.ToString()) + "; ";
                    dbCmd = new SQLiteCommand(query, dbConn);
                    dbCmd.ExecuteNonQuery();
                    dbCmd.Dispose();
                    dbConn.Close();
                }
            }
            catch (Exception ex)
            {
                AutoClosingMessageBox.Show(ex.ToString(), "Error", autotimeout);
                return;
            }
            //ENd Here
            EditLogElementInputBox.Visibility = Visibility.Collapsed;
            Edit_LogRecipeName.Text           = String.Empty;
            Edit_LogAmount.Text  = String.Empty;
            Edit_LogPGRatio.Text = String.Empty;
            Edit_LogVGRatio.Text = String.Empty;
            Edit_LogNotes.Text   = String.Empty;
            FillDataGrid();
        }
Ejemplo n.º 15
0
        private void CallOpenBook(bool HasOpenFinishedFileVersion = false)
        {
            MouseTool.ShowLoading();
            try
            {
                Home Home_Window = Application.Current.Windows.OfType <Home>().FirstOrDefault();

                if (Home_Window.IsInSync == true && Home_Window.IsSyncOwner == false)
                {
                    AutoClosingMessageBox.Show("同步中需由主控人員進行操作");
                    return;
                }


                //

                string filePath = ClickOnceTool.GetFilePath();

                //string _bookPath = System.IO.Path.Combine(filePath, fileItem.UnZipFilePath);
                string UnZipFileFolder = PaperLess_Emeeting.Properties.Settings.Default.File_UnZipFileFolder;
                //string _bookPath = filePath + "\\" + UnZipFileFolder + "\\" + UserID + "\\" + MeetingID + "\\"+ fileItem.ID +"\\"+fileItem.FileVersion.ToString();
                // 等於上面那個路徑
                string _bookPath = fileItem.UnZipFilePath;

                // 從資料庫查詢上一次完成的檔案版本
                if (HasOpenFinishedFileVersion == true)
                {
                    DataTable dt = MSCE.GetDataTable("SELECT FinishedFileVersion FROM FileRow where ID=@1 and UserID=@2 and MeetingID=@3"
                                                     , meetingDataDownloadFileFile.ID
                                                     , UserID
                                                     , MeetingID);
                    if (dt.Rows.Count > 0)
                    {
                        _bookPath = filePath + "\\" + UnZipFileFolder + "\\" + UserID + "\\" + MeetingID + "\\" + fileItem.ID + "\\" + dt.Rows[0]["FinishedFileVersion"].ToString();
                    }
                }
                string _bookId    = fileItem.ID;
                string _account   = UserID;
                string _userName  = UserName;
                string _email     = UserEmail;
                string _meetingId = MeetingID;
                string _watermark = "";
                if (MeetingDataCT_GetWatermark_Event != null)
                {
                    _watermark = MeetingDataCT_GetWatermark_Event();
                }
                string _dbPath        = System.IO.Path.Combine(ClickOnceTool.GetDataPath(), PaperLess_Emeeting.Properties.Settings.Default.bookInfo_Path);
                bool   _isSync        = Home_Window.IsInSync;
                bool   _isSyncOwner   = Home_Window.IsSyncOwner;
                string _webServiceUrl = WsTool.GetUrl() + "/AnnotationUpload";
                string _socketMessage = "";


                SocketClient _socket   = null;
                SocketClient tmpSocket = Singleton_Socket.GetInstance(MeetingID, UserID, UserName, Home_Window.IsInSync);

                if (tmpSocket != null && tmpSocket.GetIsConnected() == true)
                {
                    _socket = tmpSocket;
                }

                //if (_socket.GetIsConnected() == false)
                //    _socket = null;
                //if (Home_Window.IsInSync == false)
                //    _socket = null;

                // 呼叫一個事件取得 BookVMs
                Dictionary <string, BookVM> cbBooksData = new Dictionary <string, BookVM>();
                if (MeetingDataCT_GetBookVMs_ByMeetingFileCate_Event != null)
                {
                    cbBooksData = MeetingDataCT_GetBookVMs_ByMeetingFileCate_Event(fileItem);
                }
                // debug
                //BooksData["cAF6-P"] = new BookVM("cAF6-P", filePath + "\\" + UnZipFileFolder + "\\" + UserID + "\\" + MeetingID + "\\" + "cAF6-P");
                //BooksData["cAF3-P"] = new BookVM("cAF3-P", filePath + "\\" + UnZipFileFolder + "\\" + UserID + "\\" + MeetingID + "\\" + "cAF3-P");

                Home_Window.CloseAllWindow("", true);

                switch (fileItem.FileCate)
                {
                case MeetingFileCate.電子書:

                    InitSyncCenter(_dbPath, _bookId, _account, _meetingId);

                    Task.Factory.StartNew(() =>
                    {
                        this.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            byte[] ReaderKey = new byte[1];

                            try
                            {
                                if (fileItem.EncryptionKey.Equals("") == false)
                                {
                                    ReaderKey = ReaderDecodeTool.GetReaderKey(fileItem.EncryptionKey);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogTool.Debug(ex);
                            }
                            ReadWindow rw = new ReadWindow(cbBooksData, Home_Window.OpenBookFromReader, _bookPath, _bookId, _account
                                                           , _userName, _email, _meetingId
                                                           , _watermark, _dbPath, _isSync
                                                           , _isSyncOwner, _webServiceUrl, ReaderKey, _socketMessage, _socket);

                            //ReadWindow rw = new ReadWindow(cbBooksData, Home_Window.OpenBookFromReader, _bookPath, _bookId, _account
                            //                      , _userName, _email, _meetingId
                            //                      , _watermark, _dbPath, _isSync
                            //                      , _isSyncOwner, _webServiceUrl, _socketMessage, _socket);
                            rw.FolderID = this.FolderID;
                            rw.WindowStyle = WindowStyle.None;
                            rw.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            rw.WindowState = WindowState.Maximized;
                            if (PaperLess_Emeeting.Properties.Settings.Default.AssemblyName.Contains("TPI4F") == true)
                            {
                                //rw.WindowStyle = WindowStyle.SingleBorderWindow;
                            }
                            rw.Show();
                        }));
                    });


                    break;

                case MeetingFileCate.Html5投影片:
                    _bookPath = _bookPath + @"\" + new FileInfo(Directory.GetFiles(_bookPath)[0]).Name;

                    InitSyncCenter(_dbPath, _bookId, _account, _meetingId);

                    Task.Factory.StartNew(() =>
                    {
                        this.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            HTML5ReadWindow Html5rw = new HTML5ReadWindow(cbBooksData, Home_Window.OpenBookFromReader, _bookPath, _bookId, _account
                                                                          , _userName, _email, _meetingId
                                                                          , _watermark, _dbPath, _isSync
                                                                          , _isSyncOwner, _webServiceUrl, _socketMessage, _socket);
                            Html5rw.FolderID = this.FolderID;
                            Html5rw.WindowStyle = WindowStyle.None;
                            Html5rw.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            Html5rw.WindowState = WindowState.Maximized;
                            if (PaperLess_Emeeting.Properties.Settings.Default.AssemblyName.Contains("TPI4F") == true)
                            {
                                //Html5rw.WindowStyle = WindowStyle.SingleBorderWindow;
                            }
                            Html5rw.Show();
                        }));
                    });


                    break;

                case MeetingFileCate.影片檔:
                    _bookPath = _bookPath + @"\" + new FileInfo(Directory.GetFiles(_bookPath)[0]).Name;

                    Task.Factory.StartNew(() =>
                    {
                        this.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            MVWindow mvWindow = new MVWindow(cbBooksData, Home_Window.OpenBookFromReader, _bookPath, _bookId);
                            mvWindow.WindowStyle = WindowStyle.None;
                            mvWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            mvWindow.WindowState = WindowState.Maximized;
                            if (PaperLess_Emeeting.Properties.Settings.Default.AssemblyName.Contains("TPI4F") == true)
                            {
                                //mvWindow.WindowStyle = WindowStyle.SingleBorderWindow;
                            }
                            mvWindow.Show();
                        }));
                    });

                    break;
                }

                if (Home_Window.IsInSync == true && Home_Window.IsSyncOwner == true)
                {
                    SocketClient socketClient = Singleton_Socket.GetInstance(MeetingID, UserID, UserName, Home_Window.IsInSync);
                    Task.Factory.StartNew(() =>
                    {
                        if (socketClient != null && socketClient.GetIsConnected() == true)
                        {
                            string OB = "{\"bookId\":\"" + meetingDataDownloadFileFile.ID + "\",\"cmd\":\"R.OB\"}";
                            socketClient.broadcast(OB);
                        }
                        else
                        {
                            //AutoClosingMessageBox.Show("同步伺服器尚未啟動,請聯絡議事管理員開啟同步");
                        }
                    });
                }
            }
            catch (Exception ex)
            {
                LogTool.Debug(ex);
            }

            MouseTool.ShowArrow();
        }
Ejemplo n.º 16
0
        private void btnXuatBB_Click(object sender, EventArgs e)
        {
            if (SqlDataAccessHelper.TestConnection(SqlDataAccessHelper.ConnectionString) == false)
            {
                AutoClosingMessageBox.Show("Mất kết nối với CSDL. Vui lòng thử lại sau.", "Lỗi", 2000);
                return;
            }

            //1. lấy dữ liệu từ form
            #region lấy ngày BD và kết thúc, và update lại Ngày BD = 1 ngày trước 31/08 12:00 AM, ngày KT là 1 ngày sau ngay 1 23:59:59
            dtpNgay.Update();
            DateTime ngayBD = dtpNgay.Value.Date;
            ngayBD = ngayBD.AddDays(-2d);
            DateTime ngayKT = ngayBD.AddDays(4d);
            #endregion

            // lấy dsnv tất cả nv thuộc các phòng ban được chọn
            DataTable table = DAL.LayDSNV(m_listIDPhongBan.ToArray());
            if (table.Rows.Count == 0)
            {
                return;
            }
            m_DSNV.Clear();
            XL.KhoiTaoDSNV(m_DSNV, table);

            //3. lấy dữ liệu chấm công của các nhân viên
            //[CHÚ Ý] ngày bắt đầu và kết thúc đã cộng trừ thêm 1 ngày trước sau ở bở trên
            if (XL.KiemtraDulieuCapnhatTuServer(DateTime.Now) == false)
            {
                AutoClosingMessageBox.Show("Dữ liệu chấm công chưa được cập nhật mới nhất từ các máy chấm công.\nCác thay đổi giờ chấm công có thể làm sai sót giờ chấm công thực tế khi dữ liệu được cập nhật.", "Thông báo", 4000);
            }

            int SoNVDangLamViec = 0, SoNVDaRaVe = 0, SoNVVang = 0;
            //dsnv = XL.XemCong(table, ArrDSMaCC_Checked, ngayBD, ngayKT);
            XL.DiemDanh(m_DSNV, ngayBD, ngayKT);
            m_CTDiemDanh.Rows.Clear();
            XL.TaoTableDiemDanh(m_DSNV, m_CTDiemDanh, out SoNVDangLamViec, out SoNVDaRaVe, out SoNVVang);

            saveFileDlgDiemDanh.Filter = "Excel File|*.xlsx";
            saveFileDlgDiemDanh.ShowDialog();
            if (saveFileDlgDiemDanh.FileName == String.Empty)
            {
                return;
            }
            var saveFileName = saveFileDlgDiemDanh.FileName;

            using (var p = new ExcelPackage()) {
                #region Ghi file , nếu xảy ra lỗi thì báo
                XuatBBDSNVDLV(p);
                XuatBBDSNVVang(p);
                Byte[] bin = p.GetAsByteArray();
                try {
                    File.WriteAllBytes(saveFileName, bin);                    //(file_path, bin);
                    AutoClosingMessageBox.Show("Xuất báo biểu thành công.", "Thông báo", 2000);
                } catch (Exception exception) {
                    lg.Error("XuatBBDiemDanh", exception);
                    if (exception is UnauthorizedAccessException)
                    {
                        MessageBox.Show("Bạn chưa được cấp quyền ghi file vào folder.", "Lỗi");
                    }
                    else if (exception is DirectoryNotFoundException)
                    {
                        MessageBox.Show("Không tìm thấy folder lưu trữ.", "Lỗi");
                    }
                    else if (exception is IOException)
                    {
                        MessageBox.Show("File đang mở bởi ứng dụng khác.", "Lỗi");
                    }
                    else
                    {
                        MessageBox.Show("Không thể ghi được file báo biểu.", "Lỗi");
                    }
                }

                #endregion
            }
        }
Ejemplo n.º 17
0
        public void MovePlayer(object sender, EventArgs e)
        {
            counter++;
            lbl_Counter.Text = counter.ToString();

            // Yönü bul
            // Gidilecek yönü kontrol et

            // eski
            //var box = infoList.Where(i => i.X == playerPosition.X && i.Y == playerPosition.Y).FirstOrDefault();
            //if (box == null) throw new Exception("WTF");

            ucBox old = boxList[playerPosition.Y, playerPosition.X];

            // bunu eskiline getir

            //Hızı eski haline çevir
            timer.Interval = 300;

            int x     = playerPosition.X;
            int y     = playerPosition.Y;
            int old_x = playerPosition.X;
            int old_y = playerPosition.Y;

            switch (playa.Yon)
            {
            case Direction.Top:
                x = x - 1;
                break;

            case Direction.Right:
                y = y + 1;
                break;

            case Direction.Down:
                x = x + 1;
                break;

            case Direction.Left:
                y = y - 1;
                break;

            case Direction.Stop:
                playerPosition.X = 0;
                playerPosition.Y = 0;
                //Duvara çarptığında bir tepki ver
                break;

            default:
                break;
            }


            // yeni
            try
            {
                ucBox yeni = boxList[y, x];

                if (yeni.MapChar == 'F' || playerPosition.X == maxY)

                {
                    timer.Interval = 100000;

                    DialogResult result = MessageBox.Show("You Won!!" + "\n" + "Your Soccer is :" + (health * 100 - (counter * 5)) + "\n" + "Do you wanna next game? ", "You Won!", MessageBoxButtons.YesNoCancel);
                    if (result == DialogResult.Yes)
                    {
                        NewMap();
                    }
                    else if (result == DialogResult.No)

                    {
                        Environment.Exit(0);
                    }
                    else if (result == DialogResult.Cancel)
                    {
                        //code for Cancel
                    }
                }
                else if (yeni.MapChar == '0' || playerPosition.X >= maxY || playerPosition.Y >= maxX)
                {
                    health--;
                    //Eğer can düştüyse Mesajı göster ve diğer hamle yapılana kadar oyunu yavaşlat.
                    //Tekrar tekrar duvara çar
                    timer.Interval = 1400;
                    AutoClosingMessageBox.Show("You hit the wall!" + "\n" + "Your health is :" + health, "Warning!", 1300);

                    #region Duvara carptıktan sonrası
                    // Duvara sürekli çarpmasını engelle
                    if (playa.Yon == Direction.Down)
                    {
                        playa.Yon = Direction.Top;
                    }
                    else if (playa.Yon == Direction.Left)
                    {
                        playa.Yon = Direction.Right;
                    }
                    else if (playa.Yon == Direction.Right)
                    {
                        playa.Yon = Direction.Left;
                    }
                    else
                    {
                        playa.Yon = Direction.Down;
                    }

                    timer.Interval = 500;
                    #endregion

                    if (health == 0)
                    {
                        timer.Interval = 1000000;

                        DialogResult result = MessageBox.Show("You lost the game!" + "\n" + "Do you wanna new game? ", "Game is over!", MessageBoxButtons.YesNoCancel);
                        if (result == DialogResult.Yes)
                        {
                            EndGame();
                        }
                        else if (result == DialogResult.No)

                        {
                            Environment.Exit(0);
                        }
                        else if (result == DialogResult.Cancel)
                        {
                        }
                    }
                }



                //else if ( playerPosition.X < 0 || playerPosition.Y < 0 || playerPosition.X >= maxY-2 || playerPosition.Y >= maxX-1 )
                //    EndGame();
                else
                {
                    playerPosition.X = x;
                    playerPosition.Y = y;

                    var temp = yeni.BackColor;
                    yeni.BackColor = Color.IndianRed;
                    old.BackColor  = temp;
                    old.SetPicture(null);

                    yeni.SetPicture(GetPlayerImage());
                }
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
Ejemplo n.º 18
0
        private void btnThem_Click(object sender, EventArgs e)
        {
            if (SqlDataAccessHelper.TestConnection(SqlDataAccessHelper.ConnectionString) == false)
            {
                AutoClosingMessageBox.Show("Mất kết nối với CSDL. Vui lòng thử lại sau.", "Lỗi", 2000);
                return;
            }

            IsReload = true;

            #region lấy thông tin

            var timespanGioVao = dtpVao.Value.TimeOfDay;
            var timespanGioRaa = dtpRaa.Value.TimeOfDay;
            var lydo           = (cbLyDo.SelectedItem != null) ? cbLyDo.SelectedItem.ToString() : cbLyDo.SelectedText;
            var ghichu         = tbGhiChu.Text;

            #endregion

            var tempstring = radGioVao.Checked ? "vào" : "ra";
            var temptime   = (radGioVao.Checked) ? dtpVao.Value : dtpRaa.Value;
            if (dgrdDSGioVaoRa.SelectedRows.Count == 0)
            {
                return;
            }

            #region hỏi lại trước khi thêm

            if (MessageBox.Show(string.Format(Resources.xacNhanThemGioHangLoat, tempstring, temptime.ToString("H:mm")),
                                Resources.capXacNhan, MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            #endregion

            #region lấy ds các giờ vào ra, group lại theo từng nhân viên để thực hiện thêm 1 loạt rồi sau đó xử lý tính toán lại checkinout và ngày công

            IEnumerable <DataGridViewRow> dataGridViewRows = dgrdDSGioVaoRa.SelectedRows.Cast <DataGridViewRow>();
            var arrRecord = (from row in dataGridViewRows
                             let nv = (cUserInfo)(((DataRowView)row.DataBoundItem).Row["cUserInfo"])
                                      let cChkInOut = (cChkInOut)(((DataRowView)row.DataBoundItem).Row["cChkInOut"])
                                                      let ngay = (DateTime)(((DataRowView)row.DataBoundItem).Row["TimeStrNgay"])
                                                                 select new { nhanvien = nv, CIO = cChkInOut, Ngay = ngay }).GroupBy(o => o.nhanvien).ToList();

            #endregion

            var ds_raa3_vao1     = new List <cChk>();
            var DS_Check_KoHopLe = new List <cChk>();
            foreach (var group in arrRecord)
            {
                var nhanvien = group.Key;
                foreach (var item in group)
                {
                    if (item.CIO.HaveINOUT == 1)
                    {
                        continue;                               // 1. bỏ qua các giờ đủ IO
                    }
                    if (radGioVao.Checked)                      //2. thêm I cho O kv
                    {
                        if (item.CIO.HaveINOUT == -2)
                        {
                            var giovao = item.Ngay.Add(timespanGioVao);
                            if (giovao > item.CIO.Raa.Time)
                            {
                                giovao = giovao.AddDays(-1d);                                                        // trừ đi 1 ngày nếu (giờ vào thêm) > giờ ra
                            }
                            var checkinn = new cChkInn_A {
                                IsEdited = 1, MaCC = item.nhanvien.MaCC, Type = "I", Time = giovao, Source = "PC", MachineNo = 21, PhucHoi = new cPhucHoi {
                                    Them = true, IDGioGoc = -1, Xoaa = false
                                }
                            };
                            XL.ThemGioChoNV(checkinn, item.nhanvien, XL2.currUserID, lydo, ghichu);
                        }
                    }
                    else
                    {
                        if (item.CIO.HaveINOUT == -1)                          //3. thêm O cho I kr
                        {
                            var gioraa = item.Ngay.Add(timespanGioRaa);
                            if (gioraa < item.CIO.Vao.Time)
                            {
                                gioraa = gioraa.AddDays(1d);                                                        // cộng thêm 1 ngày nếu (giờ vào thêm) > giờ ra
                            }
                            var checkout = new cChkOut_A()
                            {
                                IsEdited = 1, MaCC = item.nhanvien.MaCC, Type = "O", Time = gioraa, Source = "PC", MachineNo = 22, PhucHoi = new cPhucHoi {
                                    Them = true, IDGioGoc = -1, Xoaa = false
                                }
                            };
                            XL.ThemGioChoNV(checkout, item.nhanvien, XL2.currUserID, lydo, ghichu);
                        }
                    }
                }

                XL.SapXepDS_Check(new[] { nhanvien.DS_Check_A });

                XL.LoaiBoCheckCungLoaiTrong30phut(nhanvien.DS_Check_A, nhanvien.DS_Check_KoHopLe);
                XL.GhepCIO_A(nhanvien.DS_Check_A, nhanvien.DS_CIO_A);
                XL.LoaiBoCIOKoHopLe(nhanvien.DS_CIO_A, nhanvien.DS_Check_A, nhanvien.DS_Check_KoHopLe);
                if (nhanvien.DS_Check_KoHopLe.Count > 0)
                {
                    DS_Check_KoHopLe.AddRange(nhanvien.DS_Check_KoHopLe);
                    nhanvien.DS_Check_KoHopLe.Clear();
                }

                XL.XetCa_CIO_A(nhanvien.DS_CIO_A, nhanvien.LichTrinhLV.DSCa, ds_raa3_vao1, nhanvien.DS_Check_A);
                XL.TronDS_CIO_A_V(nhanvien.DS_CIO_A, nhanvien.DS_CIO_V, nhanvien.DSVaoRa);
                XL.TinhCongTheoNgay(nhanvien.DSVaoRa, nhanvien.NgayCongBD_Bef2D, nhanvien.NgayCongKT_Aft2D, nhanvien.DSVang, nhanvien.DSNgayCong, nhanvien.MacDinhTinhPC50);
                XL.TinhLaiPhuCapTC(nhanvien.DSXNPhuCap50, nhanvien.DSNgayCong);
                XL.TinhLaiPhuCapDB(nhanvien.DSXNPhuCapDB, nhanvien.DSNgayCong);
            }
            if (DS_Check_KoHopLe.Count > 0)
            {
                DAL.LoaiGioLienQuan(DS_Check_KoHopLe);
            }
            if (ds_raa3_vao1.Count > 0)
            {
                DAL.ThemGio_ra3_vao1(ds_raa3_vao1);
            }

            loadGrid();
        }
Ejemplo n.º 19
0
        private void frmPrint_Load(object sender, EventArgs e)
        {
            try
            {
                pictureBox1.Visible   = true;
                pictureBox1.Width     = this.Width;
                pictureBox1.BackColor = this.BackColor;
                pictureBox1.Bounds    = new Rectangle(this.Width * 25 / 100, this.Height * 25 / 100, this.Width / 2, this.Height * 1 / 20);

                objFL.objCompany = ObjBLFD.ObjCompany;
                bool validflg = true;

                objiREPORT.HTREPORT  = HTFilter;
                objiREPORT.ACTIVE_BL = ObjBLFD;
                MethodInfo methodInfo = typeof(iREPORT).GetMethod("ReportPreview");
                validflg = bool.Parse(methodInfo.Invoke(objiREPORT, null).ToString().Trim());
                if (validflg)
                {
                    HTFilter = objiREPORT.HTREPORT;
                }

                if (flgDocorReport)
                {
                    DataSet ds = objFL.REPORT_TRANSACTION(tran_id, tran_cd, sp_name);
                    if (ds != null && ds.Tables.Count != 0 && ds.Tables[0].Rows.Count != 0)
                    {
                        doc = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                        doc.Load(AppDomain.CurrentDomain.BaseDirectory + objIni.GetKeyFieldValue("SQL", "initial catalog") + @"\" + rep_nm + ".rpt");
                        doc.SetDataSource(ds.Tables[0]);
                        //if (objLicense.License_code == "sZLKa7BcYsepmYbILRVBlg==")
                        if (ObjBLFD.ObjLoginUser != null && (ObjBLFD.ObjLoginUser.License_type == "SUPPORT LICENSE" || ObjBLFD.ObjLoginUser.License_type == "DEMO LICENSE"))
                        {
                            Report_Modification(doc);
                        }

                        Type           t = typeof(Company);
                        PropertyInfo[] publicFieldInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);

                        ParameterFieldDefinitions crParameterdef;
                        crParameterdef = doc.DataDefinition.ParameterFields;
                        foreach (PropertyInfo field in publicFieldInfos)
                        {
                            foreach (ParameterFieldDefinition def in crParameterdef)
                            {
                                if (null != field)
                                {
                                    if (def.Name.Equals("ORG." + field.Name.ToLower()))                                                                                                                   // check if parameter exists in report
                                    {
                                        doc.SetParameterValue("ORG." + field.Name.ToLower(), field.GetValue(ObjBLFD.ObjCompany, null) == null ? string.Empty : field.GetValue(ObjBLFD.ObjCompany, null)); // set the parameter value in the report
                                    }
                                }
                            }
                        }

                        string  strApproval = string.Empty;
                        DataSet dsetTable1  = objDL_ADAPTER.dsquery("select code,Main_tbl_nm,Approve_tbl_nm,isReqAuthority from tran_set where isApprove=1 and tran_type='Transaction' and code='" + ObjBLFD.Code + "' and compid=" + ObjBLFD.ObjCompany.Compid);
                        if (dsetTable1 != null && dsetTable1.Tables.Count != 0 && dsetTable1.Tables[0].Rows.Count != 0)
                        {
                            DataSet dsetTable = new DataSet();
                            if (bool.Parse(dsetTable1.Tables[0].Rows[0]["isReqAuthority"] != null && dsetTable1.Tables[0].Rows[0]["isReqAuthority"].ToString() != "" ? dsetTable1.Tables[0].Rows[0]["isReqAuthority"].ToString() : "False"))
                            {
                                // dsetTable = objDL_ADAPTER.dsquery("select i_approved=case when(authorse_by='NOT APPLICABLE') then 1 else i_approved end from " + ObjBLFD.Main_tbl_nm + " main_tbl inner join tran_set on main_tbl.tran_cd=tran_set.code where tran_set.isApprove=1 and tran_set.tran_type='Transaction' and " + ObjBLFD.Primary_id + "='" + tran_id + "' and tran_set.code='" + ObjBLFD.Code + "' and tran_set.compid=" + ObjBLFD.ObjCompany.Compid);
                                dsetTable = objDL_ADAPTER.dsquery("select i_approved=case when(authorse_by='NOT APPLICABLE') then 'True' else i_approved end from " + ObjBLFD.Main_tbl_nm + " main_tbl where " + ObjBLFD.Primary_id + "='" + tran_id + "' and main_tbl.tran_cd='" + ObjBLFD.Code + "' and main_tbl.compid=" + ObjBLFD.ObjCompany.Compid);
                            }
                            else
                            {
                                //dsetTable = objDL_ADAPTER.dsquery("select i_approved from " + ObjBLFD.Main_tbl_nm + " main_tbl inner join tran_set on main_tbl.tran_cd=tran_set.code where tran_set.isApprove=1 and tran_set.tran_type='Transaction' and " + ObjBLFD.Primary_id + "='" + tran_id + "' and tran_set.code='" + ObjBLFD.Code + "' and tran_set.compid=" + ObjBLFD.ObjCompany.Compid);
                                dsetTable = objDL_ADAPTER.dsquery("select i_approved from " + ObjBLFD.Main_tbl_nm + " main_tbl where " + ObjBLFD.Primary_id + "='" + tran_id + "' and main_tbl.code='" + ObjBLFD.Code + "' and main_tbl.compid=" + ObjBLFD.ObjCompany.Compid);
                            }
                            if (dsetTable != null && dsetTable.Tables.Count != 0 && dsetTable.Tables[0].Rows.Count != 0)
                            {
                                if (dsetTable.Tables[0].Rows[0]["i_approved"] != null && dsetTable.Tables[0].Rows[0]["i_approved"].ToString() != "" && bool.Parse(dsetTable.Tables[0].Rows[0]["i_approved"].ToString()))
                                {
                                    strApproval = "APPROVE";
                                }
                                else
                                {
                                    strApproval = "PENDING";
                                }
                            }
                            foreach (ParameterFieldDefinition def in crParameterdef)
                            {
                                if (def.Name.Equals("approval"))                    // check if parameter exists in report
                                {
                                    doc.SetParameterValue("approval", strApproval); // set the parameter value in the report
                                }
                            }
                        }
                        else
                        {
                            foreach (ParameterFieldDefinition def in crParameterdef)
                            {
                                if (def.Name.Equals("approval"))           // check if parameter exists in report
                                {
                                    doc.SetParameterValue("approval", ""); // set the parameter value in the report
                                }
                            }
                        }
                        crystalReportViewer1.ReportSource = doc;
                        //crystalReportViewer1.RefreshReport();
                        //  this.TopMost = true;
                        crystalReportViewer1.Visible = true;
                    }
                    else
                    {
                        AutoClosingMessageBox.Show("error in report", "Error");
                    }
                }
                else
                {
                    DataSet ds = objFL.REPORT_SHOW(this.HTFilter, ObjBLFD.ObjCompany.Compid.ToString());
                    if (ds != null)
                    {
                        CrystalDecisions.CrystalReports.Engine.ReportDocument doc = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                        doc.Load(AppDomain.CurrentDomain.BaseDirectory + objIni.GetKeyFieldValue("SQL", "initial catalog") + @"\" + rep_nm + ".rpt");
                        doc.SetDataSource(ds.Tables[0]);
                        //  if (objLicense.License_code == "sZLKa7BcYsepmYbILRVBlg==")
                        if (ObjBLFD.ObjLoginUser != null && (ObjBLFD.ObjLoginUser.License_type == "SUPPORT LICENSE" || ObjBLFD.ObjLoginUser.License_type == "DEMO LICENSE"))
                        {
                            Report_Modification(doc);
                        }

                        Type           t = typeof(Company);
                        PropertyInfo[] publicFieldInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);

                        ParameterFieldDefinitions crParameterdef;
                        crParameterdef = doc.DataDefinition.ParameterFields;
                        foreach (PropertyInfo field in publicFieldInfos)
                        {
                            foreach (ParameterFieldDefinition def in crParameterdef)
                            {
                                if (null != field)
                                {
                                    if (def.Name.Equals("ORG." + field.Name.ToLower()))                                                                                                                   // check if parameter exists in report
                                    {
                                        doc.SetParameterValue("ORG." + field.Name.ToLower(), field.GetValue(ObjBLFD.ObjCompany, null) == null ? string.Empty : field.GetValue(ObjBLFD.ObjCompany, null)); // set the parameter value in the report
                                    }
                                }
                            }
                        }
                        crystalReportViewer1.ReportSource = doc;


                        //crystalReportViewer1.BackgroundImage = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + @"IMAGE\setting.jpg");
                        //crystalReportViewer1.BackgroundImageLayout = ImageLayout.Stretch;
                        //crystalReportViewer1.DisplayBackgroundEdge = true;
                        crystalReportViewer1.Visible = true;
                    }
                    else
                    {
                        AutoClosingMessageBox.Show("error in report", "Error");
                    }
                }
                ucToolBar1.Width1 = this.Width;
                AddThemesToTitleBar((Form)this, ucToolBar1, ObjBLFD, "Report");
                #region 2.0
                if (HTFilter != null && HTFilter.Count != 0)
                {
                    if (HTFilter.Contains("rep_gr"))
                    {
                        ucToolBar1.Titlebar = HTFilter["rep_gr"].ToString() + " (" + rep_nm + ".rpt)";
                    }
                    else
                    {
                        ucToolBar1.Titlebar = HTFilter["rep_nm"].ToString() + " (" + rep_nm + ".rpt)";
                    }
                }
                else
                {
                    ucToolBar1.Titlebar = rep_nmshow + " (" + rep_nm + ".rpt)";
                }
                #endregion 2.0
                this.TopMost = true;
            }
            catch (Exception ex)
            {
                AutoClosingMessageBox.Show("Fields not Exist", "Error");
                this.TopMost        = false;
                pictureBox1.Visible = false;
            }
            pictureBox1.Visible = false;
            //this.TopMost = false;
        }
Ejemplo n.º 20
0
        private void btnSuaa_Click(object sender, EventArgs e)
        {
            if (SqlDataAccessHelper.TestConnection(SqlDataAccessHelper.ConnectionString) == false)
            {
                AutoClosingMessageBox.Show("Mất kết nối với CSDL. Vui lòng thử lại sau.", "Lỗi", 2000);
                return;
            }

            IsReload = true;
            var timespanGioVao = dtpVao.Value.TimeOfDay;
            var timespanGioRaa = dtpRaa.Value.TimeOfDay;
            var lydo           = (cbLyDo.SelectedItem != null) ? cbLyDo.SelectedItem.ToString() : cbLyDo.SelectedText;
            var ghichu         = tbGhiChu.Text;

            if (dgrdDSGioVaoRa.SelectedRows.Count == 0)
            {
                return;
            }

            #region hỏi lại trước khi sửa

            if (radGioVao.Checked)
            {
                if (MessageBox.Show(string.Format(Resources.xacNhanSuaGioHangLoat, "vào", dtpVao.Value.ToString("H:mm")),
                                    Resources.capXacNhan, MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
            }
            else
            {
                if (MessageBox.Show(string.Format(Resources.xacNhanSuaGioHangLoat, "ra", dtpRaa.Value.ToString("H:mm")),
                                    Resources.capXacNhan, MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    return;
                }
            }

            #endregion

            var flagThongBao = false;             // flag thông báo không cho phép sửa giờ đã CN
            IEnumerable <DataGridViewRow> dataGridViewRows = dgrdDSGioVaoRa.SelectedRows.Cast <DataGridViewRow>();
            var arrRecord = (from row in dataGridViewRows
                             let nv = (cUserInfo)(((DataRowView)row.DataBoundItem).Row["cUserInfo"])
                                      let cChkInOut = (cChkInOut)(((DataRowView)row.DataBoundItem).Row["cChkInOut"])
                                                      let ngay = (DateTime)(((DataRowView)row.DataBoundItem).Row["TimeStrNgay"])
                                                                 select new { nhanvien = nv, CIO = cChkInOut, Ngay = ngay }).GroupBy(o => o.nhanvien).ToList();
            var ds_raa3_vao1     = new List <cChk>();
            var DS_Check_KoHopLe = new List <cChk>();
            foreach (var group in arrRecord)
            {
                var nhanvien = group.Key;
                foreach (var item in group)
                {
                    if (item.CIO.GetType() == typeof(cChkInOut_V))
                    {
                        flagThongBao = true;
                        continue;
                    }
                    if (radGioVao.Checked)
                    {
                        if (item.CIO.HaveINOUT == -2)
                        {
                            continue;
                        }
                        var giovao      = item.Ngay.Add(timespanGioVao);
                        var checkinnold = item.CIO.Vao;
                        var checkinnnew = new cChkInn_A {
                            MaCC    = nhanvien.MaCC, Type = "I", Time = giovao, Source = "PC", MachineNo = 21, IsEdited = 1,
                            PhucHoi = new cPhucHoi {
                                IDGioGoc = int.MaxValue, Them = checkinnold.PhucHoi.Them, Xoaa = checkinnold.PhucHoi.Xoaa
                            }
                        };
                        XL.SuaGioChoNV(checkinnold, checkinnnew, nhanvien, XL2.currUserID, lydo, ghichu);
                    }
                    else
                    {
                        if (item.CIO.HaveINOUT == -1)
                        {
                            continue;
                        }
                        var gioraa      = item.Ngay.Add(timespanGioRaa);
                        var checkoutold = item.CIO.Raa;
                        var checkoutnew = new cChkOut_A {
                            MaCC    = nhanvien.MaCC, Type = "O", Time = gioraa, Source = "PC", MachineNo = 22, IsEdited = 1,
                            PhucHoi = new cPhucHoi {
                                IDGioGoc = int.MaxValue, Them = checkoutold.PhucHoi.Them, Xoaa = checkoutold.PhucHoi.Xoaa
                            }
                        };
                        XL.SuaGioChoNV(checkoutold, checkoutnew, nhanvien, XL2.currUserID, lydo, ghichu);
                    }
                }
                XL.SapXepDS_Check(new[] { nhanvien.DS_Check_A });
                XL.LoaiBoCheckCungLoaiTrong30phut(nhanvien.DS_Check_A, nhanvien.DS_Check_KoHopLe);
                if (nhanvien.DS_Check_KoHopLe.Count > 0)
                {
                    DS_Check_KoHopLe.AddRange(nhanvien.DS_Check_KoHopLe);
                    nhanvien.DS_Check_KoHopLe.Clear();
                }

                XL.GhepCIO_A(nhanvien.DS_Check_A, nhanvien.DS_CIO_A);
                XL.LoaiBoCIOKoHopLe(nhanvien.DS_CIO_A, nhanvien.DS_Check_A, nhanvien.DS_Check_KoHopLe);
                XL.XetCa_CIO_A(nhanvien.DS_CIO_A, nhanvien.LichTrinhLV.DSCa, ds_raa3_vao1, nhanvien.DS_Check_A);
                XL.TronDS_CIO_A_V(nhanvien.DS_CIO_A, nhanvien.DS_CIO_V, nhanvien.DSVaoRa);
                XL.TinhCongTheoNgay(nhanvien.DSVaoRa, nhanvien.NgayCongBD_Bef2D, nhanvien.NgayCongKT_Aft2D, nhanvien.DSVang, nhanvien.DSNgayCong, nhanvien.MacDinhTinhPC50);
                XL.TinhLaiPhuCapTC(nhanvien.DSXNPhuCap50, nhanvien.DSNgayCong);
                XL.TinhLaiPhuCapDB(nhanvien.DSXNPhuCapDB, nhanvien.DSNgayCong);
            }
            if (DS_Check_KoHopLe.Count > 0)
            {
                DAL.LoaiGioLienQuan(DS_Check_KoHopLe);
            }
            if (ds_raa3_vao1.Count > 0)
            {
                DAL.ThemGio_ra3_vao1(ds_raa3_vao1);
            }

            loadGrid();
            if (flagThongBao)
            {
                AutoClosingMessageBox.Show("Không thể sửa các giờ đã xác nhận.", "Thông báo", 2000);
            }
        }
        private void vialValidation2()
        {
            bool isvialvalid2 = true;

            for (int i = 0; i < agregation2.Count; i++)
            {
                if (agregation2[i].Contains(tbVial2.Text))
                {
                    isvialvalid2 = false;
                    break;
                }
            }

            foreach (string items in agregation)
            {
                System.Console.WriteLine(items);
                if (items.Contains(tbVial2.Text))
                {
                    DataRow row = table2.NewRow();
                    row[0] = tbVial2.Text;
                    row[1] = "FAIL";
                    row[2] = DateTime.Now.ToLongDateString();
                    row[3] = DateTime.Now.ToLongTimeString();
                    table2.Rows.Add(row);
                    dataGridView2.DataSource = table2;
                    lblQty2.Text             = table2.Rows.Count.ToString();
                    tbVial2.Text             = "";
                    tbVial2.Enabled          = false;
                    vialLog2.Add(tbCarton2.Text + "&" + tbVial2.Text + "&" + "FAIL" + "&" + DateTime.Now.ToLongDateString() + "&" + DateTime.Now.ToLongTimeString());
                    vialvalidationLog2.Add(tbCarton2.Text + "&" + tbVial2.Text + "&" + "FAIL" + "&" + DateTime.Now.ToLongDateString() + "&" + DateTime.Now.ToLongTimeString());
                    tbVial2.Text  = "";
                    lblFail2.Text = vialvalidationLog2.Count.ToString();
                    gs1idvial2    = null;
                    isvialvalid2  = false;
                    break;
                }
            }

            if (isvialvalid2)
            {
                List <string> field = new List <string>();
                field.Add("gsonevialid");
                List <string> field2 = new List <string>();
                field2.Add("gsonevialid");
                string guid = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 6).ToUpper();

                if (cap2 == null)
                {
                    cap2 = bnumber2 + guid.PadLeft(3, '0');
                }
                if (db.selectList(field, "[vaccine]", "gsonevialid='" + tbVial2.Text + "' AND batchnumber='" + bnumber2 + "'AND isreject='1' AND flag='2'") != null)
                {
                    cap = cbProduct2.SelectedValue.ToString() + bnumber2 + guid.PadLeft(3, '0');
                    Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
                    agregation2.Add("'" + tbVial2.Text + "'");
                    DataRow row = table2.NewRow();
                    row[0] = tbVial2.Text;
                    row[1] = "PASS";
                    row[2] = DateTime.Now.ToLongDateString();
                    row[3] = DateTime.Now.ToLongTimeString();
                    table2.Rows.Add(row);
                    dataGridView2.DataSource = table2;
                    dataGridView2.Sort(dataGridView2.Columns[3], ListSortDirection.Descending);
                    vialLog2.Add(tbCarton2.Text + "&" + tbVial2.Text + "&" + "Pass" + "&" + DateTime.Now.ToLongDateString() + "&" + DateTime.Now.ToLongTimeString());
                    lblQty2.Text    = table2.Rows.Count.ToString();
                    lblPass2.Text   = agregation2.Count.ToString();
                    tbVial2.Text    = "";
                    tbVial2.Enabled = false;
                    gs1idvial2      = null;

                    if (agregation2.Count == int.Parse(_comboProduct2[cbProduct2.SelectedIndex].Qty))
                    {
                        tbVial2.Enabled = false;
                        int    i = 0;
                        string aggregationWhere = String.Join(",", agregation2.ToArray());

                        if (db.aggregationVial(aggregationWhere, tbCarton2.Text, infeedid2))
                        {
                            agregation2.Clear();
                            vialvalidationLog2.Clear();
                            lblQty2.Text = "";
                            table2.Rows.Clear();
                            Dictionary <string, string> syslog = new Dictionary <string, string>();
                            syslog.Add("eventType", "12");
                            syslog.Add("eventName", "Aggregation GS1 ID Carton " + tbCarton1.Text + " Batchnumber " + tbBatchnumber1.Text);
                            syslog.Add("[from]", "Packaging");
                            syslog.Add("uom", "Carton");
                            syslog.Add("userid", adminid);
                            db.insert(syslog, "[system_log]");
                            log.LogWriter("Aggregation GS1 ID Carton " + tbCarton2.Text + " Batchnumber " + tbBatchnumber2.Text + " Status Success");
                            lblQtyBatch2.Text = db.selectCountPass(bnumber2).ToString();
                            tbCarton2.Text    = "";
                            lblPass2.Text     = "0";
                            lblFail2.Text     = "0";
                            lblQty2.Text      = "0";
                            cartonvalidated2  = false;
                            gs1carton2        = null;
                            gs1idvial2        = null;
                            tbCarton2.Enabled = false;
                        }
                        else
                        {
                            AutoClosingMessageBox.Show("Cannot Connect To Database Server!", "Error", 3000);
                        }
                    }
                }
                else
                {
                    DataRow row = table2.NewRow();
                    row[0] = tbVial2.Text;
                    row[1] = "FAIL";
                    row[2] = DateTime.Now.ToLongDateString();
                    row[3] = DateTime.Now.ToLongTimeString();
                    table2.Rows.Add(row);
                    dataGridView2.DataSource = table2;
                    lblQty2.Text             = table2.Rows.Count.ToString();
                    tbVial2.Text             = "";
                    tbVial2.Enabled          = false;
                    vialLog2.Add(tbCarton2.Text + "&" + tbVial2.Text + "&" + "FAIL" + "&" + DateTime.Now.ToLongDateString() + "&" + DateTime.Now.ToLongTimeString());
                    vialvalidationLog2.Add(tbCarton2.Text + "&" + tbVial2.Text + "&" + "FAIL" + "&" + DateTime.Now.ToLongDateString() + "&" + DateTime.Now.ToLongTimeString());
                    tbVial2.Text  = "";
                    lblFail2.Text = vialvalidationLog2.Count.ToString();
                    gs1idvial2    = null;
                }
            }
            else
            {
                tbVial2.Text    = "";
                tbVial2.Enabled = false;
                gs1idvial2      = null;
            }
        }
Ejemplo n.º 22
0
        private void btnXoaGioRaa_Click(object sender, EventArgs e)
        {
            if (SqlDataAccessHelper.TestConnection(SqlDataAccessHelper.ConnectionString) == false)
            {
                AutoClosingMessageBox.Show("Mất kết nối với CSDL. Vui lòng thử lại sau.", "Lỗi", 2000);
                return;
            }

            IsReload = true;
            var lydo   = cbLyDo.SelectedText;
            var ghichu = tbGhiChu.Text;

            #region hỏi lại ttrước khi xoá

            if (MessageBox.Show(string.Format(Resources.xacNhanXoaGioHangLoat, "ra"), Resources.capXacNhan, MessageBoxButtons.YesNo) == DialogResult.No)
            {
                return;
            }

            #endregion


            if (dgrdDSGioVaoRa.SelectedRows.Count == 0)
            {
                return;
            }
            var flagThongBao = false;            // thông báo ko được xoá giờ đãn XN

            IEnumerable <DataGridViewRow> dataGridViewRows = dgrdDSGioVaoRa.SelectedRows.Cast <DataGridViewRow>();
            var arrRecord = (from row in dataGridViewRows
                             let nv = (cUserInfo)(((DataRowView)row.DataBoundItem).Row["cUserInfo"])
                                      let cChkInOut = (cChkInOut)(((DataRowView)row.DataBoundItem).Row["cChkInOut"])
                                                      let ngay = (DateTime)(((DataRowView)row.DataBoundItem).Row["TimeStrNgay"])
                                                                 select new { nhanvien = nv, CIO = cChkInOut, Ngay = ngay }).GroupBy(o => o.nhanvien).ToList();

            var ds_raa3_vao1     = new List <cChk>();
            var DS_Check_KoHopLe = new List <cChk>();
            foreach (var groupByNV in arrRecord)
            {
                var nhanvien = groupByNV.Key;
                foreach (var row in groupByNV)
                {
                    if (row.CIO.GetType() == typeof(cChkInOut_V))
                    {
                        flagThongBao = true;
                        continue;
                    }

                    if (row.CIO.HaveINOUT == -1)
                    {
                        continue;
                    }
                    var checkout = row.CIO.Raa;
                    XL.XoaGioChoNV(checkout, row.nhanvien, XL2.currUserID, lydo, ghichu);
                }
                XL.LoaiBoCheckCungLoaiTrong30phut(nhanvien.DS_Check_A, nhanvien.DS_Check_KoHopLe);
                XL.GhepCIO_A(nhanvien.DS_Check_A, nhanvien.DS_CIO_A);
                XL.LoaiBoCIOKoHopLe(nhanvien.DS_CIO_A, nhanvien.DS_Check_A, nhanvien.DS_Check_KoHopLe);
                if (nhanvien.DS_Check_KoHopLe.Count > 0)
                {
                    DS_Check_KoHopLe.AddRange(nhanvien.DS_Check_KoHopLe);
                    nhanvien.DS_Check_KoHopLe.Clear();
                }

                XL.XetCa_CIO_A(nhanvien.DS_CIO_A, nhanvien.LichTrinhLV.DSCa, ds_raa3_vao1, nhanvien.DS_Check_A);
                XL.TronDS_CIO_A_V(nhanvien.DS_CIO_A, nhanvien.DS_CIO_V, nhanvien.DSVaoRa);
                XL.TinhCongTheoNgay(nhanvien.DSVaoRa, nhanvien.NgayCongBD_Bef2D, nhanvien.NgayCongKT_Aft2D, nhanvien.DSVang, nhanvien.DSNgayCong, nhanvien.MacDinhTinhPC50);
                XL.TinhLaiPhuCapTC(nhanvien.DSXNPhuCap50, nhanvien.DSNgayCong);
                XL.TinhLaiPhuCapDB(nhanvien.DSXNPhuCapDB, nhanvien.DSNgayCong);
            }
            if (DS_Check_KoHopLe.Count > 0)
            {
                DAL.LoaiGioLienQuan(DS_Check_KoHopLe);
            }
            if (ds_raa3_vao1.Count > 0)
            {
                DAL.ThemGio_ra3_vao1(ds_raa3_vao1);
            }

            loadGrid();


            if (flagThongBao)
            {
                AutoClosingMessageBox.Show("Không thể xoá các giờ đã xác nhận.", "Thông báo", 2000);
            }
        }
Ejemplo n.º 23
0
        private void ConvertToPdf(string tran_id, string tran_cd, string sp_nm, string rep_nm, string rep_desc)
        {
            CrystalDecisions.Windows.Forms.CrystalReportViewer crystalReportViewer1 = new CrystalDecisions.Windows.Forms.CrystalReportViewer();
            DataSet ds = objFLRep.REPORT_TRANSACTION(tran_id, tran_cd, sp_nm);

            CrystalDecisions.CrystalReports.Engine.ReportDocument doc;
            if (ds != null && ds.Tables.Count != 0 && ds.Tables[0].Rows.Count != 0)
            {
                doc = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                doc.Load(AppDomain.CurrentDomain.BaseDirectory + objIni.GetKeyFieldValue("SQL", "initial catalog") + @"\" + rep_nm + ".rpt");
                doc.SetDataSource(ds.Tables[0]);
                //if (objLicense.License_code == "sZLKa7BcYsepmYbILRVBlg==")
                if (ObjBLFD.ObjLoginUser != null && (ObjBLFD.ObjLoginUser.License_type == "SUPPORT LICENSE" || ObjBLFD.ObjLoginUser.License_type == "DEMO LICENSE"))
                {
                    Report_Modification(doc);
                }

                Type           t = typeof(Company);
                PropertyInfo[] publicFieldInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public);

                ParameterFieldDefinitions crParameterdef;
                crParameterdef = doc.DataDefinition.ParameterFields;
                foreach (PropertyInfo field in publicFieldInfos)
                {
                    foreach (ParameterFieldDefinition def in crParameterdef)
                    {
                        if (null != field)
                        {
                            if (def.Name.Equals("ORG." + field.Name.ToLower()))                                                                                                                   // check if parameter exists in report
                            {
                                doc.SetParameterValue("ORG." + field.Name.ToLower(), field.GetValue(ObjBLFD.ObjCompany, null) == null ? string.Empty : field.GetValue(ObjBLFD.ObjCompany, null)); // set the parameter value in the report
                            }
                        }
                    }
                }
                string strApproval = string.Empty;
                //DataSet dsetTable = objDL_ADAPTER.dsquery("select i_approved from " + ObjBLFD.Main_tbl_nm + " main_tbl inner join tran_set on main_tbl.tran_cd=tran_set.code where tran_set.isApprove=1 and tran_set.tran_type='Transaction' and "+objBLFD.Primary_id+"='" + tran_id + "' and tran_set.code='" + ObjBLFD.Code + "' and tran_set.compid=" + ObjBLFD.ObjCompany.Compid);
                //if (dsetTable != null && dsetTable.Tables.Count != 0 && dsetTable.Tables[0].Rows.Count != 0)
                //{
                //    if (dsetTable.Tables[0].Rows[0]["i_approved"] != null && dsetTable.Tables[0].Rows[0]["i_approved"].ToString() != "" && bool.Parse(dsetTable.Tables[0].Rows[0]["i_approved"].ToString()))
                //    {
                //        strApproval = "APPROVE";
                //    }
                //    else
                //    {
                //        strApproval = "PENDING";
                //    }
                //}
                DataSet dsetTable1 = objDL_ADAPTER.dsquery("select code,Main_tbl_nm,Approve_tbl_nm,isReqAuthority from tran_set where isApprove=1 and tran_type='Transaction' and code='" + ObjBLFD.Code + "' and compid=" + ObjBLFD.ObjCompany.Compid);
                if (dsetTable1 != null && dsetTable1.Tables.Count != 0 && dsetTable1.Tables[0].Rows.Count != 0)
                {
                    DataSet dsetTable = new DataSet();
                    if (bool.Parse(dsetTable1.Tables[0].Rows[0]["isReqAuthority"] != null && dsetTable1.Tables[0].Rows[0]["isReqAuthority"].ToString() != "" ? dsetTable1.Tables[0].Rows[0]["isReqAuthority"].ToString() : "False"))
                    {
                        // dsetTable = objDL_ADAPTER.dsquery("select i_approved=case when(authorse_by='NOT APPLICABLE') then 1 else i_approved end from " + ObjBLFD.Main_tbl_nm + " main_tbl inner join tran_set on main_tbl.tran_cd=tran_set.code where tran_set.isApprove=1 and tran_set.tran_type='Transaction' and " + ObjBLFD.Primary_id + "='" + tran_id + "' and tran_set.code='" + ObjBLFD.Code + "' and tran_set.compid=" + ObjBLFD.ObjCompany.Compid);
                        dsetTable = objDL_ADAPTER.dsquery("select i_approved=case when(authorse_by='NOT APPLICABLE') then 'True' else i_approved end from " + ObjBLFD.Main_tbl_nm + " main_tbl where " + ObjBLFD.Primary_id + "='" + tran_id + "' and main_tbl.tran_cd='" + ObjBLFD.Code + "' and main_tbl.compid=" + ObjBLFD.ObjCompany.Compid);
                    }
                    else
                    {
                        //dsetTable = objDL_ADAPTER.dsquery("select i_approved from " + ObjBLFD.Main_tbl_nm + " main_tbl inner join tran_set on main_tbl.tran_cd=tran_set.code where tran_set.isApprove=1 and tran_set.tran_type='Transaction' and " + ObjBLFD.Primary_id + "='" + tran_id + "' and tran_set.code='" + ObjBLFD.Code + "' and tran_set.compid=" + ObjBLFD.ObjCompany.Compid);
                        dsetTable = objDL_ADAPTER.dsquery("select i_approved from " + ObjBLFD.Main_tbl_nm + " main_tbl where " + ObjBLFD.Primary_id + "='" + tran_id + "' and main_tbl.code='" + ObjBLFD.Code + "' and main_tbl.compid=" + ObjBLFD.ObjCompany.Compid);
                    }
                    if (dsetTable != null && dsetTable.Tables.Count != 0 && dsetTable.Tables[0].Rows.Count != 0)
                    {
                        if (dsetTable.Tables[0].Rows[0]["i_approved"] != null && dsetTable.Tables[0].Rows[0]["i_approved"].ToString() != "" && bool.Parse(dsetTable.Tables[0].Rows[0]["i_approved"].ToString()))
                        {
                            strApproval = "APPROVE";
                        }
                        else
                        {
                            strApproval = "PENDING";
                        }
                    }
                }
                foreach (ParameterFieldDefinition def in crParameterdef)
                {
                    if (def.Name.Equals("approval"))                    // check if parameter exists in report
                    {
                        doc.SetParameterValue("approval", strApproval); // set the parameter value in the report
                    }
                }
                crystalReportViewer1.ReportSource = doc;
                crystalReportViewer1.Visible      = false;

                CrystalDecisions.Shared.ExportOptions CrExportOptions;
                DiskFileDestinationOptions            CrDiskFileDestinationOptions = new DiskFileDestinationOptions();
                PdfRtfWordFormatOptions CrFormatTypeOptions = new PdfRtfWordFormatOptions();

                CrExportOptions = doc.ExportOptions;
                {
                    CrExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;

                    CrDiskFileDestinationOptions.DiskFileName = AppDomain.CurrentDomain.BaseDirectory + objBLFD.ObjCompany.Db_nm + "\\FILES\\" + rep_desc.Replace(" ", "_") + tran_id + tran_cd + ".pdf";
                    CrExportOptions.ExportFormatType          = ExportFormatType.PortableDocFormat;

                    CrExportOptions.DestinationOptions = CrDiskFileDestinationOptions;
                    CrExportOptions.FormatOptions      = CrFormatTypeOptions;
                }
                doc.Export();

                if (_hashSendMailAttachements == null || !_hashSendMailAttachements.Contains(rep_nm.Replace(".rpt", "_") + tran_id + tran_cd))
                {
                    _hashSendMailAttachements[rep_nm.Replace(".rpt", "_") + tran_id + tran_cd] = AppDomain.CurrentDomain.BaseDirectory + objBLFD.ObjCompany.Db_nm + "\\FILES\\" + rep_desc.Replace(" ", "_") + tran_id + tran_cd + ".pdf";
                }
            }
            else
            {
                AutoClosingMessageBox.Show("error in report", "Error");
            }
        }
 private void ShowMessageBox([NotNull] string s)
 {
     AutoClosingMessageBox.Show(s, "Error in the Distributed Simulator", 15000 + (_rnd.Next(15) * 1000));
 }
Ejemplo n.º 25
0
        private void OpenButton_Click(object sender, RoutedEventArgs e)
        {
            var screen = new OpenFileDialog();

            if (screen.ShowDialog() == true)
            {
                try
                {
                    bitmap = new BitmapImage(new Uri(screen.FileName));
                }
                catch (System.NotSupportedException)
                {
                    MessageBox.Show("Please select the image file!", "WARING", MessageBoxButton.OK, MessageBoxImage.Warning);
                    OpenButton_Click(sender, e);
                    return;
                }
                Debug.WriteLine(screen.FileName);
                var orgImage = bitmap;
                originalImage.Source = new BitmapImage(new Uri(screen.FileName));

                imageWidth       = (int)fullImageWidth / 3;
                imageHeight      = (int)(fullImageWidth * bitmap.Height / bitmap.Width) / 3;
                mainFrame.Height = imageHeight * 3 + 15;
                var rng  = new Random();
                var pool = new List <int> {
                    1, 2, 3, 4, 5, 6, 7, 8
                };
                var pooli = new List <int> {
                    0, 1, 2, 0, 1, 2, 0, 1
                };
                var poolj = new List <int> {
                    0, 0, 0, 1, 1, 1, 2, 2
                };

                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        if (i != 2 || j != 2)
                        {
                            // Set vi tri

                            var k = rng.Next(pool.Count); // Chon ngau nhien mot chi muc trong pool

                            var cropped = new CroppedBitmap(bitmap, new Int32Rect(
                                                                (int)(pooli[k] * bitmap.PixelWidth / 3), (int)(poolj[k] * bitmap.PixelHeight / 3),
                                                                ((int)bitmap.PixelWidth / 3), ((int)bitmap.PixelHeight / 3)));

                            // Tao giao dien

                            var imageView = new Image();
                            imageView.Source = cropped;
                            imageView.Width  = imageWidth;
                            imageView.Height = imageHeight;
                            container.Children.Add(imageView);
                            //mageView.MouseEnter += new MouseEventHandler(Enter);
                            //imageView.MouseLeave += new MouseEventHandler(Leave);

                            Canvas.SetLeft(imageView, i * (imageWidth + padding));
                            Canvas.SetTop(imageView, j * (imageHeight + padding));

                            images[i, j] = imageView;
                            imgID[j, i]  = pool[k];

                            pool.RemoveAt(k);
                            pooli.RemoveAt(k);
                            poolj.RemoveAt(k);
                        }
                    }
                }


                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        //images[i,j].MouseEnter += new MouseEventHandler(Enter);
                        //images[i,j].MouseLeave += new MouseEventHandler(Leave);
                        Debug.Write(imgID[i, j]);
                    }
                    Debug.WriteLine("");
                }

                isOpenedImage = true;
            }

            MessageBoxResult res = MessageBox.Show("Are you ready?", "Start Game", MessageBoxButton.OK, MessageBoxImage.Question);

            if (res == MessageBoxResult.OK)
            {
                Debug.Write("1");
                AutoClosingMessageBox.Show("3", "Countdown", 1000);
                Debug.Write("2");
                AutoClosingMessageBox.Show("2", "Countdown", 1000);
                Debug.Write("3");
                AutoClosingMessageBox.Show("1", "Countdown", 1000);
                AutoClosingMessageBox.Show("START", "Countdown", 500);
                if (isRestart || isLoaded)
                {
                    time = 180;
                    Timer.Start();
                }
                else
                {
                    PlayTime();
                }
            }
        }
Ejemplo n.º 26
0
 public async void PerformCommand(SpeechRecognizedEventArgs e, AvailableCommandsForm form, SpeechRecognizer speechRecogniser, DictateSpeech dictateSpeech, Microsoft.CognitiveServices.Speech.SpeechRecognizer speechRecognizer)
 {
     UpdateCurrentProcess();
     try
     {
         SpeechUI.SendTextFeedback(e.Result, $"Recognised: {e.Result.Text} {e.Result.Confidence:P1}", true);
     }
     catch (Exception exception)
     {
         AutoClosingMessageBox.Show(exception.Message, "Error Sending feedback to speech recognition", 3000);
     }
     if (e.Result.Grammar.Name == "New with Space" && e.Result.Confidence > 0.6)
     {
         inputSimulator.Keyboard.TextEntry(" new ");
         inputSimulator.Keyboard.KeyDown(VirtualKeyCode.ESCAPE);
     }
     else if (e.Result.Grammar.Name == "Step Over" && e.Result.Confidence > 0.6)
     {
         inputSimulator.Keyboard.KeyDown(VirtualKeyCode.F10);
     }
     else if (e.Result.Grammar.Name == "Step Into" && e.Result.Confidence > 0.6)
     {
         inputSimulator.Keyboard.KeyDown(VirtualKeyCode.F11);
     }
     else if (e.Result.Grammar.Name == "Reset Code" && e.Result.Confidence > 0.6)
     {
         inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.SHIFT, VirtualKeyCode.F5);
     }
     else if (e.Result.Grammar.Name == "Use Dragon" && e.Result.Confidence > 0.6)
     {
         ToggleSpeechRecognitionListeningMode(inputSimulator);
         inputSimulator.Keyboard.KeyDown(VirtualKeyCode.ADD);
     }
     else if (e.Result.Grammar.Name == "Window Monitor Switch" && e.Result.Confidence > 0.6)
     {
         inputSimulator.Keyboard.ModifiedKeyStroke(windowAndShift, VirtualKeyCode.RIGHT);
     }
     else if (e.Result.Grammar.Name == "Select Line" && e.Result.Confidence > 0.6)
     {
         inputSimulator.Keyboard.KeyPress(VirtualKeyCode.HOME);
         inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.SHIFT, VirtualKeyCode.END);
     }
     else if (e.Result.Grammar.Name == "Mouse Down" && e.Result.Confidence > 0.6)
     {
         inputSimulator.Mouse.LeftButtonDown();
     }
     else if (e.Result.Grammar.Name == "Shutdown Windows" && e.Result.Confidence > 0.5)
     {
         CommandToBeConfirmed = e.Result.Grammar.Name;
         SetupConfirmationCommands(speechRecogniser, form);
     }
     else if (e.Result.Grammar.Name == "Restart Windows" && e.Result.Confidence > 0.5)
     {
         CommandToBeConfirmed = e.Result.Grammar.Name;
         SetupConfirmationCommands(speechRecogniser, form);
     }
     else if (e.Result.Grammar.Name == "Confirmed")
     {
         if (CommandToBeConfirmed == "Shutdown Windows")
         {
             Process.Start("shutdown", "/s /t 10");
         }
         else if (CommandToBeConfirmed == "Restart Windows")
         {
             Process.Start("shutdown", "/r /t 10");
         }
         PerformQuitApplicationCommand(e);
     }
     else if (e.Result.Grammar.Name == "Short Dictation" && e.Result.Confidence > 0.4)
     {
         await PerformShortDictation(e, form, dictateSpeech, speechRecognizer);
     }
     else if (e.Result.Grammar.Name == "Serenade" && e.Result.Confidence > 0.4)
     {
         PerformSerenadeCommand(speechRecogniser);
     }
     else if (e.Result.Grammar.Name == "Denied")
     {
         var availableCommands = speechSetup.SetUpMainCommands(speechRecogniser, form.UseAzureSpeech);
         form.RichTextBoxAvailableCommands = availableCommands;
     }
     else if (e.Result.Grammar.Name == "Studio" && e.Result.Confidence > 0.5)
     {
         RunVisualStudioCommand(speechRecogniser);
     }
     else if (e.Result.Grammar.Name == "Default Box" && e.Result.Confidence > 0.5)
     {
         Process.Start(@"C:\Users\MPhil\Source\Repos\SpeechRecognitionHelpers\DictationBoxMSP\bin\Release\DictationBoxMSP.exe");
     }
     else if (e.Result.Grammar.Name == "Dictation Box" && e.Result.Confidence > 0.5)
     {
         Process.Start(@"C:\Program Files (x86)\Speech Productivity\dictation box default\dictation box.exe");
     }
     else if (e.Result.Grammar.Name == "Get and Set" && e.Result.Confidence > 0.5)
     {
         inputSimulator.Keyboard.TextEntry(" { get; set; }");
     }
     else if (e.Result.Grammar.Name.Contains("Phonetic Alphabet"))             // Could be lower, mixed or upper
     {
         ProcessKeyboardCommand(e);
     }
     else if (e.Result.Grammar.Name == "Show Recent" && e.Result.Confidence > 0.5)
     {
         inputSimulator.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LMENU, VirtualKeyCode.VK_F);
         inputSimulator.Keyboard.KeyPress(VirtualKeyCode.VK_J);
     }
     else if (e.Result.Grammar.Name == "Fresh Line" && e.Result.Confidence > 0.5)
     {
         inputSimulator.Keyboard.KeyPress(VirtualKeyCode.END);
         inputSimulator.Keyboard.KeyPress(VirtualKeyCode.RETURN);
     }
     else if (e.Result.Grammar.Name == "Semi Colon" && e.Result.Confidence > 0.3)
     {
         inputSimulator.Keyboard.TextEntry(";");
     }
     // where the grammar name is the same Click cancelas the method Without the perform and command, with the spaces remove use reflection to call it
     else if (e.Result.Confidence > 0.6)
     {
         string methodName = $"Perform{e.Result.Grammar.Name.Replace(" ", "")}Command";
         Type   thisType   = this.GetType();
         //MethodInfo theMethod = thisType.GetMethod(methodName,BindingFlags.NonPublic  | BindingFlags.Instance);
         try
         {
             thisType.InvokeMember(methodName,
                                   BindingFlags.DeclaredOnly |
                                   BindingFlags.Public | BindingFlags.NonPublic |
                                   BindingFlags.Instance | BindingFlags.InvokeMethod
                                   , null, this, new Object[] { e });
         }
         catch (Exception exception)
         {
             //AutoClosingMessageBox.Show(exception.Message, $"Error Running a method {exception.Source}", 3000);
             System.Windows.Forms.MessageBox.Show(exception.Message, "Error running a method", MessageBoxButtons.OK);
         }
     }
 }
Ejemplo n.º 27
0
        private void frmExportDetailsInSales_Load(object sender, EventArgs e)
        {
            try
            {
                DataSet ds1 = objdblayer.dsquery("select * from CT_MAST");
                if (ds1.Tables[0].Rows.Count != 0)
                {
                    cmbCtDesc.DataSource    = ds1.Tables[0];
                    cmbCtDesc.DisplayMember = "CTDESC";
                    cmbCtDesc.ValueMember   = "CTID";
                    cmbCtDesc.Update();
                    //ACTIVE_BL.HTMAIN["CTDESC"] = cmbCtDesc.SelectedItem;
                    //ACTIVE_BL.HTMAIN["CTID"] = cmbCtDesc.SelectedValue;
                }

                DataSet ds2 = objdblayer.dsquery("select * from ARE_MAST");
                if (ds2.Tables[0].Rows.Count != 0)
                {
                    cmbAreDesc.DataSource    = ds2.Tables[0];
                    cmbAreDesc.DisplayMember = "AREDESC";
                    cmbAreDesc.ValueMember   = "AREID";
                    cmbAreDesc.Update();
                    //ACTIVE_BL.HTMAIN["AREDESC"] = cmbAreDesc.SelectedItem;
                    //ACTIVE_BL.HTMAIN["AREID"] = cmbAreDesc.SelectedValue;
                }

                if (ACTIVE_BL.Tran_mode != "add_mode")
                {
                    if (ACTIVE_BL.Tran_mode == "view_mode")
                    {
                        ((Control)tpExpDets1).Enabled = false;
                        ((Control)tpExpDets2).Enabled = false;
                    }
                    if (ACTIVE_BL.HTMAIN["CTDESC"].ToString() != "CT-3")
                    {
                        btn_ct.Enabled = false;
                    }
                    txtExpRef.Text           = ACTIVE_BL.HTMAIN["EXP_REF"].ToString();
                    txtPoNo.Text             = ACTIVE_BL.HTMAIN["PO_NO"].ToString();
                    txtOtherRef.Text         = ACTIVE_BL.HTMAIN["OTHER_REF"].ToString();
                    txtCorg.Text             = ACTIVE_BL.HTMAIN["C_ORG"].ToString();
                    txtCFinDest.Text         = ACTIVE_BL.HTMAIN["C_FINDEST"].ToString();
                    txtPlaceRecpt.Text       = ACTIVE_BL.HTMAIN["PLACE_RECPT"].ToString();
                    txtVesselNo.Text         = ACTIVE_BL.HTMAIN["VESSEL_NO"].ToString();
                    dtShipDt.Value           = DateTime.Parse(ACTIVE_BL.HTMAIN["SHIP_DT"].ToString());
                    txtPortLoad.Text         = ACTIVE_BL.HTMAIN["P_LOAD"].ToString();
                    txtPortDisc.Text         = ACTIVE_BL.HTMAIN["P_DISCHARGE"].ToString();
                    txtFinDest.Text          = ACTIVE_BL.HTMAIN["FIN_DEST"].ToString();
                    txtPreCarg.Text          = ACTIVE_BL.HTMAIN["PRE_CARG"].ToString();
                    txtCont1.Text            = ACTIVE_BL.HTMAIN["CONT1_NO"].ToString();
                    txtCont2.Text            = ACTIVE_BL.HTMAIN["CONT2_NO"].ToString();
                    txtExcNo1.Text           = ACTIVE_BL.HTMAIN["EXC_SEAL1_NO"].ToString();
                    txtExcNo2.Text           = ACTIVE_BL.HTMAIN["EXC_SEAL2_NO"].ToString();
                    txtTranNo1.Text          = ACTIVE_BL.HTMAIN["TRAN_SEAL1_NO"].ToString();
                    txtTranNo2.Text          = ACTIVE_BL.HTMAIN["TRAN_SEAL2_NO"].ToString();
                    txtShipDet.Text          = ACTIVE_BL.HTMAIN["SHIP_DETS"].ToString();
                    txtTermDelPay.Text       = ACTIVE_BL.HTMAIN["TER_DEL_PAY"].ToString();
                    txtBondNo.Text           = ACTIVE_BL.HTMAIN["BOND_NO"].ToString();
                    dtBonddt.Value           = DateTime.Parse(ACTIVE_BL.HTMAIN["BOND_DT"].ToString());
                    txtBondAmt.Text          = ACTIVE_BL.HTMAIN["BOND_AMT"].ToString();
                    dtCtDt.Value             = DateTime.Parse(ACTIVE_BL.HTMAIN["CT_DT"].ToString());
                    txtCtNo.Text             = ACTIVE_BL.HTMAIN["CT_NO"].ToString();
                    txtAreNo.Text            = ACTIVE_BL.HTMAIN["ARE_NO"].ToString();
                    dtAreDt.Value            = DateTime.Parse(ACTIVE_BL.HTMAIN["ARE_DT"].ToString());
                    cmbCtDesc.Text           = ACTIVE_BL.HTMAIN["CTDESC"].ToString();
                    cmbAreDesc.Text          = ACTIVE_BL.HTMAIN["AREDESC"].ToString();
                    cmbCtDesc.SelectedValue  = ACTIVE_BL.HTMAIN["CTID"].ToString();
                    cmbAreDesc.SelectedValue = ACTIVE_BL.HTMAIN["AREID"].ToString();
                }
                else
                {
                    btn_ct.Enabled     = false;
                    txtExpRef.Text     = ACTIVE_BL.HTMAIN["EXP_REF"].ToString();
                    txtPoNo.Text       = ACTIVE_BL.HTMAIN["PO_NO"].ToString();
                    txtOtherRef.Text   = ACTIVE_BL.HTMAIN["OTHER_REF"].ToString();
                    txtCorg.Text       = ACTIVE_BL.HTMAIN["C_ORG"].ToString();
                    txtCFinDest.Text   = ACTIVE_BL.HTMAIN["C_FINDEST"].ToString();
                    txtPlaceRecpt.Text = ACTIVE_BL.HTMAIN["PLACE_RECPT"].ToString();
                    txtVesselNo.Text   = ACTIVE_BL.HTMAIN["VESSEL_NO"].ToString();
                    dtShipDt.Value     = DateTime.Now;
                    txtPortLoad.Text   = ACTIVE_BL.HTMAIN["P_LOAD"].ToString();
                    txtPortDisc.Text   = ACTIVE_BL.HTMAIN["P_DISCHARGE"].ToString();
                    txtFinDest.Text    = ACTIVE_BL.HTMAIN["FIN_DEST"].ToString();
                    txtPreCarg.Text    = ACTIVE_BL.HTMAIN["PRE_CARG"].ToString();
                    txtCont1.Text      = ACTIVE_BL.HTMAIN["CONT1_NO"].ToString();
                    txtCont2.Text      = ACTIVE_BL.HTMAIN["CONT2_NO"].ToString();
                    txtExcNo1.Text     = ACTIVE_BL.HTMAIN["EXC_SEAL1_NO"].ToString();
                    txtExcNo2.Text     = ACTIVE_BL.HTMAIN["EXC_SEAL2_NO"].ToString();
                    txtTranNo1.Text    = ACTIVE_BL.HTMAIN["TRAN_SEAL1_NO"].ToString();
                    txtTranNo2.Text    = ACTIVE_BL.HTMAIN["TRAN_SEAL2_NO"].ToString();
                    txtShipDet.Text    = ACTIVE_BL.HTMAIN["SHIP_DETS"].ToString();
                    txtTermDelPay.Text = ACTIVE_BL.HTMAIN["TER_DEL_PAY"].ToString();
                    txtBondNo.Text     = ACTIVE_BL.HTMAIN["BOND_NO"].ToString();
                    dtBonddt.Value     = DateTime.Now;
                    txtBondAmt.Text    = ACTIVE_BL.HTMAIN["BOND_AMT"].ToString();
                    dtCtDt.Value       = DateTime.Now;
                    txtCtNo.Text       = ACTIVE_BL.HTMAIN["CT_NO"].ToString();

                    txtAreNo.Text = ACTIVE_BL.HTMAIN["ARE_NO"].ToString();
                    dtAreDt.Value = DateTime.Now;

                    //cmbCtDesc.SelectedItem = ACTIVE_BL.HTMAIN["CTDESC"].ToString();
                    //cmbAreDesc.SelectedItem = ACTIVE_BL.HTMAIN["AREDESC"].ToString();
                }

                AddThemesToTitleBar((Form)this, ucToolBar1, ACTIVE_BL, "CustomMaster");
                ucToolBar1.Titlebar = "Export Details";
            }
            catch (Exception ex)
            {
                AutoClosingMessageBox.Show(ex.Message, "Exception");
            }
        }
        private void dgrdTongHop_SelectionChanged(object sender, EventArgs e)
        {
            if (dgrdTongHop.SelectedRows.Count == 0)
            {
                return;
            }
            DataTable tmpTable = (dgrdTongHop.DataSource as DataTable);

            if (tmpTable == null || tmpTable.Rows.Count == 0)
            {
                return;
            }
            DataRowView dataRowView = dgrdTongHop.SelectedRows[0].DataBoundItem as DataRowView;

            //dgrdTongHop.Tag = dataRowView;
            if (dataRowView == null)
            {
                return;
            }

            int       tmpUserEnrollNumber = (int)dataRowView["UserEnrollNumber"];
            cUserInfo tmpNV       = flstDSNVChk.Find(o => o.UserEnrollNumber == tmpUserEnrollNumber);
            DateTime  tmpNgayCong = (DateTime)dataRowView["TimeStrNgay"];
            //test += "\nTimeStrNgay:" + tmpNgayCong.ToShortDateString() + " ";
            DateTime tmpVao = (dataRowView["TimeStrVao"] == DBNull.Value) ? DateTime.MinValue : (DateTime)dataRowView["TimeStrVao"];
            DateTime tmpRa  = (dataRowView["TimeStrRa"] == DBNull.Value) ? DateTime.MinValue : (DateTime)dataRowView["TimeStrRa"];
            //test += "\ttmpVao:" + tmpVao.ToShortTimeString() + " \ttmpRa" + tmpRa.ToShortTimeString();

            cNgayCong ngayCong = tmpNV.DSNgayCong.Find(o => o.NgayCong == tmpNgayCong);
            //test += tmpNV + "\n " + ngayCong;
            //lg.Info(test);
            cChkInOut old_CIO = new cChkInOut_A()
            {
                TG = new ThoiGian()
            };

            try {
                if (ngayCong.HasCheck == false || (tmpVao == DateTime.MinValue && tmpRa == DateTime.MinValue))
                {
                    old_CIO = null;
                }
                else if (tmpVao == DateTime.MinValue && tmpRa != DateTime.MinValue)
                {
                    old_CIO = ngayCong.DSVaoRa.Find(o => o.HaveINOUT == -2 && o.Raa.TimeStr == tmpRa);
                }
                else if (tmpRa == DateTime.MinValue && tmpVao != DateTime.MinValue)
                {
                    old_CIO = ngayCong.DSVaoRa.Find(o => o.HaveINOUT == -1 && o.Vao.TimeStr == tmpVao);
                }
                else
                {
                    old_CIO = ngayCong.DSVaoRa.Find(o => o.HaveINOUT > 0 && o.Vao.TimeStr == tmpVao && o.Raa.TimeStr == tmpRa);
                }

                LoadTabThemGio(tmpNV, tmpNgayCong, old_CIO);
                LoadTabSuaGio(tmpNV, tmpNgayCong, old_CIO);
            } catch (Exception ex) {
                string temp = "\n--start \n NV: " + tmpNV + "\nCIO: ";
                temp += (old_CIO != null) ? old_CIO.ToString() : "null";
                temp += "\n--end";
                lg.Fatal(ex.StackTrace + temp);
                AutoClosingMessageBox.Show("Có lỗi trong quá trình thao tác.", "Lỗi", 1500);
            }
        }
Ejemplo n.º 29
0
        private void btnServerCtrl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // 做啟動Server動作
            if (txtStatus.Text.Equals("未啟動") == true)
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        bool success = StartSyncServer(MeetingID);

                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            ChangeServerCtrl(success);
                        }));
                        if (success == true)
                        {
                            AutoClosingMessageBox.Show("啟動成功");
                            try
                            {
                                SocketClient socketClient = Singleton_Socket.GetInstance(MeetingID, UserID, UserName, false);
                                Task.Factory.StartNew(() =>
                                {
                                    if (socketClient != null && socketClient.GetIsConnected() == true)
                                    {
                                        socketClient.getUserList();
                                    }
                                    else
                                    {
                                        //AutoClosingMessageBox.Show("同步伺服器尚未啟動,請聯絡議事管理員開啟同步");
                                    }
                                });
                            }
                            catch (Exception ex)
                            {
                                LogTool.Debug(ex);
                            }
                        }
                        else
                        {
                            AutoClosingMessageBox.Show("啟動失敗");
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTool.Debug(ex);
                    }
                });
            }
            else // 做停止Server動作
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        bool success = StopSyncServer(MeetingID);
                        this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            ChangeServerCtrl(!success);
                        }));
                        if (success == true)
                        {
                            AutoClosingMessageBox.Show("停止成功");
                            this.Dispatcher.BeginInvoke(new Action(() =>
                            {
                                BroadcastRowSP.Children.Clear();
                            }));
                        }
                        else
                        {
                            AutoClosingMessageBox.Show("停止失敗");
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTool.Debug(ex);
                    }
                });
            }
        }
Ejemplo n.º 30
0
        static int Main(string[] args)
        {
            #region Initialize Variables

            string                  message       = defaultmessage;
            string                  title         = defaulttitle;
            MessageBoxButtons       buttons       = MessageBoxButtons.OK;
            MessageBoxIcon          icon          = MessageBoxIcon.Information;
            MessageBoxDefaultButton defaultbutton = MessageBoxDefaultButton.Button1;
            MessageBoxOptions       option        = MessageBoxOptions.DefaultDesktopOnly;
            bool         buttonsset    = false;
            bool         defaultset    = false;
            bool         escapemessage = true;
            bool         iconset       = false;
            bool         optionsset    = false;
            bool         useswitches   = false;
            DialogResult result;
            int          rc = 0;

            #endregion Initialize Variables


            #region Command Line Parsing

            foreach (string arg in args)
            {
                if (arg[0] == '/')
                {
                    useswitches = true;
                    if (arg.Length > 3 && arg[2] == ':')
                    {
                        string key = arg[1].ToString( ).ToUpper( );
                        string val = arg.Substring(3).ToUpper( );
                        switch (key)
                        {
                        case "?":
                            return(DisplayHelp( ));

                        case "B":
                            switch (val)
                            {
                            case "A":
                            case "ABORTRETRYIGNORE":
                                buttons = MessageBoxButtons.AbortRetryIgnore;
                                break;

                            case "C":
                            case "OKCANCEL":
                                buttons = MessageBoxButtons.OKCancel;
                                break;

                            case "N":
                            case "YESNOCANCEL":
                                buttons = MessageBoxButtons.YesNoCancel;
                                break;

                            case "O":
                            case "OK":
                                buttons = MessageBoxButtons.OK;
                                break;

                            case "R":
                            case "RETRYCANCEL":
                                buttons = MessageBoxButtons.RetryCancel;
                                break;

                            case "Y":
                            case "YESNO":
                                buttons = MessageBoxButtons.YesNo;
                                break;

                            default:
                                rc = 1;
                                break;
                            }
                            buttonsset = true;
                            break;

                        case "D":
                            if (!buttonsset)
                            {
                                rc = 1;
                            }
                            switch (val)
                            {
                            case "1":
                            case "BUTTON1":
                            case "ABORT":
                            case "OK":
                            case "YES":
                                defaultbutton = MessageBoxDefaultButton.Button1;
                                break;

                            case "2":
                            case "BUTTON2":
                            case "NO":
                                defaultbutton = MessageBoxDefaultButton.Button2;
                                break;

                            case "3":
                            case "BUTTON3":
                            case "IGNORE":
                                defaultbutton = MessageBoxDefaultButton.Button3;
                                break;

                            case "CANCEL":
                                if (buttons == MessageBoxButtons.YesNoCancel)
                                {
                                    defaultbutton = MessageBoxDefaultButton.Button3;
                                }
                                else
                                {
                                    defaultbutton = MessageBoxDefaultButton.Button2;
                                }
                                break;

                            case "RETRY":
                                if (buttons == MessageBoxButtons.RetryCancel)
                                {
                                    defaultbutton = MessageBoxDefaultButton.Button1;
                                }
                                else
                                {
                                    defaultbutton = MessageBoxDefaultButton.Button2;
                                }
                                break;

                            default:
                                rc = 1;
                                break;
                            }
                            defaultset = true;
                            break;

                        case "I":
                            switch (val)
                            {
                            case "A":
                            case "ASTERISK":
                                icon = MessageBoxIcon.Asterisk;
                                break;

                            case "E":
                            case "ERROR":
                                icon = MessageBoxIcon.Error;
                                break;

                            case "H":
                            case "HAND":
                                icon = MessageBoxIcon.Hand;
                                break;

                            case "I":
                            case "INFORMATION":
                                icon = MessageBoxIcon.Information;
                                break;

                            case "N":
                            case "NONE":
                                icon = MessageBoxIcon.None;
                                break;

                            case "Q":
                            case "QUESTION":
                                icon = MessageBoxIcon.Question;
                                break;

                            case "S":
                            case "STOP":
                                icon = MessageBoxIcon.Stop;
                                break;

                            case "W":
                            case "WARNING":
                                icon = MessageBoxIcon.Warning;
                                break;

                            case "X":
                            case "EXCLAMATION":
                                icon = MessageBoxIcon.Exclamation;
                                break;

                            default:
                                rc = 1;
                                break;
                            }
                            iconset = true;
                            break;

                        case "O":
                            switch (val)
                            {
                            case "H":
                            case "HIDECONSOLE":
                                HideConsoleWindow( );
                                break;

                            case "L":
                            case "RTLREADING":
                                option |= MessageBoxOptions.RtlReading;
                                break;

                            case "N":
                            case "NOESCAPE":
                                escapemessage = false;
                                break;

                            case "R":
                            case "RIGHTALIGN":
                                option |= MessageBoxOptions.RightAlign;
                                break;

                            default:
                                rc = 1;
                                break;
                            }
                            optionsset = true;
                            break;

                        case "T":
                            rc = CheckTimeout(val);
                            break;

                        default:
                            rc = 1;
                            break;
                        }
                    }
                    else
                    {
                        rc = 1;
                    }
                }
                else
                {
                    if (message == defaultmessage)
                    {
                        message = arg;
                    }
                    else if (title == defaulttitle)
                    {
                        title = arg;
                    }
                    else if (useswitches)                       // If switches are used, only 2 "unnamed" arguments are allowed
                    {
                        rc = 1;
                    }
                    else if (!buttonsset)
                    {
                        switch (arg.ToLower( ))
                        {
                        case "abortretryignore":
                            buttons = MessageBoxButtons.AbortRetryIgnore;
                            break;

                        case "ok":
                            buttons = MessageBoxButtons.OK;
                            break;

                        case "okcancel":
                            buttons = MessageBoxButtons.OKCancel;
                            break;

                        case "retrycancel":
                            buttons = MessageBoxButtons.RetryCancel;
                            break;

                        case "yesno":
                            buttons = MessageBoxButtons.YesNo;
                            break;

                        case "yesnocancel":
                            buttons = MessageBoxButtons.YesNoCancel;
                            break;

                        default:
                            buttons = MessageBoxButtons.OK;
                            rc      = 1;
                            break;
                        }
                        buttonsset = true;
                    }
                    else if (!iconset)
                    {
                        switch (arg.ToLower( ))
                        {
                        case "asterisk":
                            icon = MessageBoxIcon.Asterisk;
                            break;

                        case "error":
                            icon = MessageBoxIcon.Error;
                            break;

                        case "exclamation":
                            icon = MessageBoxIcon.Exclamation;
                            break;

                        case "hand":
                            icon = MessageBoxIcon.Hand;
                            break;

                        case "information":
                            icon = MessageBoxIcon.Information;
                            break;

                        case "none":
                            icon = MessageBoxIcon.None;
                            break;

                        case "question":
                            icon = MessageBoxIcon.Question;
                            break;

                        case "stop":
                            icon = MessageBoxIcon.Stop;
                            break;

                        case "warning":
                            icon = MessageBoxIcon.Warning;
                            break;

                        default:
                            icon = MessageBoxIcon.Warning;
                            rc   = 1;
                            break;
                        }
                        iconset = true;
                    }
                    else if (!defaultset)
                    {
                        switch (arg.ToLower( ))
                        {
                        case "":
                        case "abort":
                        case "button1":
                        case "ok":
                        case "yes":
                            defaultbutton = MessageBoxDefaultButton.Button1;
                            break;

                        case "button2":
                        case "no":
                            defaultbutton = MessageBoxDefaultButton.Button2;
                            break;

                        case "button3":
                        case "ignore":
                            defaultbutton = MessageBoxDefaultButton.Button3;
                            break;

                        case "cancel":
                            if (args[2].ToLower( ) == "okcancel" || args[2].ToLower( ) == "retrycancel")
                            {
                                defaultbutton = MessageBoxDefaultButton.Button2;
                            }
                            else                                     // yesnocancel
                            {
                                defaultbutton = MessageBoxDefaultButton.Button3;
                            }
                            break;

                        case "retry":
                            if (args[2].ToLower( ) == "abortretryignore")
                            {
                                defaultbutton = MessageBoxDefaultButton.Button2;
                            }
                            else                                     // retrycancel
                            {
                                defaultbutton = MessageBoxDefaultButton.Button1;
                            }
                            break;

                        default:
                            defaultbutton = MessageBoxDefaultButton.Button1;
                            rc            = 1;
                            break;
                        }
                        defaultset = true;
                    }
                    else if (!optionsset)
                    {
                        switch (arg.ToLower( ))
                        {
                        case "":
                        case "none":
                            optionsset = true;
                            break;

                        case "hideconsole":
                            HideConsoleWindow( );
                            optionsset = true;
                            break;

                        case "noescape":
                            escapemessage = false;
                            optionsset    = true;
                            break;

                        case "rightalign":
                            option     = MessageBoxOptions.RightAlign;
                            optionsset = true;
                            break;

                        case "rtlreading":
                            option     = MessageBoxOptions.RtlReading;
                            optionsset = true;
                            break;

                        default:                                 // try if option is unspecified and argument is timeout
                            rc = CheckTimeout(arg);
                            break;
                        }
                    }
                    else if (timeout == 0)
                    {
                        rc = CheckTimeout(arg);
                    }
                    else
                    {
                        rc = 1;
                    }
                }
            }

            if (!escapemessage && message != defaultmessage)
            {
                message = UnEscapeString(message);
                title   = UnEscapeString(title);
            }

            // MessageBoxOptions.ServiceNotification allows interactive use by SYSTEM account (or any other account not currently logged in)
            option |= MessageBoxOptions.ServiceNotification;

            #endregion Command Line Parsing


            if (rc == 1)               // command line error
            {
                ShowConsoleWindow( );
                message       = defaultmessage;
                title         = defaulttitle;
                buttons       = MessageBoxButtons.OK;
                icon          = MessageBoxIcon.Warning;
                defaultbutton = MessageBoxDefaultButton.Button1;
                return(DisplayHelp( ));
            }

            if (rc == 0 && timeout > 0)
            {
                result = AutoClosingMessageBox.Show(message, title, timeout, buttons, icon, defaultbutton, option);
                if (timeoutelapsed)
                {
                    Console.WriteLine("timeout");
                    return(3);
                }
            }
            else
            {
                if (message == defaultmessage)
                {
                    message = defaultmessage.Substring(0, defaultmessage.IndexOf("\n\nNotes:")) + "\n\nWritten by Rob van der Woude\nhttp://www.robvanderwoude.com";
                    result  = System.Windows.Forms.MessageBox.Show(message, title, buttons, icon, defaultbutton, option);
                    Console.WriteLine(result.ToString( ).ToLower( ));
                    message = defaultmessage.Substring(defaultmessage.IndexOf("Notes:"));
                }
                result = System.Windows.Forms.MessageBox.Show(message, title, buttons, icon, defaultbutton, option);
            }
            Console.WriteLine(result.ToString( ).ToLower( ));
            return(rc);
        }