Пример #1
0
        /// <summary>
        /// write log info to redis
        /// </summary>
        /// <param name="errorModel">log info.</param>
        /// <returns></returns>
        private Task <long> WriteAllLogToRedis(ErrorInfoLogModel errorModel)
        {
            var cachKey = AppConfigurationHelper.GetAppSettings <CacheLogModel>("AppSettings:ErrorLogCache");

            cachKey = string.IsNullOrEmpty(cachKey?.Cachekey) ? new CacheLogModel {
                Cachekey = "ErrorLogCache", DatabaseNumber = 1
            } : cachKey;
            var addTask = RedisCacheHelper.AddListAsync(cachKey.Cachekey, errorModel, cachKey.DatabaseNumber);

            return(addTask);
        }
Пример #2
0
        /// <summary>
        /// Stock Method
        /// </summary>
        private async void StockErrorLogInfo()
        {
            var logInfoDataAccess = new LogInfoDataAccess();
            var cacheKey          = AppConfigurationHelper.GetAppSettings <CacheLogModel>("AppSettings:ErrorLogCache");

            cacheKey = string.IsNullOrEmpty(cacheKey?.Cachekey) ? new CacheLogModel {
                Cachekey = "ErrorLogCache", DatabaseNumber = 1
            } : cacheKey;
            long cacheListLength = RedisCacheHelper.GetListLength(cacheKey.Cachekey, cacheKey.DatabaseNumber);

            while (cacheListLength > 0)
            {
                var cacheModel = RedisCacheHelper.GetLastOneList <ErrorInfoLogModel>(cacheKey.Cachekey,
                                                                                     cacheKey.DatabaseNumber);
                await logInfoDataAccess.AddLogInfoAsync(cacheModel);

                cacheListLength = RedisCacheHelper.GetListLength(cacheKey.Cachekey, cacheKey.DatabaseNumber);
            }
        }
 /// <summary>
 /// Get single connection object
 /// </summary>
 /// <returns></returns>
 public static ConnectionMultiplexer GetConnection()
 {
     if (_conn == null)
     {
         lock (SyncRoot)
         {
             if (_conn == null)
             {
                 var appSettings      = AppConfigurationHelper.GetAppSettings <AppSettingsModel>("AppSettings");
                 var connectionString = appSettings?.RedisCaching?.ConnectionString;
                 if (string.IsNullOrEmpty(connectionString))
                 {
                     throw new ArgumentException("Redis connection config is Empty,please check you config.");
                 }
                 _conn = ConnectionMultiplexer.Connect(connectionString);
             }
         }
     }
     return(_conn);
 }
