Exemplo n.º 1
0
        private void Login(string LoginId, string Password)
        {
            var response = new LogonService().LoginUser(LoginId, Password, HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);

            Session.Timeout = AppConfigurationHelper.GetValue <int>(ConfigKeys.SessionTimeout);
            UserEntity user        = DataHelper.GetObject <UserEntity>(response);
            var        userSession = DataHelper.GetObject <UserSession>(response);

            SessionClass.LoginUserEntity = user;
            // SessionClass.FinancialYearId = new AcademicYearData().GetAcademicYear().Where(x => x.IsActive == true).FirstOrDefault().FinancialYearId;


            var userData = new UserSessionData {
                UserDisplayName = user.UserName, UserId = user.UserId, RoleId = user.RoleId, LoginTime = DateTime.Now, MenuList = DataHelper.GetListLevelZero <MenuEntity>(response)
            };

            var contextInfo = new ContextInfo {
                UserId = userSession.UserId, SessionId = userSession.Sessionid
            };

            Session[ctlMasterPage.ContextInfo]       = contextInfo;
            Session[ctlMasterPage.UserSessionObject] = userData;

            FormsAuthentication.SetAuthCookie(Page.User.Identity.Name, false);

            // Response.Redirect("~/UI/AdminDashBoard.aspx", false);

            Response.Redirect("~/UI/DashBoard.aspx", false);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 方法执行前,如果没有登录就调整到Passport登录页面,没有权限就抛出信息
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            #region [1、验证是否在服务时间内]

            var startTimeStr = AppConfigurationHelper.GetString("SystemRunStartTime");
            var endTimeStr   = AppConfigurationHelper.GetString("SystemRunEndTime");
            //没有配置时间
            if (!string.IsNullOrEmpty(startTimeStr) && !string.IsNullOrEmpty(endTimeStr))
            {
                var startTime = DataTypeConvertHelper.ToDateTime(startTimeStr);
                var endTime   = DataTypeConvertHelper.ToDateTime(endTimeStr);

                if (startTime <= new DateTime(1900, 1, 1) || endTime <= new DateTime(1900, 1, 1))
                {
                    filterContext.Result = Request.UrlReferrer != null?Stop("系统运行时间配置错误!", Request.UrlReferrer.AbsoluteUri) : Content("系统运行时间配置错误!");

                    return;
                }
                startTime = new DateTime(1900, 1, 1, startTime.Hour, startTime.Minute, startTime.Second);
                endTime   = new DateTime(1900, 1, 1, endTime.Hour, endTime.Minute, endTime.Second);
                var newTime = DateTime.Now;
                newTime = new DateTime(1900, 1, 1, newTime.Hour, newTime.Minute, newTime.Second);
                if (newTime < startTime || newTime > endTime)
                {
                    filterContext.Result = Request.UrlReferrer != null?Stop("系统处于维护期!", Request.UrlReferrer.AbsoluteUri) : Content("系统处于维护期!");
                }
            }

            #endregion
        }
Exemplo n.º 3
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 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 mailUserName     = AppConfigurationHelper.GetString("FromName");
            var fromEmailAddress = AppConfigurationHelper.GetString("FromEmailAddress");
            var mailServer       = AppConfigurationHelper.GetString("EmailSmtpServerAddress");
            var mailPassword     = AppConfigurationHelper.GetString("FromEmailPassword");

            if (string.IsNullOrEmpty(fromEmailAddress) ||
                string.IsNullOrEmpty(mailPassword) ||
                string.IsNullOrEmpty(mailServer))
            {
                throw new Exception("Email config error,please check you config.FromEmailAddress,EmailSmtpServerAddress,FromEmailPassword filed is must have.");
            }
            new Thread(delegate()
            {
                SmtpClient smtp = new SmtpClient
                {
                    Host        = mailServer,
                    Port        = 25,
                    Credentials = new NetworkCredential(fromEmailAddress, mailPassword)
                };
                //邮箱的smtp地址
                //端口号
                //构建发件人的身份凭据类
                //构建消息类
                MailMessage objMailMessage = new MailMessage
                {
                    //设置优先级
                    Priority = MailPriority.High,
                    //消息发送人
                    From = new MailAddress(fromEmailAddress, mailUserName, Encoding.UTF8)
                };
                //收件人
                objMailMessage.To.Add(toEmailAddress);
                //标题
                objMailMessage.Subject = subject.Trim();
                //标题字符编码
                objMailMessage.SubjectEncoding = Encoding.UTF8;
                //正文
                objMailMessage.Body       = message;
                objMailMessage.IsBodyHtml = true;
                //内容字符编码
                objMailMessage.BodyEncoding = Encoding.UTF8;
                //发送
                smtp.Send(objMailMessage);
            }).Start();
        }
