private void btnAddConfirm_Click(object sender, EventArgs e)
        {
            bool areFieldsValid = ValidateInputFields();

            if (areFieldsValid)
            {
                string[] inputFields = new string[] {
                    this.nameTextBox.Text,
                    this.sinceDatePicker.Text,
                    this.dueDatePicker.Text,
                    this.phoneTextBox.Text,
                    this.emailTextBox.Text,
                    this.facebookTextBox.Text,
                    this.amountTextBox.Text
                };

                RegexOptions options = RegexOptions.None;
                Regex        regex   = new Regex("[ ]{2,}", options);

                for (int i = 0; i < inputFields.Length; i++)
                {
                    // Removing all unnecessary whitespaces.
                    inputFields[i] = inputFields[i].TrimStart().TrimEnd();
                    inputFields[i] = regex.Replace(inputFields[i], " ");
                }

                decimal currencyInterest   = decimal.Parse(this.interestWithCurrencyTextBox.Text);
                decimal percentageInterest = 1.00m + (decimal.Parse(this.interestWithPercentageTextBox.Text) / 100.00m);

                string  name     = inputFields[0];
                string  since    = inputFields[1];
                string  dueDate  = inputFields[2];
                string  phone    = inputFields[3];
                string  email    = inputFields[4];
                string  facebook = inputFields[5];
                decimal amount   = (decimal.Parse(inputFields[6]) + currencyInterest);

                if (percentageInterest > 0)
                {
                    amount *= percentageInterest;
                }

                string transactorType = string.Empty;
                string path           = TransactorsFilePath;

                if (btnDebtor.BackColor == Color.FromArgb(0, 208, 255))
                {
                    transactorType = TransactorType.Debtor.ToString();
                    XmlProcess.AddTransactorToXml(path, name, since, dueDate, phone, email, amount, facebook, transactorType);
                }
                else if (btnCreditor.BackColor == Color.FromArgb(0, 208, 255))
                {
                    transactorType = TransactorType.Creditor.ToString();
                    XmlProcess.AddTransactorToXml(path, name, since, dueDate, phone, email, amount, facebook, transactorType);
                }

                this.FormClosing -= AlertUserOnExit;
                this.Close();
            }
        }
        private void button1_Copy_Click(object sender, RoutedEventArgs e)
        {
            Score socre = new Score();

            socre.Scores       = "100";
            socre.SecondTitile = "考试成绩1";
            socre.Titile       = "张三 考试成绩";
            XmlProcess.SerializeScoreFieldsSetting(socre);
        }
Esempio n. 3
0
        [OutputCache(NoStore = true, Duration = 0)] // 以防Server取得的是Cache,必須即時更新
        public ActionResult ShowXML(XMLSettingVM vm)
        {
            // 限定同網站的Ajax專用
            if (!Request.IsAjaxRequest())
            {
                return(Content("Fail"));
            }

            #region 取得暫存 Session XMLMappings
            List <tblXMLMapping> xmlMappings = new List <tblXMLMapping>();
            string ColumnName = string.Empty;

            try
            {
                xmlMappings = JsonConvert.DeserializeObject <List <tblXMLMapping> >(Cache.GetCache("XMLMappings"));
            }
            catch { }
            #endregion

            #region 依指定SQL語句抓取資料
            using (tblSQLSettingRepository setting = new tblSQLSettingRepository())
            {
                tblSQLSetting SQLSetting = setting.select(vm.SQLName);
                if (SQLSetting != null)
                {
                    using (DataAccess da = new DataAccess())
                    {
                        string sql = Func.SqlPlusTop(SQLSetting.SQLStatement, SQLSetting.DataRow);
                        Tuple <bool, DataTable, string> result = da.TryExecuteDataTable(sql);
                        DataTable dt = result.Item2;

                        XmlDocument xmlDoc = XmlProcess.GenerateXML(dt, xmlMappings);

                        //XmlDocument xmlDoc = new XmlDocument();
                        ////根節點 只有1個
                        //var rootTag = xmlMappings.Where(x => string.IsNullOrEmpty(x.FatherTag)).First();

                        //XmlElement root = xmlDoc.CreateElement(rootTag.TagName);
                        //for (int i = 0; i < dt.Rows.Count; i++)
                        //    appendXmlByRow(dt.Rows[i], xmlMappings, xmlDoc, root, rootTag.TagName, 1);

                        ////addSubElement(xmlMappings, xmlDoc, root, rootTag.TagName, dt);
                        //xmlDoc.AppendChild(root);

                        model.XMLView = Server.HtmlEncode(Func.BeautifyXML(xmlDoc));
                    }
                }
                else
                {
                    model.XMLView = "找不到指定的 SQL 設定!";
                }
            }
            #endregion

            return(PartialView("_XMLView", model));
        }
Esempio n. 4
0
    // Send PING to irc server every minutes
    public void Run()
    {
        while (true)
        {
            foreach (User us in Users.list)
            {
                us.watchTime++;

                XmlProcess.Write("xml\\users.xml", "User", us.name, us.admin.ToString(), us.currency.ToString(), us.watchTime.ToString(), us.hp.ToString(), us.def.ToString(), us.atk.ToString(), us.rep.ToString());
            }

            IrcBot.Send(PING + IrcBot.SERVER);
            Thread.Sleep(60000);
        }
    }
