• 封装基本类在项目中的应用


    相信大家在使用.net开发的时候都会封装好自己的基本类,基本类包括很多比如保存数据、验证各样控件和发送邮件等等,下面就是开发过程中用到的,我整理了好长时间才搞好所以觉得有必要粘贴在这里。希望对大家有用!

    public class WebBaseSetData : WebBasePage

    {

       public WebBaseSetData() {
            //
            // TODO: Add constructor logic here
            //
        }
       

        protected virtual void InitForm() {

        }

        protected virtual bool SaveDataDetail() {
            return true;
        }

        protected virtual void SaveDataDetailAfter() {

        }

        protected bool SaveData() {
            try {
                if (!CheckBeforeSave()) {
                    return false;
                }

                bool RtnValue = SaveDataDetail();
                if (RtnValue) {

                }
                SaveDataDetailAfter();
                return RtnValue;
            }
            catch (Exception E) {
                string ErrMsg = E.Message;
                ErrMsg = ErrMsg.Replace("\r", "");
                ErrMsg = ErrMsg.Replace("\n", "");
                ErrMsg = ErrMsgCtr(ErrMsg);
                ErrMsgStr = ErrMsg;

                return false;
            }
        }

      

     #region Validation of Input

        protected virtual bool CheckBeforeSave() {
            return true;
        }

        protected bool CheckNull(System.Web.UI.WebControls.WebControl Control, string HintMsg) {
            bool RtnValue = true;
            if (Control is TextBox) {
                if ((Control as TextBox).Text.Trim() == "") {
                    RtnValue = false;
                }
            }
            else if (Control is DropDownList) {
                if ((Control as DropDownList).SelectedValue.ToString() == "") {
                    RtnValue = false;
                }
            }

            if (!RtnValue) {
                ShowErrMsg(HintMsg);
            }

            return RtnValue;
        }

        protected void CheckIsEmial(TextBox[] itxtArray) {
            for (int i = 0; i < itxtArray.Length; i++) {
                itxtArray[i].Attributes["onchange"] = "return isEmail(this.value,'.');";
            }
        }

        protected void CheckIsDateTime(TextBox[] itxtArray) {
            for (int i = 0; i < itxtArray.Length; i++) {
                itxtArray[i].Attributes["onchange"] = "return isDateTime(this.value,'.');";
            }
        }

        protected void CheckIsDate(TextBox[] itxtArray) {
            for (int i = 0; i < itxtArray.Length; i++) {
                itxtArray[i].Attributes["onchange"] = "return isDate(this.value,'.');";
            }
        }

        protected void CheckIsNum(TextBox[] itxtArray) {
            for (int i = 0; i < itxtArray.Length; i++) {
                itxtArray[i].Attributes["onchange"] = "return isNumberStr(this.value);";
            }
        }

        protected void CheckIsRegisterName(TextBox[] itxtArray) {
            for (int i = 0; i < itxtArray.Length; i++) {
                itxtArray[i].Attributes["onchange"] = "return isRegisterUserName(this.value);";
            }
        }

        protected void SetDeleteBtn(Button Btn) {
            Btn.Attributes["onclick"] = "return confirm('是否要删除');";
        }

        protected void SetDeleteImgBtn(ImageButton ImgBtn) {
            ImgBtn.Attributes["onclick"] = "return confirm('是否要删除');";

        }

        #endregion

        #region about upload

        protected void DeleFile(string FilePath) {
            File.Delete(FilePath);
        }

        private void CreatDir(string FileTmpPath) {

            if (!Directory.Exists(FileTmpPath)) {
                Directory.CreateDirectory(FileTmpPath);
            }

        }

        protected virtual void UpLoadEnd(string FilePath) {

        }

        protected bool UpLoadData(FileUpload MyFile, string LogicPath) {
            string filename = "", fileExtension = "", fullname = "";
            LogicPath = Server.MapPath(".") + @"\" + LogicPath;

            CreatDir(LogicPath);

            if (MyFile.PostedFile != null) {
                filename = Path.GetFileName(MyFile.PostedFile.FileName);
                fileExtension = Path.GetExtension(MyFile.PostedFile.FileName);
                fullname = LogicPath + @"\" + Guid.NewGuid().ToString() + "_" + filename;

                try {
                    MyFile.PostedFile.SaveAs(fullname);
                    UpLoadEnd(fullname);
                    return true;

                }
                catch (Exception S) {
                    throw S;
                }
            }
            return false;
        }

        protected string ReadFileByType(string FilePath) {
            string RetStr = "";
            int i = 0;

            File.SetAttributes(FilePath, FileAttributes.Normal);
            FileStream TmpStr = new FileStream(FilePath, FileMode.Open);

            if (TmpStr.CanRead) {
                for (; (i = TmpStr.ReadByte()) != -1; ) {
                    RetStr += (char)i;
                }
            }

            TmpStr.Close();

            File.SetAttributes(FilePath, FileAttributes.ReadOnly);

            return RetStr;
        }

        #endregion

      #region
        protected void VwObjToEntity<T>(T VwObj, T Entity) {
            foreach (PropertyInfo pro in typeof(T).GetProperties()) {
                if (!pro.CanRead) {
                    continue;
                }
                if (!pro.CanWrite) {
                    continue;
                }

                if (pro.GetValue(VwObj, null) != null) {
                    pro.SetValue(Entity, pro.GetValue(VwObj, null), null);
                }
                else {
                    pro.SetValue(Entity, null, null);
                }
            }
        }

        protected void SetObjToEntity<T, M>(T Sobj, M Eobj, string except) {
            foreach (PropertyInfo proM in typeof(M).GetProperties()) {
                if (except.IndexOf(proM.Name) >= 0) {
                    continue;
                }

                foreach (PropertyInfo proT in typeof(T).GetProperties()) {
                    if (proM.Name == proT.Name) {
                        if (proT.GetValue(Sobj, null) != null) {
                            if (proM.PropertyType == typeof(System.Nullable<double>) || proM.PropertyType == typeof(System.Double)) {
                                proM.SetValue(Eobj, Convert.ToDouble(proT.GetValue(Sobj, null)), null);
                            }
                            else if (proM.PropertyType == typeof(System.Nullable<Int16>)) {
                                proM.SetValue(Eobj, Convert.ToInt16(proT.GetValue(Sobj, null)), null);
                            }
                            else if (proM.PropertyType == typeof(System.Byte)) {
                                proM.SetValue(Eobj, Convert.ToByte(proT.GetValue(Sobj, null)), null);
                            }
                            else if (proM.PropertyType == typeof(System.Decimal)) {
                                proM.SetValue(Eobj, Convert.ToDecimal(proT.GetValue(Sobj, null)), null);
                            }
                            else if (proT.PropertyType == typeof(System.Char)) {
                                proM.SetValue(Eobj, Convert.ToString(proT.GetValue(Sobj, null)), null);
                            }
                            else if (proM.PropertyType == typeof(System.Char)) {
                                proM.SetValue(Eobj, Convert.ToChar(proT.GetValue(Sobj, null)), null);
                            }
                            else {
                                proM.SetValue(Eobj, proT.GetValue(Sobj, null), null);
                            }
                        }
                    }
                }
            }
        }

        #endregion

    #region --SendEmail--

        protected string GetEmailBody(string EmailTemplateName) {
            String EmailBody = "";
            EmailBody = ReadFileByType(HttpContext.Current.Request.PhysicalApplicationPath + @"EmailTemplate\" + EmailTemplateName);
            return EmailBody;
        }

        protected void SendMailBodyToList(String Subject, String EmailBody, List<String> ToList) {

            String MailServer = ConfigurationSettings.AppSettings["MailServer"];
            String FromName = ConfigurationSettings.AppSettings["MailFromName"];
            String FromAddr = ConfigurationSettings.AppSettings["MailFromAddress"];
            List<String> To = ToList;

            SendEmail(FromName, FromAddr, To, new List<string> { }, new List<string> { }, MailServer, "", "", new List<string> { }, Subject, EmailBody, true, null, 60, false);

        }


        protected void SendMailToList(string EmailTemplateName, List<String> ToList) {
            String EmailBody = "";
            EmailBody = ReadFileByType(HttpContext.Current.Request.PhysicalApplicationPath + @"EmailTemplate\" + EmailTemplateName);
            String MailServer = ConfigurationSettings.AppSettings["MailServer"];
            String FromName = ConfigurationSettings.AppSettings["MailFromName"];
            String FromAddr = ConfigurationSettings.AppSettings["MailFromAddress"];
            List<String> To = ToList;
            String Subject = "Register mail";
            SendEmail(FromName, FromAddr, To, new List<string> { }, new List<string> { }, MailServer, "", "", new List<string> { }, Subject, EmailBody, true, null, 60, false);
        }

        public event SendCompletedEventHandler AsyncSendCompleted;

        private void SendEmail(String fromName, String fromEmail, List<String> recipients, List<String> bccs, List<String> ccs, String server, String username, String password, List<String> attachments, String subject, String body, Boolean isBodyHtml, Object obj, int timeout, Boolean needAuthenticate) {
            MailAddress from = new MailAddress(fromEmail, fromName);
            MailMessage mail = new MailMessage();
            foreach (var to in recipients) {
                mail.To.Add(to);
            }
            mail.From = from;
            mail.Headers.Add("X-Priority", "3");
            mail.Headers.Add("X-MSMail-Priority", "Normal");
            mail.Headers.Add("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
            mail.Headers.Add("X-MimeOLE", "Produced By Microsoft MimeOLE V6.00.2900.2869");
            foreach (var bcc in bccs) {
                mail.Bcc.Add(bcc);
            }
            foreach (var cc in ccs) {
                mail.CC.Add(cc);
            }
            string a = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(subject));
            mail.Subject = subject;
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.Body = body;
            mail.IsBodyHtml = isBodyHtml;
            foreach (String attachment in attachments) {
                Attachment data = new Attachment(attachment);
                mail.Attachments.Add(data);
            }

            SmtpClient client = new SmtpClient(server);

            client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);

            client.Timeout = timeout * 1000;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            if (needAuthenticate) {
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(username, password);
            }
            else {
                client.UseDefaultCredentials = true;
            }
            client.Send(mail);

        }

        void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) {
            AsyncSendCompleted(sender, e);
        }
        #endregion

    }

  • 相关阅读:
    动态存储区(堆)、动态存储区(栈)、静态存储区、程序代码区
    auto, extern, register, static
    #include <iomanip>
    use
    ZooKeeper某一QuorumPeerMain挂了
    python 中的 字符串 列表 元祖 字典
    JAVA的23种设计模式
    spark job分析
    Spark1
    SQL三大范式
  • 原文地址:https://www.cnblogs.com/meetweb/p/1490870.html
Copyright © 2020-2023  润新知