Exemplo n.º 4
0
        protected override void OnStart(string[] args)
        {
            FileLog.Initialize(ServiceName);
            string serviceAssembly   = AppConfigurationHelper.GetConfiguration("ServiceAssembly");
            string serviceType       = AppConfigurationHelper.GetConfiguration("ServiceType");
            string InterfaceAssembly = AppConfigurationHelper.GetConfiguration("InterfaceAssembly");
            string InterfaceType     = AppConfigurationHelper.GetConfiguration("InterfaceType");
            string baseUri           = AppConfigurationHelper.GetConfiguration("BaseUri");
            string mexUri            = AppConfigurationHelper.GetConfiguration("MexUri");

            _host = CreateServiceHost(
                serviceAssembly,
                serviceType,
                InterfaceAssembly,
                InterfaceType,
                baseUri,
                mexUri);
            try
            {
                _host.Open();
            }
            catch (Exception e)
            {
                string message = string.Format("Error starting service {0}", ServiceName);
                FileLog.Fatal(message, e);
                throw;
            }

            FileLog.Info(string.Format("Service {0} started. Address: {1}.", ServiceName, baseUri));
        }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
0
        /// <summary>
        /// 测试数据连接
        /// </summary>
        public void DbLink()
        {
            var linkStr = AppConfigurationHelper.GetString("DbString");
            var dual    = AppConfigurationHelper.GetString("DbDual");

            using (var conn = SqlConnectionHelper.GetOpenConnection(linkStr))
            {
                var data = conn.Query(dual);
                Console.WriteLine(data);
            }
        }
Exemplo n.º 7
0
        private void InitializeStaticResource()
        {
            ViewBag.RootNode = AppConfigurationHelper.GetString("ReferenceKey.RootNode") ?? string.Empty;
            var dicSlider    = new SysDicService().GetDicByValue("IndexSlider")?.FirstOrDefault();
            var sliderServer = new SysAdvertiseService();

            ViewBag.SliderList = null;
            if (dicSlider != null)
            {
                ViewBag.SliderList = sliderServer.GetList(dicSlider.Id, 1, 10, out _);
            }
        }