Esempio n. 5
0
    public User(string name)
    {
        this.name  = name;
        this.admin = XmlProcess.Read("xml\\users.xml", "User", name, "admin").ToUpper() == "TRUE";
        int.TryParse(XmlProcess.Read("xml\\users.xml", "User", name, "currency"), out this.currency);
        int.TryParse(XmlProcess.Read("xml\\users.xml", "User", name, "watchtime"), out this.watchTime);

        if (!int.TryParse(XmlProcess.Read("xml\\users.xml", "User", name, "hp"), out this.hp))
        {
            this.hp = 100;
        }
        int.TryParse(XmlProcess.Read("xml\\users.xml", "User", name, "def"), out this.def);
        int.TryParse(XmlProcess.Read("xml\\users.xml", "User", name, "atk"), out this.atk);
        if (!int.TryParse(XmlProcess.Read("xml\\users.xml", "User", name, "rep"), out this.rep))
        {
            this.rep = 10;
        }
    }
Esempio n. 6
0
        private void FillDataTable(string path, TransactorType transactorType)
        {
            if (path == null)
            {
                throw new NullReferenceException(ErrorMessage.PathCannotBeNull);
            }
            else if (!File.Exists(path))
            {
                throw new InvalidOperationException(ErrorMessage.FileDoesntExist);
            }

            IEnumerable <Transactor> transactors = XmlProcess.DeserializeXmlWithTransactorType(path, transactorType);

            foreach (Transactor transactor in transactors)
            {
                this.table.Rows.Add(
                    transactor.No,
                    transactor.Name,
                    transactor.Since,
                    transactor.DueDate,
                    $"{transactor.Amount:f2} {transactor.CurrencyAbbreviation}");
            }
        }
 /// <summary>
 /// 初始化验证 使用内置路径
 /// </summary>
 public UserAuthorizeAttribute()
 {
     var xmlProcess = new XmlProcess(Path);
     SetAttribute(ref xmlProcess);
 }
        private void CreateXmlWriter()
        {
            string xmlFileName = m_cs2FileName.Substring(0, m_cs2FileName.LastIndexOf(".")) + ".xml";

            m_xmlProcess = new XmlWriter(xmlFileName);
        }
 private void CreateXmlReader()
 {
     m_xmlProcess = new XmlReader(m_xmlFileName);
 }