Пример #4
0
        /// <summary>
        /// Send email method.
        /// </summary>
        /// <param name="toEmailAddress">send to email address.</param>
        /// <param name="subject">email subject.</param>
        /// <param name="message">send email content,txt or html boy,if html body ,you should set isHtmlBody param is true.</param>
        /// <param name="toName">send to email name,could by null,if null will use default string.</param>
        /// <param name="isHtmlBody">flag the send email </param>
        public static async void SendEmailAsync(string toEmailAddress, string subject, string message,
            string toName = null, bool isHtmlBody = false)
        {
            if (string.IsNullOrEmpty(toEmailAddress)) throw new ArgumentNullException(nameof(toEmailAddress));
            if (string.IsNullOrEmpty(message)) throw new ArgumentNullException(nameof(message));
            if (string.IsNullOrEmpty(subject)) throw new ArgumentNullException(nameof(subject));
            var emailSereverConfigModel =
                AppConfigurationHelper.GetAppSettings<EmailServerConfigModel>("AppSettings:EmailServerConfig");
            if (string.IsNullOrEmpty(emailSereverConfigModel?.FromEmailAddress)
                || string.IsNullOrEmpty(emailSereverConfigModel.FromEmailPassword)
                || string.IsNullOrEmpty(emailSereverConfigModel.EmailSmtpServerAddress))
            {
                throw new Exception("Email config error,please check you config.FromEmailAddress,EmailSmtpServerAddress,FromEmailPassword filed is must have.");
            }

            var emailMessage = new MimeMessage();
            emailMessage.From.Add(new MailboxAddress(emailSereverConfigModel.FromName, emailSereverConfigModel.FromEmailAddress));

            emailMessage.To.Add(new MailboxAddress(toName ?? "FreshMan Server Email", toEmailAddress));
            emailMessage.Subject = subject;
            if (isHtmlBody)
            {
                var bodyBuilder = new BodyBuilder { HtmlBody = message };
                emailMessage.Body = bodyBuilder.ToMessageBody();
            }
            else
            {
                emailMessage.Body = new TextPart("plain") { Text = message };
            }
            using (var client = new SmtpClient())
            {
                await client.ConnectAsync(emailSereverConfigModel.EmailSmtpServerAddress);
                await client.AuthenticateAsync(emailSereverConfigModel.FromEmailAddress, emailSereverConfigModel.FromEmailPassword);
                await client.SendAsync(emailMessage).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
Пример #5
0
 public ApiResultModel <DataBaseModel> AddNewFile()
 {
     long size         = 0;
     var  files        = Request.Form.Files;
     var  newName      = HttpContext.GetStringFromParameters("fileName");
     var  fileRootPath = AppConfigurationHelper.GetAppSettings("AppSettings:FileSavePath");
     //one file or multifile
     var file = files.FirstOrDefault();
     {
         var filesuffix          = Path.GetExtension(file.FileName);
         var fileName            = string.IsNullOrEmpty(newName) ? ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"') : newName + filesuffix;
         var dirfilePath         = hostingEnv.WebRootPath + $@"\{fileRootPath}";
         var dirfileSavePullName = dirfilePath + $@"\{fileName}";
         size += file.Length;
         if (!Directory.Exists(dirfilePath))
         {
             Directory.CreateDirectory(dirfilePath);
         }
         using (FileStream fs = System.IO.File.Create(dirfileSavePullName))
         {
             file.CopyTo(fs);
             fs.Flush();
         }
         var newFile = new ChooseImageInfo();
         newFile.ImageCreateTime = DateTime.Now;
         newFile.ImageDriverFlag = Guid.NewGuid().ToString();
         newFile.ImageName       = fileName;
         newFile.ImagePath       = $@"\{fileRootPath}\{fileName}";
         newFile.ImageSize       = file.Length;
         UploadFileServer.StorageFile(newFile);
         var resutleInfo = new DataBaseModel();
         resutleInfo.StateCode = "200";
         resutleInfo.StateDesc = $"/{fileRootPath}/{fileName}";
         return(ResponseDataApi(resutleInfo));
     }
 }
Пример #6
0
        /// <summary>
        /// Init db
        /// </summary>
        private static void SetupDB()
        {
            /// <summary>
            /// Db username
            /// </summary>
            string _userName = "******";

            /// <summary>
            /// Db password
            /// </summary>
            string _password = "******";

            /// <summary>
            /// Db host name
            /// </summary>
            string _hostName = "localhost";

            /// <summary>
            /// Db port
            /// </summary>
            int _port = 3306;

            /// <summary>
            /// Db name
            /// </summary>
            string _dbName = "sys";
            var    mysqlConnectionString = $"Server={_hostName};Port={_port};User Id={_userName};Password={_password};Database={_dbName};SslMode=None";
            var    dbrecreated           = false;

            SimpleCRUD.SetDialect(SimpleCRUD.Dialect.MySQL);
            using (var connection = SqlConnectionHelper.GetOpenConnection(mysqlConnectionString))
            {
                try
                {
                    connection.Execute(@" DROP DATABASE SimplecrudDemoWebsite; ");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("database drop  failed - close and reopen VS and try again:" + ex.Message);
                }
                try
                {
                    connection.Execute(@" CREATE DATABASE SimplecrudDemoWebsite; ");
                    dbrecreated = true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("database create failed - close and reopen VS and try again:" + ex.Message);
                }
            }
            if (!dbrecreated)
            {
                return;
            }
            mysqlConnectionString = AppConfigurationHelper.GetAppSettings("AppSettings:MySqlConnectionString");
            using (var connection = SqlConnectionHelper.GetOpenConnection(mysqlConnectionString))
            {
                connection.Execute(@" DROP TABLE IF EXISTS `car`;
CREATE TABLE `car` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Make` varchar(100) NOT NULL,
  `ModelName` varchar(100) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ");
                connection.Insert(new CarViewModel()
                {
                    Make = "Honda", ModelName = "Civic"
                });
                connection.Execute(@" DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
  `UserId` int(11) NOT NULL AUTO_INCREMENT,
  `FirstName` varchar(100) NOT NULL,
  `LastName` varchar(100) NOT NULL,
  `intAge` int(11) NOT NULL,
  PRIMARY KEY (`UserId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ");
                connection.Insert(new UserViewModel()
                {
                    Age = 42, FirstName = "Jim", LastName = "Smith"
                });
                connection.Execute(@" DROP TABLE IF EXISTS `guidtest`;
CREATE TABLE `guidtest` (
   `Id` int(11) Not NULL AUTO_INCREMENT,
  `guid` char(36) NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ");
                connection.Insert(new GUIDTestViewModel {
                    guid = Guid.NewGuid().ToString(), name = "Example"
                });

                int x = 1;
                do
                {
                    connection.Insert(new User {
                        FirstName = "Jim ", LastName = "Smith " + x, Age = x
                    });
                    x++;
                } while (x < 101);
            }
        }
Пример #7
0
        /// <summary>
        /// cut put point.
        /// </summary>
        static SqlConnectionHelper()
        {
            var appSettings = AppConfigurationHelper.GetAppSettings <AppSettingsModel>("AppSettings");

            ConnectionString = appSettings?.MySqlConnectionString;
        }