Exemplo n.º 8
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 void SendEmail(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 mailUserName     = AppConfigurationHelper.GetString("FromName");
            var fromEmailAddress = AppConfigurationHelper.GetString("FromEmailAddress");
            var mailServer       = AppConfigurationHelper.GetString("EmailSmtpServerAddress");
            var mailPassword     = AppConfigurationHelper.GetString("FromEmailPassword");

            if (string.IsNullOrEmpty(fromEmailAddress) ||
                string.IsNullOrEmpty(mailPassword) ||
                string.IsNullOrEmpty(mailServer))
            {
                throw new Exception("Email config error,please check you config.FromEmailAddress,EmailSmtpServerAddress,FromEmailPassword filed is must have.");
            }
            MailMessage messageModel = new MailMessage();

            // 接收人邮箱地址
            messageModel.To.Add(new MailAddress(toEmailAddress));
            messageModel.From         = new MailAddress(fromEmailAddress, mailUserName);
            messageModel.BodyEncoding = Encoding.GetEncoding("UTF-8");
            messageModel.Body         = message;
            //GB2312
            messageModel.SubjectEncoding = Encoding.GetEncoding("UTF-8");
            messageModel.Subject         = subject;
            messageModel.IsBodyHtml      = isHtmlBody;

            SmtpClient smtpclient = new SmtpClient(mailServer, 25)
            {
                EnableSsl   = true,
                Credentials = new NetworkCredential(mailUserName, mailPassword)
            };

            //SSL连接
            try
            {
                smtpclient.Send(messageModel);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
        }
        public static string JsCssFile(this UrlHelper helper, string path)
        {
            var jsAndCssFileEdition = AppConfigurationHelper.GetString("JsAndCssFileEdition");

            if (string.IsNullOrEmpty(jsAndCssFileEdition))
            {
                jsAndCssFileEdition = Guid.NewGuid().ToString();
            }

            path += string.Format("?v={0}", jsAndCssFileEdition);

            return(helper.StaticFile(path));
        }
Exemplo n.º 10
0
 protected void Application_Start()
 {
     AreaRegistration.RegisterAllAreas();
     GlobalConfiguration.Configure(WebApiConfig.Register);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     BundleConfig.RegisterBundles(BundleTable.Bundles);
     AppConfigurationHelper.EncryptionConnectionString(ConfigurationManager.ConnectionStrings["pdb_ccmsContext"].ConnectionString);
     // Register mapping
     UnityConfig.RegisterMapping();
     //CardHolderCreateMapper.RegisterMapping();
     // end mapping
     AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
 }
Exemplo n.º 11
0
        public Startup1(IConfiguration configuration, IHostingEnvironment hostingEnvironment)
        {
            //IConfigurationBuilder builder = new ConfigurationBuilder()
            //   .SetBasePath(hostingEnvironment.ContentRootPath)
            //   .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            //   .AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: true);

            Server.ContentRootPath = Path.GetFullPath(@"..\..\..\..\..\") + @"src\My.D3";

            // 初始化config的配置为了读取appjson文件
            IConfigurationRoot configuration2 = AppConfigurationHelper.Get(Server.ContentRootPath);

            Configuration = configuration2;
            this._env     = hostingEnvironment;
        }
        /// <summary>
        /// 得到静态文件
        /// </summary>
        /// <param name="helper"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string StaticFile(this UrlHelper helper, string path)
        {
            var rootUrl = AppConfigurationHelper.GetString("ReferenceKey.RootNode") ?? string.Empty;

            if (string.IsNullOrWhiteSpace(path))
            {
                return("");
            }

            if (path.StartsWith("~"))
            {
                return(helper.Content(path));
            }
            else
            {
                return(rootUrl + path);
            }
        }
Exemplo n.º 13
0
        private static IWebHost BuildWebHost(string[] args, IConfigurationRoot configuration = null)
        {
            if (configuration == null)
            {
                configuration = AppConfigurationHelper.GetAppConfiguration(AppInfo.AppBasePath);
            }

            return(WebHost.CreateDefaultBuilder(args)
                   .UseConfiguration(configuration)
                   .UseStartup <Startup>()
                   .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(LogLevel.Trace);
            })
                   // NLog: Setup NLog for Dependency injection
                   .UseNLog()
                   .Build());
        }
Exemplo n.º 14
0
 /// <summary>
 /// Get single connection object
 /// </summary>
 /// <returns></returns>
 public static ConnectionMultiplexer GetConnection()
 {
     if (_conn == null)
     {
         lock (SyncRoot)
         {
             if (_conn == null)
             {
                 var connectionString = AppConfigurationHelper.GetString("RedisConnectionString");
                 if (string.IsNullOrEmpty(connectionString))
                 {
                     throw new ArgumentException("Redis connection config is Empty,please check you config.");
                 }
                 _conn = ConnectionMultiplexer.Connect(connectionString);
             }
         }
     }
     return(_conn);
 }
Exemplo n.º 15
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);
 }