Esempio n. 10
0
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            bool areInputFieldsValid = AreInputFieldsValid(
                this.nameTextBox,
                this.sinceDatePicker,
                this.dueDatePicker,
                this.phoneTextBox,
                this.emailTextBox,
                this.facebookTextBox,
                this.amountTextBox,
                this.interestCheckBox,
                this.interestWithCurrencyTextBox,
                this.interestWithPercentageTextBox);

            if (areInputFieldsValid)
            {
                // The array is necessary so we can later trim each textbox.
                string[] inputFields = new string[] {
                    this.nameTextBox.Text,
                    this.sinceDatePicker.Text,
                    this.dueDatePicker.Text,
                    this.phoneTextBox.Text,
                    this.emailTextBox.Text,
                    this.facebookTextBox.Text,
                    this.amountTextBox.Text,
                    this.interestWithCurrencyTextBox.Text,
                    this.interestWithPercentageTextBox.Text
                };

                RegexOptions options = RegexOptions.None;
                Regex        regex   = new Regex("[ ]{2,}", options);

                for (int i = 0; i < inputFields.Length; i++)
                {
                    // Removing all unnecessary whitespaces.
                    inputFields[i] = inputFields[i].TrimStart().TrimEnd();
                    inputFields[i] = regex.Replace(inputFields[i], " ");
                }

                decimal currencyInterest   = decimal.Parse(inputFields[7]);
                decimal percentageInterest = 1.00m + (decimal.Parse(inputFields[8]) / 100.00m);

                this.newName        = inputFields[0];
                this.newSince       = inputFields[1];
                this.newDueDate     = inputFields[2];
                this.newPhoneNumber = inputFields[3];
                this.newEmail       = inputFields[4];
                this.newFacebook    = inputFields[5];
                this.newAmount      = decimal.Parse(inputFields[6]) + currencyInterest;
                Currency currencyObj = this.currencyComboBox.SelectedItem as Currency;
                this.newCurrency = currencyObj;

                if (percentageInterest > 1.00m)
                {
                    newAmount = decimal.Parse((newAmount * percentageInterest).ToString("f2"));
                }

                this.newTransactorType = string.Empty;
                XDocument xmlDocument = XDocument.Load(TransactorsFilePath);

                if (btnDebtor.BackColor == Color.FromArgb(0, 208, 255))
                {
                    this.newTransactorType = TransactorType.Debtor.ToString();
                }
                else if (btnCreditor.BackColor == Color.FromArgb(0, 208, 255))
                {
                    this.newTransactorType = TransactorType.Creditor.ToString();
                }

                if (this.oldTransactorType != this.newTransactorType)
                {
                    // Deleting the transactor from the old collection and putting it (with the new data) into the new collection.
                    xmlDocument.Root.Elements().FirstOrDefault(x => x.Attribute("no").Value == this.no.ToString() &&
                                                               x.Element("TransactorType").Value == this.oldTransactorType)
                    .Remove();

                    int noCounter = 1;
                    IEnumerable <XElement> transactorsWithType = xmlDocument
                                                                 .Element(XmlRoot)
                                                                 .Elements(XmlElement)
                                                                 .Where(x => x.Element("TransactorType").Value == this.oldTransactorType);

                    foreach (XElement debtor in transactorsWithType)
                    {
                        debtor.SetAttributeValue("no", noCounter++);
                    }

                    xmlDocument.Save(TransactorsFilePath, SaveOptions.DisableFormatting);

                    XmlProcess.AddTransactorToXml(TransactorsFilePath,
                                                  this.newName,
                                                  this.newSince,
                                                  this.newDueDate,
                                                  this.newPhoneNumber,
                                                  this.newEmail,
                                                  this.newAmount,
                                                  this.newCurrency.Abbreviation,
                                                  this.newFacebook,
                                                  this.newTransactorType);
                }
                else if (this.oldTransactorType == this.newTransactorType)
                {
                    // Overwriting the old data with the new one and keeping the record in the same collection.
                    XmlProcess.EditTransactorFromXml(
                        TransactorsFilePath,
                        this.no,
                        this.newName,
                        this.newSince,
                        this.newDueDate,
                        this.newPhoneNumber,
                        this.newEmail,
                        this.newFacebook,
                        this.newAmount,
                        this.newCurrency.Abbreviation,
                        this.oldTransactorType);
                }

                this.mainForm.EnableMainFormAndRefreshDataGrid(this.mainForm);
                this.FormClosing -= AlertUserOnExit;
                this.Close();
            }
        }
 /// <summary>
 /// 初始化验证 使用内置路径
 /// </summary>
 public UserAuthorizeAttribute(Models.User user, string settingFilePath)
 {
     User = user;
     var xmlProcess = new XmlProcess(settingFilePath);
     SetAttribute(ref xmlProcess);
 }
 /// <summary>
 /// 初始化验证 使用内置路径
 /// </summary>
 public UserAuthorizeAttribute(Models.User user)
 {
     User = user;
     var xmlProcess = new XmlProcess(Path);
     SetAttribute(ref xmlProcess);
 }
 /// <summary>
 /// 初始化验证
 /// </summary>
 /// <param name="settingFilePath">全局设置文件路径,相对于程序集</param>
 public UserAuthorizeAttribute(string settingFilePath)
 {
     var xmlProcess = new XmlProcess(settingFilePath);
     SetAttribute(ref xmlProcess);
 }
        public ActionResult Generate(QueryVM vm)
        {
            vm.UserID = userInfo.Account;
            string exeResult = string.Empty;

            try
            {
                string SQLName = string.Empty;
                if (!canGenerate(vm))
                {
                    return(RedirectToAction("Query", vm));
                    //return View("Index", vm);
                }

                #region XML
                if (vm.Format.Equals("XML"))
                {
                    using (tblXMLSettingRepository rep = new tblXMLSettingRepository())
                        using (tblXMLMappingRepository map = new tblXMLMappingRepository())
                        {
                            tblXMLSetting setting = rep.get(vm.SettingName);
                            if (setting != null)
                            {
                                SQLName = setting.SQLName;
                            }
                            List <tblXMLMapping> mapping = map.get(vm.SettingName).ToList();
                            using (tblSQLSettingRepository set = new tblSQLSettingRepository())
                            {
                                tblSQLSetting sqlSetting = set.select(SQLName);
                                using (DataAccess da = new DataAccess())
                                {
                                    Tuple <bool, DataTable, string> result = da.TryExecuteDataTable(sqlSetting.SQLStatement, null, vm.Columns);
                                    if (!result.Item1)
                                    {
                                        log.Save("轉出", userInfo.Name, vm.CustomerName, vm.Format, vm.DataDestination, vm.Email, vm.FTPServerIP, vm.FileName, "失敗", result.Item3);
                                        return(View("Index", vm));
                                    }

                                    vm.SQLResultDataRow = result.Item2;
                                    XmlDocument       xmlDoc   = XmlProcess.GenerateXML(result.Item2, mapping);
                                    XmlWriterSettings settings = new XmlWriterSettings();
                                    settings.Indent              = true;
                                    settings.OmitXmlDeclaration  = false;
                                    settings.NewLineOnAttributes = true;
                                    settings.Encoding            = Encoding.GetEncoding("utf-8");

                                    if (vm.DataDestination.Equals("Download", StringComparison.OrdinalIgnoreCase))
                                    {
                                        MemoryStream ms = new MemoryStream();
                                        using (XmlWriter writer = XmlWriter.Create(ms, settings))
                                        {
                                            xmlDoc.WriteTo(writer); // Write to memorystream
                                        }

                                        byte[] data = ms.ToArray();

                                        Response.Clear();
                                        Response.ContentType = "application/octet-stream";
                                        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(vm.FileName));
                                        Response.Charset = "UTF-8";
                                        Response.BinaryWrite(data);
                                        Response.End();
                                        ms.Flush(); // Probably not needed
                                        ms.Close();
                                    }
                                    else if (vm.DataDestination.Equals("FTP", StringComparison.OrdinalIgnoreCase))
                                    {
                                        using (Stream fs = System.IO.File.Open(Server.MapPath("~/Files/" + vm.FileName), FileMode.CreateNew))
                                        {
                                            XmlWriter writer = XmlWriter.Create(fs, settings);
                                            xmlDoc.WriteTo(writer); // Write to memorystream
                                            writer.Flush();
                                            fs.Close();
                                        }

                                        //xmlDoc.Save(Server.MapPath("~/Files/" + vm.FileName));
                                        FTPData ftpData = new FTPData()
                                        {
                                            FTPServerIP = vm.FTPServerIP,
                                            Port        = vm.FTPPort ?? 21,
                                            UserName    = vm.FTPUserName,
                                            Password    = vm.FTPPassword,
                                            file        = new FileInfo(Server.MapPath("~/Files/" + vm.FileName))
                                        };
                                        if (vm.FTPPort == 22)
                                        {
                                            SFtpProcess uploader = new SFtpProcess(ftpData);
                                            exeResult = uploader.Put(ftpData.file, ftpData.DirName);
                                        }
                                        else
                                        {
                                            FtpProcess uploader = new FtpProcess();
                                            exeResult = uploader.Upload(ftpData);
                                        }
                                    }
                                    else if (vm.DataDestination.Equals("EMail", StringComparison.OrdinalIgnoreCase))
                                    {
                                        using (Stream fs = System.IO.File.Open(Server.MapPath("~/Files/" + vm.FileName), FileMode.CreateNew))
                                        {
                                            XmlWriter writer = XmlWriter.Create(fs, settings);
                                            xmlDoc.WriteTo(writer); // Write to memorystream
                                            writer.Flush();
                                            fs.Close();
                                        }
                                        string subject = string.Empty;
                                        using (bscodeRepository bscode = new bscodeRepository())
                                        {
                                            subject = bscode.getSubject(sqlSetting.SQLType);
                                        }
                                        MailProcess sender   = new MailProcess();
                                        EmailData   mailData = new EmailData()
                                        {
                                            To         = vm.Email,
                                            Subject    = subject,
                                            Attachment = new FileInfo(Server.MapPath("~/Files/" + vm.FileName))
                                        };
                                        exeResult = sender.SendEmail(mailData);
                                    }
                                    if (!string.IsNullOrEmpty(exeResult))
                                    {
                                        log.Save("轉出", userInfo.Name, vm.CustomerName, vm.Format, vm.DataDestination, vm.Email, vm.FTPServerIP, vm.FileName, "失敗", exeResult);
                                    }
                                    else
                                    {
                                        log.Save("轉出", userInfo.Name, vm.CustomerName, vm.Format, vm.DataDestination, vm.Email, vm.FTPServerIP, vm.FileName, "成功", "");
                                    }
                                }
                            }
                        }
                }
                #endregion
                #region EXCEL
                else if (vm.Format.Equals("EXCEL"))
                {
                    using (tblExcelSettingRepository rep = new tblExcelSettingRepository())
                        using (tblExcelMappingRepository map = new tblExcelMappingRepository())
                        {
                            tblExcelSetting setting = rep.get(vm.SettingName);
                            if (setting != null)
                            {
                                SQLName = setting.SQLName;
                            }

                            List <tblExcelMapping> mapping = map.get(vm.SettingName).ToList();
                            using (tblSQLSettingRepository set = new tblSQLSettingRepository())
                            {
                                tblSQLSetting sqlSetting = set.select(SQLName);
                                using (DataAccess da = new DataAccess())
                                {
                                    Tuple <bool, DataTable, string> result = da.TryExecuteDataTable(sqlSetting.SQLStatement, null, vm.Columns);
                                    if (!result.Item1)
                                    {
                                        log.Save("轉出", userInfo.Name, vm.CustomerName, vm.Format, vm.DataDestination, vm.Email, vm.FTPServerIP, vm.FileName, "失敗", result.Item3);
                                        return(View("Index", vm));
                                    }
                                    vm.SQLResultDataRow = result.Item2;
                                    HSSFWorkbook book = ExcelProcess.GenerateExcel(result.Item2, mapping);

                                    if (vm.DataDestination.Equals("Download", StringComparison.OrdinalIgnoreCase))
                                    {
                                        MemoryStream ms = new MemoryStream();
                                        book.Write(ms);
                                        Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", HttpUtility.UrlEncode(vm.FileName)));
                                        Response.BinaryWrite(ms.ToArray());
                                        Response.End();
                                        book = null;
                                        ms.Close();
                                        ms.Dispose();
                                    }
                                    else if (vm.DataDestination.Equals("FTP", StringComparison.OrdinalIgnoreCase))
                                    {
                                        FileStream file = new FileStream(Server.MapPath("~/Files/" + vm.FileName), FileMode.Create);//產生檔案
                                        book.Write(file);
                                        file.Close();

                                        FTPData ftpData = new FTPData()
                                        {
                                            FTPServerIP = vm.FTPServerIP,
                                            Port        = vm.FTPPort ?? 21,
                                            UserName    = vm.FTPUserName,
                                            Password    = vm.FTPPassword,
                                            file        = new FileInfo(Server.MapPath("~/Files/" + vm.FileName))
                                        };
                                        if (vm.FTPPort == 22)
                                        {
                                            SFtpProcess uploader = new SFtpProcess(ftpData);
                                            exeResult = uploader.Put(ftpData.file, ftpData.DirName);
                                        }
                                        else
                                        {
                                            FtpProcess uploader = new FtpProcess();
                                            exeResult = uploader.Upload(ftpData);
                                        }
                                    }
                                    else if (vm.DataDestination.Equals("EMail", StringComparison.OrdinalIgnoreCase))
                                    {
                                        FileStream file = new FileStream(Server.MapPath("~/Files/" + vm.FileName), FileMode.Create);//產生檔案
                                        book.Write(file);
                                        file.Close();
                                        string subject = string.Empty;
                                        using (bscodeRepository bscode = new bscodeRepository())
                                        {
                                            subject = bscode.getSubject(sqlSetting.SQLType);
                                        }
                                        MailProcess sender   = new MailProcess();
                                        EmailData   mailData = new EmailData()
                                        {
                                            To         = vm.Email,
                                            Subject    = subject,
                                            Attachment = new FileInfo(Server.MapPath("~/Files/" + vm.FileName))
                                        };
                                        exeResult = sender.SendEmail(mailData);
                                    }
                                    if (!string.IsNullOrEmpty(exeResult))
                                    {
                                        log.Save("轉出", userInfo.Name, vm.CustomerName, vm.Format, vm.DataDestination, vm.Email, vm.FTPServerIP, vm.FileName, "失敗", exeResult);
                                    }
                                    else
                                    {
                                        log.Save("轉出", userInfo.Name, vm.CustomerName, vm.Format, vm.DataDestination, vm.Email, vm.FTPServerIP, vm.FileName, "成功", "");
                                    }
                                }
                            }
                        }
                }
                #endregion
            }
            catch (Exception ex)
            {
                exeResult = ex.Message.Replace("\r\n", "");
                log.Save("轉出", userInfo.Name, vm.CustomerName, vm.Format, vm.DataDestination, vm.Email, vm.FTPServerIP, vm.FileName, "失敗", exeResult);
            }

            if (!string.IsNullOrEmpty(exeResult))
            {
                ViewBag.ExeResult = exeResult;
            }
            else
            {
                ViewBag.ExeResult = "操作完成";
            }
            return(View("Index", vm));
        }
 /// <summary>
 /// 根据XMl设置属性
 /// </summary>
 /// <param name="xmlProcess">XML源</param>
 private static void SetAttribute(ref XmlProcess xmlProcess)
 {
     if (xmlProcess.XmlFileExist)
     {
         StaticResource.WebsFolder = xmlProcess.ReadAttribute("/Global/User/WebsFolder", "Url").ToLower().Trim();
         StaticResource.UserLoginUrl = xmlProcess.ReadAttribute("/Global/User/UserLogin", "Url").ToLower().Trim();
         StaticResource.DefaultRedRedirect = xmlProcess.ReadAttribute("/Global/User/DefaultRedRedirect", "Url").ToLower().Trim();
         StaticResource.DefaultLoginUserAccessController = xmlProcess.ReadAttribute("/Global/User/DefaultLoginUserAccess", "Controller").ToLower().Trim();
         StaticResource.DefaultLoginUserAccessAction = xmlProcess.ReadAttribute("/Global/User/DefaultLoginUserAccess", "Action").ToLower().Trim();
     }
     else
     {
         throw new Exception(string.Format("文件{0}不存在", xmlProcess.XmlPath));
     }
 }