Exemplo n.º 17
0
        public async Task <ActionResult> SaveUserAccess(UserAccessViewModel model, bool isUpdate = false)
        {
            string generatedPassword;
            var    _permissionAccess = model._userAccessPermission;

            _permissionAccess.Password = AppConfigurationHelper.PasswordGenerator();
            generatedPassword          = _permissionAccess.Password;


            _permissionAccess.Password = AppConfigurationHelper.AutoHashing(_permissionAccess.Password);
            var _SaveUserAccess = await UserAccessService.SaveUserAccess(_permissionAccess, isUpdate);

            if (_SaveUserAccess.flag == 0)
            {
                GenerateUserFolder(_permissionAccess.UserId);
            }
            if (_SaveUserAccess.flag == 0 && !string.IsNullOrEmpty(model._userAccessPermission.SelectedMapUserId))
            {
                var _SaveUserAccessMapping = await UserAccessService.SaveUserAccessMapping(model._userAccessPermission);

                if (isUpdate && !_permissionAccess.ChangePasswordInd)
                {
                    return(Json(new { resultCd = _SaveUserAccessMapping }, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    _SaveUserAccessMapping.desp = _SaveUserAccessMapping.flag == 0 ? _SaveUserAccessMapping.desp + ", password: "******", password: " + generatedPassword : _SaveUserAccess.desp;
                return(Json(new { resultCd = _SaveUserAccess }, JsonRequestBehavior.AllowGet));
            }
        }
Exemplo n.º 18
0
        protected override void OnStartup(StartupEventArgs e)
        {
            //this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            //ISeedDataService seedData = DependencyResolver.Kernel.Get<ISeedDataService>();
            //seedData.PopulateData();

            //Create a custom principal with an anonymous identity at startup
            CustomPrincipal customPrincipal = new CustomPrincipal();

            AppDomain.CurrentDomain.SetThreadPrincipal(customPrincipal);

            EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewKeyDownEvent, new KeyEventHandler(Grid_PreviewKeyDown));
            EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(Texbox_GotFocusEvent));
            EventManager.RegisterClassHandler(typeof(PasswordBox), PasswordBox.PreviewKeyDownEvent, new KeyEventHandler(Grid_PreviewKeyDown));
            EventManager.RegisterClassHandler(typeof(DatePicker), DatePicker.PreviewKeyDownEvent, new KeyEventHandler(Grid_PreviewKeyDown));
            EventManager.RegisterClassHandler(typeof(ComboBox), DatePicker.PreviewKeyDownEvent, new KeyEventHandler(Grid_PreviewKeyDown));

            ResourceDictionary dict = new ResourceDictionary();

            dict.Source = new Uri("\\Resources\\Languages\\StringResources-GER.xaml", UriKind.Relative);
            this.Resources.MergedDictionaries.Add(dict);

            base.OnStartup(e);

            try
            {
                AppConfigurationHelper.ReadConfig();

                WpfApiHandler.BaseApiUrl = AppConfigurationHelper.Configuration.ApiUrl;
            } catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            //Show the login view
            LoginWindow loginWindow = new LoginWindow();

            loginWindow.Show();
        }
Exemplo n.º 19
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);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Sends the Email
        /// </summary>
        /// <param name="lstTo">List of To email addresses</param>
        /// <param name="strSubject">Subject of Email</param>
        /// <param name="strBody">Body of Email</param>
        /// <param name="isHtml">if set to <c>true</c> [is HTML].</param>
        public void Send(IList <string> lstTo, string strSubject, string strBody, bool isHtml = false)
        {
            try
            {
                if (!AppConfigurationHelper.GetValue <bool>(ConfigKeys.EnableAlerts))
                {
                    return;
                }

                LogWriter.GetLogWriter().Debug("Sending email to " + string.Join(",", lstTo.ToArray()) + " Subject:" + strSubject + " Body:" + strBody);
                var mailMessage = new MailMessage {
                };
                mailMessage.From = new MailAddress(FromAddress);
                foreach (string strTo in lstTo)
                {
                    mailMessage.To.Add(new MailAddress(strTo));
                }
                mailMessage.Subject    = strSubject;
                mailMessage.Body       = strBody;
                mailMessage.IsBodyHtml = isHtml;

                var smtp = new SmtpClient(SmtpServer, Port)
                {
                };

                if (UseCredentials)
                {
                    smtp.Credentials = new NetworkCredential(Username, Password, Domain);
                }

                smtp.Send(mailMessage);
            }
            catch (Exception ex)
            {
                LogWriter.GetLogWriter().Exception(ex);
            }
        }
Exemplo n.º 21
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));
     }
 }
Exemplo n.º 22
0
        public void Send(string subject, string body, ListDictionary replacements, bool isHtml, params string[] recipients)
        {
            try
            {
                if (!AppConfigurationHelper.GetValue <bool>(ConfigKeys.EnableAlerts))
                {
                    return;
                }

                LogWriter.GetLogWriter().Debug(string.Format("Sending email to {0} Subject:{1} Body:{2}", string.Join(";", recipients), subject, body));

                var md = new MailDefinition
                {
                    From       = FromAddress,
                    Subject    = subject,
                    IsBodyHtml = isHtml
                };

                var smtp = new SmtpClient(SmtpServer, Port);
                if (UseCredentials)
                {
                    smtp.Credentials = new NetworkCredential(Username, Password, Domain);
                }

                if (File.Exists(body))
                {
                    md.BodyFileName = body;
                    smtp.Send(md.CreateMailMessage(string.Join(";", recipients), replacements == null ? new ListDictionary() : replacements, new System.Web.UI.Control()));
                }
                else
                {
                    smtp.Send(md.CreateMailMessage(string.Join(";", recipients), replacements == null ? new ListDictionary() : replacements, body, new System.Web.UI.Control()));
                }
            }
            catch (Exception ex) { LogWriter.GetLogWriter().Exception(ex); }
        }