Esempio n. 16
0
        private void btnAddConfirm_Click(object sender, EventArgs e)
        {
            bool areFieldsValid = ValidateInputFields();

            if (areFieldsValid)
            {
                string[] inputFields = new string[] {
                    this.nameTextBox.Text,
                    this.sinceDatePicker.Text,
                    this.dueDatePicker.Text,
                    this.phoneTextBox.Text,
                    this.emailTextBox.Text,
                    this.facebookTextBox.Text,
                    this.amountTextBox.Text
                };

                RegexOptions options = RegexOptions.None;
                Regex        regex   = new Regex("[ ]{2,}", options);

                for (int i = 0; i < inputFields.Length; i++)
                {
                    // Removing all unnecessary whitespaces.
                    inputFields[i] = inputFields[i].TrimStart().TrimEnd();
                    inputFields[i] = regex.Replace(inputFields[i], " ");
                }

                decimal currencyInterest   = decimal.Parse(this.interestWithCurrencyTextBox.Text);
                decimal percentageInterest = 1.00m + (decimal.Parse(this.interestWithPercentageTextBox.Text) / 100.00m);

                string  name     = inputFields[0];
                string  since    = inputFields[1];
                string  dueDate  = inputFields[2];
                string  phone    = inputFields[3];
                string  email    = inputFields[4];
                string  facebook = inputFields[5];
                decimal amount   = (decimal.Parse(inputFields[6]) + currencyInterest);

                if (percentageInterest > 0)
                {
                    amount *= percentageInterest;
                }

                string addTransactorType = string.Empty;
                string path = TransactorsFilePath;

                if (isEditable)
                {
                    if (btnDebtor.BackColor == Color.FromArgb(0, 208, 255))
                    {
                        addTransactorType = TransactorType.Debtor.ToString();
                    }
                    else if (btnCreditor.BackColor == Color.FromArgb(0, 208, 255))
                    {
                        addTransactorType = TransactorType.Creditor.ToString();
                    }

                    // If the user wants to edit data :
                    // If the user did not change the transactor type -
                    // I should keep the record at its place without changing the no.
                    // Otherwise (user has changed transactor type) I should remove the record from the previous
                    // collection and add it to the new one.

                    XDocument xmlDocument = XDocument.Load(TransactorsFilePath);

                    var transactorRoot = xmlDocument.Element("Transactors");

                    if (transactorRoot.HasElements)
                    {
                        XElement transactors = xmlDocument
                                               .Element("Transactors")
                                               .Elements("Transactor")
                                               .Where(x => x.Element("TransactorType").Value == this.transactorType &&
                                                      x.Attribute("no").Value == this.no.ToString())
                                               .FirstOrDefault();

                        if (transactorRoot != null)
                        {
                        }
                    }
                }
                else
                {
                    // If the user wants to add data.
                    if (btnDebtor.BackColor == Color.FromArgb(0, 208, 255))
                    {
                        addTransactorType = TransactorType.Debtor.ToString();
                        XmlProcess.AddTransactorToXml(path, name, since, dueDate, phone, email, amount, facebook, addTransactorType);
                    }
                    else if (btnCreditor.BackColor == Color.FromArgb(0, 208, 255))
                    {
                        addTransactorType = TransactorType.Creditor.ToString();
                        XmlProcess.AddTransactorToXml(path, name, since, dueDate, phone, email, amount, facebook, addTransactorType);
                    }
                }

                this.FormClosing -= AlertUserOnExit;
                this.Close();
            }
        }
Esempio n. 17
0
        private void btnAddConfirm_Click(object sender, EventArgs e)
        {
            bool areInputFieldsValid = AreInputFieldsValid(
                this.nameTextBox,
                this.sinceDatePicker,
                this.dueDatePicker,
                this.phoneTextBox,
                this.emailTextBox,
                this.facebookTextBox,
                this.amountTextBox,
                this.interestCheckBox,
                this.interestWithCurrencyTextBox,
                this.interestWithPercentageTextBox);

            if (areInputFieldsValid)
            {
                // The array is necessary so we can later trim each textbox.
                string[] inputFields = new string[] {
                    this.nameTextBox.Text,
                    this.sinceDatePicker.Text,
                    this.dueDatePicker.Text,
                    this.phoneTextBox.Text,
                    this.emailTextBox.Text,
                    this.facebookTextBox.Text,
                    this.amountTextBox.Text
                };

                RegexOptions options = RegexOptions.None;
                Regex        regex   = new Regex("[ ]{2,}", options);

                for (int i = 0; i < inputFields.Length; i++)
                {
                    // Removing all unnecessary whitespaces.
                    inputFields[i] = inputFields[i].TrimStart().TrimEnd();
                    inputFields[i] = regex.Replace(inputFields[i], " ");
                }

                decimal currencyInterest   = decimal.Parse(this.interestWithCurrencyTextBox.Text);
                decimal percentageInterest = 1.00m + (decimal.Parse(this.interestWithPercentageTextBox.Text) / 100.00m);

                string   name                 = inputFields[0];
                string   since                = inputFields[1];
                string   dueDate              = inputFields[2];
                string   phone                = inputFields[3];
                string   email                = inputFields[4];
                string   facebook             = inputFields[5];
                decimal  amount               = (decimal.Parse(inputFields[6]) + currencyInterest);
                Currency currencyObj          = this.currencyComboBox.SelectedItem as Currency;
                string   currencyAbbreviation = currencyObj.Abbreviation;

                if (percentageInterest > 1.00m)
                {
                    amount = decimal.Parse((amount * percentageInterest).ToString("f2"));
                }

                string addTransactorType = string.Empty;

                if (btnDebtor.BackColor == DefaultButtonColor)
                {
                    addTransactorType = TransactorType.Debtor.ToString();
                    XmlProcess.AddTransactorToXml(TransactorsFilePath, name, since, dueDate, phone, email, amount, currencyAbbreviation, facebook, addTransactorType);
                }
                else if (btnCreditor.BackColor == DefaultButtonColor)
                {
                    addTransactorType = TransactorType.Creditor.ToString();
                    XmlProcess.AddTransactorToXml(TransactorsFilePath, name, since, dueDate, phone, email, amount, currencyAbbreviation, facebook, addTransactorType);
                }

                this.FormClosing -= AlertUserOnExit;
                this.Close();
            }
        }