Exemplo n.º 23
0
        public DbFixture()
        {
            var builder = new ContainerBuilder();
            //内存数据库
            var         option  = new DbContextOptionsBuilder <MyDbContext>().UseInMemoryDatabase("My.D3").Options;
            MyDbContext context = new MyDbContext(option);

            //InitializeDbForTests  初始化测试数据
            new TestDataBuilder(context).Build();


            builder.RegisterInstance(context).As <MyDbContext>();
            //注入
            Server.ContentRootPath = Path.GetFullPath(@"..\..\..\..\..\") + @"src\My.D3";
            IConfigurationRoot configuration = AppConfigurationHelper.Get(Server.ContentRootPath);

            builder.RegisterType <SimpleDbContextProvider <MyDbContext> >().As <IDbContextProvider <MyDbContext> >().InstancePerLifetimeScope();
            var assemblysServices = Assembly.Load("My.D3.Application");

            builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces();
            builder.RegisterAssemblyTypes(typeof(DbFixture).GetTypeInfo().Assembly);

            Container = builder.Build();
        }
Exemplo n.º 24
0
 public ProjenFrameworkDbContext()
 {
     appConfiguration = new AppConfigurationHelper();
 }
Exemplo n.º 25
0
 public override string HashPassword(string password)
 {
     return(AppConfigurationHelper.AutoHashing(password));
 }
Exemplo n.º 26
0
 private void InitializeStaticResource()
 {
     ViewBag.RootNode = AppConfigurationHelper.GetString("ReferenceKey.RootNode") ?? string.Empty;
 }
Exemplo n.º 27
0
        /// <summary>
        /// 添加留言信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AddCommentInfo()
        {
            var resultMode = new ResponseBaseModel <dynamic>
            {
                ResultCode = ResponceCodeEnum.Fail,
                Message    = "响应成功"
            };
            var checkcode = System.Web.HttpContext.Current.GetStringFromParameters("checkcode");

            if (string.IsNullOrEmpty(checkcode) || string.IsNullOrEmpty(Session["ValidateCode"]?.ToString()))
            {
                resultMode.Message = "验证码必填";
                return(Json(resultMode, JsonRequestBehavior.AllowGet));
            }

            var oldCode = Session["ValidateCode"];

            Session["ValidateCode"] = null;
            if (!oldCode.Equals(checkcode))
            {
                resultMode.Message = "验证码必填";
                return(Json(resultMode, JsonRequestBehavior.AllowGet));
            }
            var content       = System.Web.HttpContext.Current.GetStringFromParameters("content");
            var createTime    = DateTime.Now;
            var customerEmail = System.Web.HttpContext.Current.GetStringFromParameters("email");
            var customerName  = System.Web.HttpContext.Current.GetStringFromParameters("username");
            var customerPhone = System.Web.HttpContext.Current.GetStringFromParameters("tel");

            var    fw       = new FilterWord();
            string str      = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            var    filePath = AppConfigurationHelper.GetString("SensitiveFilePath");

            fw.DictionaryPath = str + filePath;
            fw.SourctText     = content;
            content           = fw.Filter('*');
            if (string.IsNullOrEmpty(content))
            {
                resultMode.Message = "留言内容不能为空";
                return(Json(resultMode, JsonRequestBehavior.AllowGet));
            }
            fw.SourctText = customerEmail;
            customerEmail = fw.Filter('*');
            if (string.IsNullOrEmpty(customerEmail) || !RegExp.IsEmail(customerEmail))
            {
                resultMode.Message = "邮箱内容错误";
                return(Json(resultMode, JsonRequestBehavior.AllowGet));
            }
            fw.SourctText = customerName;
            customerName  = fw.Filter('*');
            if (string.IsNullOrEmpty(customerName))
            {
                resultMode.Message = "姓名内容错误";
                return(Json(resultMode, JsonRequestBehavior.AllowGet));
            }
            fw.SourctText = customerPhone;
            customerPhone = fw.Filter('*');
            if (string.IsNullOrEmpty(customerPhone) || !RegExp.IsMobileNo(customerPhone))
            {
                resultMode.Message = "电话内容错误";
                return(Json(resultMode, JsonRequestBehavior.AllowGet));
            }
            var commentModel = new CustomercommentModel {
                Content = content, CreateTime = createTime, CustomerName = customerName, CustomerEmail = customerEmail, CustomerPhone = customerPhone, IsDel = FlagEnum.HadZore.GetHashCode(), HasDeal = FlagEnum.HadZore
            };
            var server = new CustomerCommentService();

            try
            {
                server.SaveModel(commentModel);
                resultMode.Message    = "处理成功";
                resultMode.ResultCode = ResponceCodeEnum.Success;
            }
            catch (Exception e)
            {
                Trace.WriteLine(e);
                resultMode.Message = "系统异常";
            }
            return(Json(resultMode, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 28
0
        private static void LoadConfigurationSettings()
        {
            var configurationHelper = new AppConfigurationHelper();

            configurationHelper.LoadConfigurationSettings();
        }
Exemplo n.º 29
0
        /// <summary>
        /// 方法执行前,如果没有登录就调整到Passport登录页面,没有权限就抛出信息
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            #region [1、验证是否在服务时间内]

            var startTimeStr = AppConfigurationHelper.GetString("SystemRunStartTime");
            var endTimeStr   = AppConfigurationHelper.GetString("SystemRunEndTime");
            //没有配置时间
            if (!string.IsNullOrEmpty(startTimeStr) && !string.IsNullOrEmpty(endTimeStr))
            {
                var startTime = DataTypeConvertHelper.ToDateTime(startTimeStr);
                var endTime   = DataTypeConvertHelper.ToDateTime(endTimeStr);

                if (startTime <= new DateTime(1900, 1, 1) || endTime <= new DateTime(1900, 1, 1))
                {
                    filterContext.Result = Request.UrlReferrer != null?Stop("系统运行时间配置错误!", Request.UrlReferrer.AbsoluteUri) : Content("系统运行时间配置错误!");

                    return;
                }
                startTime = new DateTime(1900, 1, 1, startTime.Hour, startTime.Minute, startTime.Second);
                endTime   = new DateTime(1900, 1, 1, endTime.Hour, endTime.Minute, endTime.Second);
                var newTime = DateTime.Now;
                newTime = new DateTime(1900, 1, 1, newTime.Hour, newTime.Minute, newTime.Second);
                if (newTime < startTime || newTime > endTime)
                {
                    filterContext.Result = Request.UrlReferrer != null?Stop("系统处于维护期!", Request.UrlReferrer.AbsoluteUri) : Content("系统处于维护期!");

                    return;
                }
            }

            #endregion
            var noAuthorizeAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeIgnoreAttribute), false);
            if (noAuthorizeAttributes.Length > 0)
            {
                return;
            }

            base.OnActionExecuting(filterContext);

            if (CurrentModel == null)
            {
                filterContext.Result = RedirectToAction("Login", "Auth");
                return;
            }

            var permissionAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast <PermissionAttribute>();
            permissionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(PermissionAttribute), false).Cast <PermissionAttribute>().Union(permissionAttributes);
            var attributes = permissionAttributes as IList <PermissionAttribute> ?? permissionAttributes.ToList();
            var showBanner = string.Empty;
            if (attributes.Any())
            {
                var hasPermission = true;
                foreach (var attr in attributes)
                {
                    foreach (var permission in attr.Permissions)
                    {
                        if (!CurrentModel.BusinessPermissionList.Contains(permission))
                        {
                            hasPermission = false;
                            break;
                        }
                    }
                }

                if (!hasPermission)
                {
                    if (Request.UrlReferrer != null)
                    {
                        filterContext.Result = Stop("没有权限!", Request.UrlReferrer.AbsoluteUri);
                    }
                    else
                    {
                        filterContext.Result = Content("没有权限!");
                    }
                }
                if (attributes.Count > 1)
                {
                    MenuId      = attributes[0].Permissions.FirstOrDefault().GetHashCode();
                    ManagerId   = attributes[1].Permissions.FirstOrDefault().GetHashCode();
                    showBanner  = EnumHelper.GetDescriptionByEnum(attributes[1].Permissions.FirstOrDefault());
                    showBanner += "/" + EnumHelper.GetDescriptionByEnum(attributes[0].Permissions.FirstOrDefault());
                }
                else
                {
                    ManagerId  = attributes[0].Permissions.FirstOrDefault().GetHashCode();
                    showBanner = EnumHelper.GetDescriptionByEnum(attributes[0].Permissions.FirstOrDefault());
                }
            }
            ViewBag.ShowBanner = showBanner;
            ViewBag.ManagerId  = ManagerId;
            ViewBag.MenuId     = MenuId;
        }
Exemplo n.º 30
0
 /// <summary>
 /// cut put point.
 /// </summary>
 static SqlConnectionHelper()
 {
     ConnectionString = AppConfigurationHelper.GetString("SqlConnectionString", null);
 }