Esempio n. 18
0
        static void Generate(tblSchedule s)
        {
            string exeResult = string.Empty;
            string FileName  = string.Empty;

            try
            {
                string   SQLName      = string.Empty;
                string[] Destinations = s.Destination.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                #region XML
                if (s.Format.Equals("XML"))
                {
                    using (tblXMLSettingRepository rep = new tblXMLSettingRepository())
                        using (tblXMLMappingRepository map = new tblXMLMappingRepository())
                        {
                            tblXMLSetting setting = rep.get(s.SettingName);
                            if (setting != null)
                            {
                                SQLName  = setting.SQLName;
                                FileName = setting.FileName + ((string.IsNullOrEmpty(setting.FileNameDateFormat)) ? ".xml" : DateTime.Now.ToString(setting.FileNameDateFormat.Replace(",", "")) + ".xml");
                            }
                            List <tblXMLMapping> mapping = map.get(s.SettingName).ToList();
                            using (tblSQLSettingRepository set = new tblSQLSettingRepository())
                            {
                                tblSQLSetting sqlSetting = set.select(SQLName);
                                using (DataAccess da = new DataAccess())
                                {
                                    Tuple <bool, DataTable, string> result = da.TryExecuteDataTable(sqlSetting.SQLStatement, null, null);
                                    if (!result.Item1)
                                    {
                                        log.Save("轉出", "Schedule", s.CustomerName, s.Format, "", s.Email, s.FTPServer, FileName, "失敗", result.Item3);
                                    }

                                    XmlDocument       xmlDoc   = XmlProcess.GenerateXML(result.Item2, mapping);
                                    XmlWriterSettings settings = new XmlWriterSettings();
                                    settings.Indent              = true;
                                    settings.OmitXmlDeclaration  = false;
                                    settings.NewLineOnAttributes = true;
                                    settings.Encoding            = Encoding.GetEncoding("utf-8");

                                    // Path
                                    if (Destinations.Contains("1"))
                                    {
                                        try
                                        {
                                            using (Stream fs = File.Open(s.Path + "/" + FileName, FileMode.CreateNew))
                                            {
                                                XmlWriter writer = XmlWriter.Create(fs, settings);
                                                xmlDoc.WriteTo(writer); // Write to memorystream
                                                writer.Flush();
                                                fs.Close();
                                            }
                                            //xmlDoc.Save(s.Path + "/" + FileName);
                                        }
                                        catch (Exception ex)
                                        {
                                            exeResult = ex.Message.Replace("\r\n", "");
                                        }
                                        if (!string.IsNullOrEmpty(exeResult))
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "PATH", s.Email, s.FTPServer, FileName, "失敗", exeResult);
                                        }
                                        else
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "PATH", s.Email, s.FTPServer, FileName, "成功", "");
                                        }
                                    }

                                    if (Destinations.Contains("2") || Destinations.Contains("3"))
                                    {
                                        using (Stream fs = File.Open(System.AppDomain.CurrentDomain.BaseDirectory + "/Files/" + FileName, FileMode.CreateNew))
                                        {
                                            XmlWriter writer = XmlWriter.Create(fs, settings);
                                            xmlDoc.WriteTo(writer); // Write to memorystream
                                            writer.Flush();
                                            fs.Close();
                                        }
                                        //xmlDoc.Save(System.AppDomain.CurrentDomain.BaseDirectory + "/Files/" + FileName);
                                    }

                                    // Email
                                    if (Destinations.Contains("2"))
                                    {
                                        string subject = string.Empty;
                                        using (bscodeRepository bscode = new bscodeRepository())
                                        {
                                            subject = bscode.getSubject(sqlSetting.SQLType);
                                        }
                                        MailProcess sender   = new MailProcess();
                                        EmailData   mailData = new EmailData()
                                        {
                                            To         = s.Email,
                                            Subject    = subject,
                                            Attachment = new FileInfo(System.AppDomain.CurrentDomain.BaseDirectory + "/Files/" + FileName)
                                        };
                                        exeResult = sender.SendEmail(mailData);
                                        if (!string.IsNullOrEmpty(exeResult))
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "EMail", s.Email, s.FTPServer, FileName, "失敗", exeResult);
                                        }
                                        else
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "EMail", s.Email, s.FTPServer, FileName, "成功", "");
                                        }
                                    }
                                    // FTP
                                    if (Destinations.Contains("3"))
                                    {
                                        FTPData ftpData = new FTPData()
                                        {
                                            FTPServerIP = s.FTPServer,
                                            Port        = 21,
                                            UserName    = s.FTPAccount,
                                            Password    = s.FTPPassword,
                                            file        = new FileInfo(System.AppDomain.CurrentDomain.BaseDirectory + "/Files/" + FileName)
                                        };
                                        FtpProcess uploader = new FtpProcess();
                                        exeResult = uploader.Upload(ftpData);
                                        if (!string.IsNullOrEmpty(exeResult))
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "FTP", s.Email, s.FTPServer, FileName, "失敗", exeResult);
                                        }
                                        else
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "FTP", s.Email, s.FTPServer, FileName, "成功", "");
                                        }
                                    }
                                }
                            }
                        }
                }
                #endregion
                #region EXCEL
                else if (s.Format.Equals("EXCEL"))
                {
                    using (tblExcelSettingRepository rep = new tblExcelSettingRepository())
                        using (tblExcelMappingRepository map = new tblExcelMappingRepository())
                        {
                            tblExcelSetting setting = rep.get(s.SettingName);
                            if (setting != null)
                            {
                                SQLName  = setting.SQLName;
                                FileName = setting.FileName + ((string.IsNullOrEmpty(setting.FileNameDateFormat)) ? ".xls" : DateTime.Now.ToString(setting.FileNameDateFormat.Replace(",", "")) + ".xls");
                            }

                            List <tblExcelMapping> mapping = map.get(s.SettingName).ToList();
                            using (tblSQLSettingRepository set = new tblSQLSettingRepository())
                            {
                                tblSQLSetting sqlSetting = set.select(SQLName);
                                using (DataAccess da = new DataAccess())
                                {
                                    Tuple <bool, DataTable, string> result = da.TryExecuteDataTable(sqlSetting.SQLStatement, null, null);
                                    if (!result.Item1)
                                    {
                                        log.Save("轉出", "Schedule", s.CustomerName, s.Format, "", s.Email, s.FTPServer, FileName, "失敗", result.Item3);
                                    }

                                    HSSFWorkbook book = ExcelProcess.GenerateExcel(result.Item2, mapping);

                                    // Path
                                    if (Destinations.Contains("1"))
                                    {
                                        FileStream file = new FileStream(s.Path + "\\" + FileName, FileMode.Create);//產生檔案
                                        book.Write(file);
                                        file.Close();
                                        if (!string.IsNullOrEmpty(exeResult))
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "PATH", s.Email, s.FTPServer, FileName, "失敗", exeResult);
                                        }
                                        else
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "PATH", s.Email, s.FTPServer, FileName, "成功", "");
                                        }
                                    }
                                    if (Destinations.Contains("2") || Destinations.Contains("3"))
                                    {
                                        FileStream file = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + "/Files/" + FileName, FileMode.Create);//產生檔案
                                        book.Write(file);
                                        file.Close();
                                    }
                                    // EMail
                                    if (Destinations.Contains("2"))
                                    {
                                        string subject = string.Empty;
                                        using (bscodeRepository bscode = new bscodeRepository())
                                        {
                                            subject = bscode.getSubject(sqlSetting.SQLType);
                                        }
                                        MailProcess sender   = new MailProcess();
                                        EmailData   mailData = new EmailData()
                                        {
                                            To         = s.Email,
                                            Subject    = subject,
                                            Attachment = new FileInfo(System.AppDomain.CurrentDomain.BaseDirectory + "/Files/" + FileName)
                                        };
                                        exeResult = sender.SendEmail(mailData);
                                        if (!string.IsNullOrEmpty(exeResult))
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "EMail", s.Email, s.FTPServer, FileName, "失敗", exeResult);
                                        }
                                        else
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "EMail", s.Email, s.FTPServer, FileName, "成功", "");
                                        }
                                    }
                                    // FTP
                                    if (Destinations.Contains("3"))
                                    {
                                        FTPData ftpData = new FTPData()
                                        {
                                            FTPServerIP = s.FTPServer,
                                            Port        = 21,
                                            UserName    = s.FTPAccount,
                                            Password    = s.FTPPassword,
                                            file        = new FileInfo(System.AppDomain.CurrentDomain.BaseDirectory + "/Files/" + FileName)
                                        };
                                        FtpProcess uploader = new FtpProcess();
                                        exeResult = uploader.Upload(ftpData);
                                        if (!string.IsNullOrEmpty(exeResult))
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "FTP", s.Email, s.FTPServer, FileName, "失敗", exeResult);
                                        }
                                        else
                                        {
                                            log.Save("轉出", "Schedule", s.CustomerName, s.Format, "FTP", s.Email, s.FTPServer, FileName, "成功", "");
                                        }
                                    }
                                }
                            }
                        }
                }
                #endregion
            }
            catch (Exception ex)
            {
                exeResult = ex.Message.Replace("\r\n", "");
                log.Save("轉出", "Schedule", s.CustomerName, s.Format, "", s.Email, s.FTPServer, FileName, "失敗", exeResult);
            }
            finally
            {
                FileInfo file = new FileInfo(System.AppDomain.CurrentDomain.BaseDirectory + "/Files/" + FileName);
                Func.DelAttachment(file);
            }
        }