예제 #1
0
        public ActionResult Put(LeaveMessageInputDto dto)
        {
            if (Regex.Match(dto.Content, CommonHelper.BanRegex).Length > 0)
            {
                return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!"));
            }

            dto.Content = dto.Content.Trim().Replace("<p><br></p>", string.Empty);
            if (dto.Content.RemoveHtmlTag().Trim().Equals(HttpContext.Session.Get <string>("msg")))
            {
                return(ResultData(null, false, "您刚才已经发表过一次留言了!"));
            }

            var msg = dto.Mapper <LeaveMessage>();

            if (Regex.Match(dto.Content, CommonHelper.ModRegex).Length <= 0)
            {
                msg.Status = Status.Pended;
            }

            msg.PostDate = DateTime.Now;
            var user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo);

            if (user != null)
            {
                msg.NickName   = user.NickName;
                msg.QQorWechat = user.QQorWechat;
                msg.Email      = user.Email;
                if (user.IsAdmin)
                {
                    msg.Status   = Status.Pended;
                    msg.IsMaster = true;
                }
            }

            msg.Content  = dto.Content.HtmlSantinizerStandard().ClearImgAttributes();
            msg.Browser  = dto.Browser ?? Request.Headers[HeaderNames.UserAgent];
            msg.IP       = ClientIP;
            msg.Location = msg.IP.GetIPLocation().Split("|").Where(s => !int.TryParse(s, out _)).ToHashSet().Join("|");
            msg          = LeaveMessageService.AddEntitySaved(msg);
            if (msg == null)
            {
                return(ResultData(null, false, "留言发表失败!"));
            }

            HttpContext.Session.Set("msg", msg.Content.RemoveHtmlTag().Trim());
            var email   = CommonHelper.SystemSettings["ReceiveEmail"];
            var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/notify.html").Replace("{{title}}", "网站留言板").Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{nickname}}", msg.NickName).Replace("{{content}}", msg.Content);

            if (msg.Status == Status.Pended)
            {
                if (!msg.IsMaster)
                {
                    MessageService.AddEntitySaved(new InternalMessage()
                    {
                        Title   = $"来自【{msg.NickName}】的新留言",
                        Content = msg.Content,
                        Link    = Url.Action("Index", "Msg", new { cid = msg.Id }, Request.Scheme)
                    });
                }
#if !DEBUG
                if (msg.ParentId == 0)
                {
                    //新评论,只通知博主
                    BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客新留言:", content.Replace("{{link}}", Url.Action("Index", "Msg", new { cid = msg.Id }, Request.Scheme)), email));
                }
                else
                {
                    //通知博主和上层所有关联的评论访客
                    var    pid    = LeaveMessageService.GetParentMessageIdByChildId(msg.Id);
                    var    emails = LeaveMessageService.GetSelfAndAllChildrenMessagesByParentId(pid).Select(c => c.Email).Append(email).Except(new[] { msg.Email }).ToHashSet();
                    string link   = Url.Action("Index", "Msg", new { cid = msg.Id }, Request.Scheme);
                    foreach (var s in emails)
                    {
                        BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{CommonHelper.SystemSettings["Domain"]}{CommonHelper.SystemSettings["Title"]} 留言回复:", content.Replace("{{link}}", link), s));
                    }
                }
#endif
                return(ResultData(null, true, "留言发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将会显示到列表中!"));
            }

            BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客新留言(待审核):", content.Replace("{{link}}", Url.Action("Index", "Msg", new
            {
                cid = msg.Id
            }, Request.Scheme)) + "<p style='color:red;'>(待审核)</p>", email));
            return(ResultData(null, true, "留言发表成功,待站长审核通过以后将显示到列表中!"));
        }
예제 #2
0
 /// <summary>
 /// 在任务被持久化到数据库之后,Hangfire服务端立即从数据库获取相关任务并装载到相应的Job Queue下,在没有异常的情况下仅处理一次,若发生异常,提供重试机制,异常及重试信息都会被记录到数据库中,通过Hangfire控制面板可以查看到这些信息
 /// </summary>
 public void SetTestRegisterEnqueueJobs()
 {
     BackgroundJob.Enqueue(() => this.OnTimeTestRegister("Enqueue"));
 }
예제 #3
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Manage"));
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                if (info == null)
                {
                    return(View("ExternalLoginFailure"));
                }

                using (var dbConn = Helpers.OrmliteConnection.openConn())
                {
                    var exist = dbConn.SingleOrDefault <tw_User>("email={0}", model.Email);
                    if (exist == null)
                    {
                        var user = new ApplicationUser()
                        {
                            UserName = Helpers.RemoveVietNameChar.Remove(model.UserName).ToLower(), PhoneNumber = model.PhoneNumber, Email = model.Email
                        };
                        var result = await UserManager.CreateAsync(user);

                        if (result.Succeeded)
                        {
                            var newUser = new tw_User();
                            newUser.name       = Helpers.RemoveVietNameChar.Remove(model.UserName).ToLower();
                            newUser.email      = model.Email;
                            newUser.phone      = model.PhoneNumber;
                            newUser.fullName   = model.FullName;
                            newUser.registerAt = DateTime.Now;
                            newUser.active     = true;
                            newUser.vendorAuth = info.Login.LoginProvider;
                            newUser.userKey    = user.Id;
                            newUser.createdAt  = DateTime.Now;
                            newUser.createdBy  = "administrator";
                            dbConn.Insert(newUser);

                            Int64 userId = (Int64)dbConn.GetLastInsertId();

                            var groupId = dbConn.Scalar <Int64>("select id from tw_UserGroup where name = 'guest'");
                            if (groupId > 0)
                            {
                                var userInGroup = new tw_UserInGroup();
                                userInGroup.userId    = userId;
                                userInGroup.groupId   = groupId;
                                userInGroup.createdAt = DateTime.Now;
                                userInGroup.createdBy = "administrator";
                                dbConn.Insert(userInGroup);
                            }

                            result = await UserManager.AddLoginAsync(user.Id, info.Login);

                            if (result.Succeeded)
                            {
                                string body = string.Empty;
                                using (StreamReader reader = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplate/newUserTemplate.html")))
                                {
                                    body = reader.ReadToEnd();
                                }
                                body = body.Replace("{username}", Helpers.RemoveVietNameChar.Remove(model.UserName).ToLower());
                                body = body.Replace("{fullname}", model.FullName);
                                body = body.Replace("{phone}", model.PhoneNumber);
                                body = body.Replace("{email}", model.Email);

                                BackgroundJob.Enqueue(
                                    () => new Helpers.SendMail().Send(model.Email, "", "Xin hoàn thành thủ tục đăng ký trên Thietbinhanh.com!", body, ""));

                                await SignInAsync(user, isPersistent : false);

                                return(RedirectToLocal(returnUrl));
                            }
                        }

                        AddErrors(result);
                    }
                    else
                    {
                        ModelState.AddModelError("", "Email is existed");
                    }
                }
            }

            ViewBag.ReturnUrl = returnUrl;
            return(View(model));
        }
예제 #4
0
 public ContentResult RefreshAssessmentScores()
 {
     BackgroundJob.Enqueue(() => ScheduledBackgroundJobLaunchHelper.RunRefreshAssessmentScoreJob(CurrentPerson.PersonID));
     return(Content("Refresh will run in the background."));
 }
예제 #5
0
        public ActionResult UploadWord()
        {
            var files = Request.Files;

            if (files.Count > 0 && files[0] != null)
            {
                HttpPostedFileBase file     = files[0];
                string             fileName = file.FileName;
                if (fileName != null && !Regex.IsMatch(Path.GetExtension(fileName), @"doc|docx"))
                {
                    return(ResultData(null, false, "文件格式不支持,只能上传doc或者docx的文档!"));
                }
                if (fileName != null)
                {
                    string upload = Request.MapPath("/upload");
                    if (!Directory.Exists(upload))
                    {
                        Directory.CreateDirectory(upload);
                    }
                    string resourceName = string.Empty.CreateShortToken(9);
                    string ext          = Path.GetExtension(fileName);
                    string docPath      = Path.Combine(upload, resourceName + ext);
                    file.SaveAs(docPath);
                    string htmlDir = docPath.Replace(".docx", "").Replace(".doc", "");
                    DocumentConvert.Doc2Html(docPath, htmlDir);
                    string          htmlfile = Path.Combine(htmlDir, "index.html");
                    string          html     = System.IO.File.ReadAllText(htmlfile).ReplaceHtmlImgSource("/upload/" + resourceName).ClearHtml().HtmlSantinizerStandard();
                    MatchCollection matches  = Regex.Matches(html, "<img.+?src=\"(.+?)\".+?>");
                    foreach (Match m in matches)
                    {
                        string src = m.Groups[1].Value;
                        var(url, success) = CommonHelper.UploadImage(Server.MapPath(src));
                        if (success)
                        {
                            html = html.Replace(src, url);
                            BackgroundJob.Enqueue(() => System.IO.File.Delete(Server.MapPath(src)));
                        }
                    }
                    ThreadPool.QueueUserWorkItem(state => System.IO.File.Delete(htmlfile));
                    if (html.Length < 10)
                    {
                        Directory.Delete(htmlDir, true);
                        System.IO.File.Delete(docPath);
                        return(ResultData(null, false, "读取文件内容失败,请检查文件的完整性,建议另存后重新上传!"));
                    }
                    if (html.Length > 1000000)
                    {
                        Directory.Delete(htmlDir, true);
                        System.IO.File.Delete(docPath);
                        return(ResultData(null, false, "文档内容超长,服务器拒绝接收,请优化文档内容后再尝试重新上传!"));
                    }
                    return(ResultData(new
                    {
                        Title = Path.GetFileNameWithoutExtension(fileName),
                        Content = html,
                        ResourceName = resourceName + ext
                    }));
                }
            }
            return(ResultData(null, false, "请先选择您需要上传的文件!"));
        }
예제 #6
0
파일: Program.cs 프로젝트: gaiazov/Hangfire
        public static void Main()
        {
            LogManager.Adapter = new ConsoleOutLoggerFactoryAdapter(
                LogLevel.Info, false, false, true, "");

            var sqlServerStorage = new SqlServerStorage(
                @"Server=.\sqlexpress;Database=Hangfire.Sample;Trusted_Connection=True;");

            sqlServerStorage.UseMsmqQueues(@".\Private$\hangfire{0}", "default", "critical");

            JobStorage.Current =
                sqlServerStorage;
            //new RedisStorage("localhost:6379", 3);

            RecurringJob.AddOrUpdate(() => Console.WriteLine("Hello, world!"), Cron.Minutely);
            RecurringJob.AddOrUpdate("hourly", () => Console.WriteLine("Hello"), "25 15 * * *");

            var options = new BackgroundJobServerOptions
            {
                Queues = new[] { "critical", "default" }
            };

            using (var server = new BackgroundJobServer(options))
            {
                var count = 1;

                while (true)
                {
                    var command = Console.ReadLine();

                    if (command == null || command.Equals("stop", StringComparison.OrdinalIgnoreCase))
                    {
                        break;
                    }

                    if (command.Equals("start", StringComparison.OrdinalIgnoreCase))
                    {
                        server.Start();
                    }

                    if (command.StartsWith("add", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var workCount = int.Parse(command.Substring(4));
                            for (var i = 0; i < workCount; i++)
                            {
                                var number = i;
                                BackgroundJob.Enqueue <Services>(x => x.Random(number));
                            }
                            Console.WriteLine("Jobs enqueued.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    if (command.StartsWith("static", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var workCount = int.Parse(command.Substring(7));
                            for (var i = 0; i < workCount; i++)
                            {
                                BackgroundJob.Enqueue(() => Console.WriteLine("Hello, {0}!", "world"));
                            }
                            Console.WriteLine("Jobs enqueued.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    if (command.StartsWith("error", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(6));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue <Services>(x => x.Error());
                        }
                    }

                    if (command.StartsWith("args", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(5));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue <Services>(x => x.Args(Guid.NewGuid().ToString(), 14442, DateTime.UtcNow));
                        }
                    }

                    if (command.StartsWith("custom", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(7));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue <Services>(x => x.Custom(
                                                                 new Random().Next(),
                                                                 new [] { "Hello", "world!" },
                                                                 new Services.CustomObject {
                                Id = 123
                            },
                                                                 DayOfWeek.Friday
                                                                 ));
                        }
                    }

                    if (command.StartsWith("fullargs", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(9));
                        for (var i = 0; i < workCount; i++)
                        {
                            BackgroundJob.Enqueue <Services>(x => x.FullArgs(
                                                                 false,
                                                                 123,
                                                                 'c',
                                                                 DayOfWeek.Monday,
                                                                 "hello",
                                                                 new TimeSpan(12, 13, 14),
                                                                 new DateTime(2012, 11, 10),
                                                                 new Services.CustomObject {
                                Id = 123
                            },
                                                                 new[] { "1", "2", "3" },
                                                                 new[] { 4, 5, 6 },
                                                                 new long[0],
                                                                 null,
                                                                 new List <string> {
                                "7", "8", "9"
                            }));
                        }
                    }

                    if (command.StartsWith("in", StringComparison.OrdinalIgnoreCase))
                    {
                        var seconds = int.Parse(command.Substring(2));
                        var number  = count++;
                        BackgroundJob.Schedule <Services>(x => x.Random(number), TimeSpan.FromSeconds(seconds));
                    }

                    if (command.StartsWith("cancelable", StringComparison.OrdinalIgnoreCase))
                    {
                        var iterations = int.Parse(command.Substring(11));
                        BackgroundJob.Enqueue <Services>(x => x.Cancelable(iterations, JobCancellationToken.Null));
                    }

                    if (command.StartsWith("delete", StringComparison.OrdinalIgnoreCase))
                    {
                        var workCount = int.Parse(command.Substring(7));
                        for (var i = 0; i < workCount; i++)
                        {
                            var jobId = BackgroundJob.Enqueue <Services>(x => x.EmptyDefault());
                            BackgroundJob.Delete(jobId);
                        }
                    }

                    if (command.StartsWith("fast", StringComparison.OrdinalIgnoreCase))
                    {
                        try
                        {
                            var workCount = int.Parse(command.Substring(5));
                            Parallel.For(0, workCount, i =>
                            {
                                if (i % 2 == 0)
                                {
                                    BackgroundJob.Enqueue <Services>(x => x.EmptyCritical());
                                }
                                else
                                {
                                    BackgroundJob.Enqueue <Services>(x => x.EmptyDefault());
                                }
                            });
                            Console.WriteLine("Jobs enqueued.");
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    if (command.StartsWith("generic", StringComparison.OrdinalIgnoreCase))
                    {
                        BackgroundJob.Enqueue <GenericServices <string> >(x => x.Method("hello", 1));
                    }
                }
            }

            Console.WriteLine("Press Enter to exit...");
            Console.ReadLine();
        }
        public ActionResult Put(CommentInputDto comment)
        {
            UserInfoOutputDto user = Session.GetByRedis <UserInfoOutputDto>(SessionKey.UserInfo);

            comment.Content = comment.Content.Trim().Replace("<p><br></p>", string.Empty);

            if (Regex.Match(comment.Content, ModRegex).Length <= 0)
            {
                comment.Status = Status.Pended;
            }
            if (user != null)
            {
                comment.NickName   = user.NickName;
                comment.QQorWechat = user.QQorWechat;
                comment.Email      = user.Email;
                if (user.IsAdmin)
                {
                    comment.Status   = Status.Pended;
                    comment.IsMaster = true;
                }
            }
            comment.Content     = Regex.Replace(comment.Content.HtmlSantinizerStandard().ConvertImgSrcToRelativePath(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>");
            comment.CommentDate = DateTime.Now;
            comment.Browser     = comment.Browser ?? Request.Browser.Type;
            comment.IP          = Request.UserHostAddress;
            Comment com = CommentBll.AddEntitySaved(comment.Mapper <Comment>());

            if (com != null)
            {
                var emails = new List <string>();
                var email  = GetSettings("ReceiveEmail");//站长邮箱
                emails.Add(email);
                string content = System.IO.File.ReadAllText(Request.MapPath("/template/notify.html")).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{nickname}}", com.NickName).Replace("{{content}}", com.Content);
                if (comment.Status == Status.Pended)
                {
                    if (!com.IsMaster)
                    {
                        MessageBll.AddEntitySaved(new InternalMessage()
                        {
                            Title = $"来自【{com.NickName}】的新文章评论", Content = com.Content, Link = Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, "http") + "#comment"
                        });
                    }
#if !DEBUG
                    if (com.ParentId == 0)
                    {
                        emails.Add(PostBll.GetById(com.PostId).Email);
                        //新评论,只通知博主和楼主
                        BackgroundJob.Enqueue(() => SendMail(Request.Url.Authority + "|博客文章新评论:", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, "http") + "#comment"), string.Join(",", emails.Distinct())));
                    }
                    else
                    {
                        //通知博主和上层所有关联的评论访客
                        var pid = CommentBll.GetParentCommentIdByChildId(com.Id);
                        emails = CommentBll.GetSelfAndAllChildrenCommentsByParentId(pid).Select(c => c.Email).ToList();
                        emails = emails.Distinct().Except(new List <string>()
                        {
                            com.Email
                        }).ToList();
                        Parallel.ForEach(emails, e =>
                        {
                            string link = Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id, email = e }, "http") + "#comment";
                            BackgroundJob.Enqueue(() => SendMail($"{Request.Url.Authority}{GetSettings("Title")}文章评论回复:", content.Replace("{{link}}", link), e));
                        });
                    }
#endif
                    return(ResultData(null, true, "评论发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将显示到评论列表中"));
                }
                BackgroundJob.Enqueue(() => SendMail(Request.Url.Authority + "|博客文章新评论(待审核):", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = com.PostId, cid = com.Id }, "http") + "#comment") + "<p style='color:red;'>(待审核)</p>", string.Join(",", emails.Distinct())));
                return(ResultData(null, true, "评论成功,待站长审核通过以后将显示"));
            }
            return(ResultData(null, false, "评论失败"));
        }
        public Task Invoke(HttpContext context)
        {
            var request = context.Request;

            //启用读取request
            request.EnableBuffering();
            if (!AppConfig.EnableIPDirect && request.Host.Host.MatchInetAddress() && !request.Host.Host.IsPrivateIP())
            {
                context.Response.StatusCode = 404;
                return(Task.CompletedTask);
            }
            var ip         = context.Connection.RemoteIpAddress.ToString();
            var path       = HttpUtility.UrlDecode(request.Path + request.QueryString, Encoding.UTF8);
            var requestUrl = HttpUtility.UrlDecode(request.Scheme + "://" + request.Host + path);
            var match      = Regex.Match(path ?? "", CommonHelper.BanRegex);

            if (match.Length > 0)
            {
                BackgroundJob.Enqueue(() => HangfireBackJob.InterceptLog(new IpIntercepter()
                {
                    IP         = ip,
                    RequestUrl = requestUrl,
                    Time       = DateTime.Now,
                    UserAgent  = request.Headers[HeaderNames.UserAgent],
                    Remark     = $"检测到敏感词拦截:{match.Value}"
                }));
                context.Response.StatusCode  = 400;
                context.Response.ContentType = "text/html; charset=utf-8";
                return(context.Response.WriteAsync("参数不合法!", Encoding.UTF8));
            }

            if (!context.Session.TryGetValue("session", out _) && !context.Request.IsRobot())
            {
                context.Session.Set("session", 0);
                var referer = context.Request.Headers[HeaderNames.Referer].ToString();
                if (!string.IsNullOrEmpty(referer))
                {
                    try
                    {
                        new Uri(referer);//判断是不是一个合法的referer
                        if (!referer.Contains(context.Request.Host.Value) && !referer.Contains(new[] { "baidu.com", "google", "sogou", "so.com", "bing.com", "sm.cn" }))
                        {
                            HangfireHelper.CreateJob(typeof(IHangfireBackJob), nameof(IHangfireBackJob.UpdateLinkWeight), args: referer);
                        }
                    }
                    catch
                    {
                        context.Response.StatusCode  = 504;
                        context.Response.ContentType = "text/html; charset=utf-8";
                        return(context.Response.WriteAsync("您的浏览器不支持访问本站!", Encoding.UTF8));
                    }
                }
            }

            if (!context.Request.IsRobot())
            {
                if (request.QueryString.HasValue)
                {
                    var q = request.QueryString.Value.Trim('?');
                    requestUrl = requestUrl.Replace(q, q.Split('&').Where(s => !s.StartsWith("cid") && !s.StartsWith("uid")).Join("&"));
                }
                TrackData.RequestLogs.AddOrUpdate(ip, new RequestLog()
                {
                    Count       = 1,
                    RequestUrls = { requestUrl },
                    UserAgents  = { request.Headers[HeaderNames.UserAgent] }
                }, (_, i) =>
                {
                    i.UserAgents.Add(request.Headers[HeaderNames.UserAgent]);
                    i.RequestUrls.Add(requestUrl);
                    i.Count++;
                    return(i);
                });
            }

            if (string.IsNullOrEmpty(context.Session.Get <string>(SessionKey.TimeZone)))
            {
                context.Session.Set(SessionKey.TimeZone, context.Connection.RemoteIpAddress.GetClientTimeZone());
            }

            return(_next(context));
        }
 /// <summary>
 /// Registers a background job that reset a log file to mark it as unprocessed and updates all other data
 /// relevant to this state (e.g. UriStemAggregate for all requests is set to NULL).
 /// </summary>
 /// <param name="logFileId"></param>
 public void RegisterResetProcessedLogFileJob(int logFileId)
 {
     BackgroundJob.Enqueue <JobExecutionService>(x => x.ExecuteResetProcessedLogFileJob(logFileId));
 }
예제 #10
0
        public static void Main()
        {
            //The path to the Realm DB file.
            string dbPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                "Hangfire.Realm.Sample.NetCore.realm");

            Console.WriteLine($"Using database {dbPath}");

            //A standard Realm configuration.
            RealmConfiguration realmConfiguration = new RealmConfiguration(dbPath)
            {
                ShouldCompactOnLaunch = (totalBytes, usedBytes) =>
                {
                    // Compact if the file is over 100MB in size and less than 50% 'used'
                    var oneHundredMB = (ulong)(100 * 1024 * 1024);
                    return(totalBytes > oneHundredMB && (double)usedBytes / totalBytes < 0.5);
                },
            };

            //Hangfire.Realm storage options.
            RealmJobStorageOptions storageOptions = new RealmJobStorageOptions
            {
                RealmConfiguration = realmConfiguration,             //Required.
                QueuePollInterval  = TimeSpan.FromSeconds(1),        //Optional. Defaults to TimeSpan.FromSeconds(15)
                //SlidingInvisibilityTimeout = TimeSpan.FromSeconds(10), //Optional. Defaults to TimeSpan.FromMinutes(10)
                JobExpirationCheckInterval = TimeSpan.FromMinutes(1) //Optional. Defaults to TimeSpan.FromMinutes(30)
            };

            //Standard Hangfire server options.
            BackgroundJobServerOptions serverOptions = new BackgroundJobServerOptions()
            {
                WorkerCount             = 40,
                Queues                  = new[] { "default" },
                ServerTimeout           = TimeSpan.FromMinutes(10),
                HeartbeatInterval       = TimeSpan.FromSeconds(60),
                ServerCheckInterval     = TimeSpan.FromSeconds(10),
                SchedulePollingInterval = TimeSpan.FromSeconds(10),
            };

            //Hangfire global configuration
            GlobalConfiguration.Configuration
            .UseLogProvider(new ColouredConsoleLogProvider(Logging.LogLevel.Debug))
            .UseRealmJobStorage(storageOptions);


            using (new BackgroundJobServer(serverOptions))
            {
                //Queue a bunch of fire-and-forget jobs
                for (var i = 0; i < JobCount; i++)
                {
                    var jobNumber = i + 1;
                    BackgroundJob.Enqueue <FafJob>((_) => _.Execute(jobNumber, CancellationToken.None));
                }

                //A scheduled job that will run 1.5 minutes after being placed in queue
                BackgroundJob.Schedule(() =>
                                       Console.WriteLine("A Scheduled job."),
                                       TimeSpan.FromMinutes(1.5));

                //A fire-and-forget continuation job that has three steps
                BackgroundJob.ContinueJobWith(
                    BackgroundJob.ContinueJobWith(
                        BackgroundJob.Enqueue(
                            () => Console.WriteLine($"Knock knock..")),
                        () => Console.WriteLine("Who's there?")),
                    () => Console.WriteLine("A continuation job!"));

                //A scheduled continuation job that has three steps
                BackgroundJob.ContinueJobWith(
                    BackgroundJob.ContinueJobWith(
                        BackgroundJob.Schedule(
                            () => Console.WriteLine($"Knock knock.."), TimeSpan.FromMinutes(2)),
                        () => Console.WriteLine("Who's there?")),
                    () => Console.WriteLine("A scheduled continuation job!"));

                //A Cron based recurring job
                RecurringJob.AddOrUpdate("recurring-job-1", () =>
                                         Console.WriteLine("Recurring job 1."),
                                         Cron.Minutely);

                //Another recurring job
                RecurringJob.AddOrUpdate("recurring-job-2", () =>
                                         Console.WriteLine("Recurring job 2."),
                                         Cron.Minutely);

                //An update to the first recurring job
                RecurringJob.AddOrUpdate("recurring-job-1", () =>
                                         Console.WriteLine("Recurring job 1 (edited)."),
                                         Cron.Minutely);

                Console.Read();
            }
        }
        public static void Enqueue(this IMediator mediator, IRequest request)
        {
            var serializedRequest = request.Serialize();

            BackgroundJob.Enqueue <BackgroundMediator>(m => m.Send(serializedRequest));
        }
예제 #12
0
 public static string SetSendEmailAccountData(string login, string password, string email, string emailPassword, string additionalInfo, string userEmail)
 {
     return(BackgroundJob.Enqueue <SendEmailAccountData>(
                j => j.Do(login, password, email, emailPassword, additionalInfo, userEmail)));
 }
예제 #13
0
 public static string SetSendEmailChangeStatus(int orderId, string userEmail, string currentStatus, string callbackUrl)
 {
     return(BackgroundJob.Enqueue <SendEmailChangeStatus>(
                j => j.Do(orderId, userEmail, currentStatus, callbackUrl)));
 }
예제 #14
0
 public void Enqueue <TRequest, TResult>(TRequest command)
     where TRequest : IRequest <TResult>
 {
     BackgroundJob.Enqueue <BackgroundJobExecutor <TRequest, TResult> >(x => x.Execute(command));
 }
예제 #15
0
 public static void EnqueueContact(string title, string emailReceive, string name, string phone, string email, string message)
 {
     BackgroundJob.Enqueue <SendMail>(s => s.SendMailContact(title, emailReceive, name, phone, email, message));
 }
 /// <summary>
 /// Registers a background job that runs through all the requests for a specific log file, and recalculates the aggregates
 /// for those requests using the project aggregates set by the user.
 /// </summary>
 /// <param name="logFileId"></param>
 public void RegisterAggregateRequestJob(int logFileId)
 {
     BackgroundJob.Enqueue <JobExecutionService>(x => x.ExecuteAggregateRequestJob(logFileId));
 }
예제 #17
0
 public static void EnqueueCheckOut(string emailReceive, string title, string name, string email, string phone, string address, string note, string paymentMethods, List <CartItem> cartItems)
 {
     BackgroundJob.Enqueue <SendMail>(s => s.SendMailCheckOut(emailReceive, title, name, email, phone, address, note, paymentMethods, cartItems));
 }
 /// <summary>
 /// Job registered once a file has been uploaded, to process the contents of the log file.
 /// </summary>
 /// <param name="logFileId"></param>
 /// <param name="filePath"></param>
 public void RegisterProcessLogFileJob(int logFileId, string filePath)
 {
     BackgroundJob.Enqueue <JobExecutionService>(x => x.ExecuteProcessLogFileJob(logFileId, filePath));
 }
예제 #19
0
        public override Task <SendMessageResponse> SendTemplate(SendTemplateRequest request, ServerCallContext context)
        {
            string formId = null;

            if (_redis.KeyExists(CacheKey.UserIsWxAppPrefix + request.AppId))
            {
                formId = request.FormId;
            }
            var targets       = _processTarget(request.Targets);
            var messageStatus = new MessageStatus(_redis);

            messageStatus.GenMessageId();
            var now  = Util.GetTimestamp();
            var resp = new SendMessageResponse
            {
                MessageId = messageStatus.GetMessageId(),
                SendTime  = request.Time == 0 ? now : request.Time
            };

            if (request.NoStatus)
            {
                resp.MessageId = string.Empty;
                messageStatus.SetMessageId(null);
            }
            else
            {
                messageStatus.Create(targets.Keys.ToArray(), resp.SendTime);
            }
            foreach (var item in targets)
            {
                var data = new Dictionary <string, WxWebSendTemplateRequest.DataItem>();
                foreach (var dItem in request.Data)
                {
                    data.Add(dItem.Key, new WxWebSendTemplateRequest.DataItem
                    {
                        Value = _processValue(item.Value, dItem.Value),
                        Color = dItem.Color
                    });
                }
                var tmpUrl = _processValue(item.Value, request.Url);
                if (request.Time == 0)
                {
                    if (request.HighPriority)
                    {
                        BackgroundJob.Enqueue <SendMessage>(x => x.HighPriorityTemplate(messageStatus.GetMessageId(), request.AppId, item.Key, request.TemplateId, tmpUrl, data, formId, null));
                    }
                    else
                    {
                        BackgroundJob.Enqueue <SendMessage>(x => x.Template(messageStatus.GetMessageId(), request.AppId, item.Key, request.TemplateId, tmpUrl, data, formId, null));
                    }
                }
                else
                {
                    var tmpJobId = string.Empty;
                    if (request.HighPriority)
                    {
                        tmpJobId = BackgroundJob.Schedule <SendMessage>(x => x.HighPriorityTemplate(messageStatus.GetMessageId(), request.AppId, item.Key, request.TemplateId, tmpUrl, data, formId, null), TimeSpan.FromSeconds(request.Time - now));
                    }
                    else
                    {
                        tmpJobId = BackgroundJob.Schedule <SendMessage>(x => x.Template(messageStatus.GetMessageId(), request.AppId, item.Key, request.TemplateId, tmpUrl, data, formId, null), TimeSpan.FromSeconds(request.Time - now));
                    }
                    messageStatus.AddJobId(tmpJobId);
                }
            }
            return(Task.FromResult(resp));
        }
예제 #20
0
        public async Task <IActionResult> SendLicenceCreationMessage(string licenceGuild)
        {
            BackgroundJob.Enqueue(() => new OneStopUtils(Configuration).SendLicenceCreationMessage(null, licenceGuild));

            return(Ok());
        }
예제 #21
0
        public ActionResult Publish(PostInputDto post)
        {
            UserInfoOutputDto user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo);

            if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available))
            {
                return(ResultData(null, message: "请选择一个分类"));
            }

            if (string.IsNullOrEmpty(post.Label?.Trim()))
            {
                post.Label = null;
            }
            else if (post.Label.Trim().Length > 50)
            {
                post.Label = post.Label.Replace(",", ",");
                post.Label = post.Label.Trim().Substring(0, 50);
            }
            else
            {
                post.Label = post.Label.Replace(",", ",");
            }

            post.Status     = Status.Pending;
            post.PostDate   = DateTime.Now;
            post.ModifyDate = DateTime.Now;
            if (user != null && user.IsAdmin)
            {
                post.Status = Status.Pended;
            }
            else
            {
                post.Content = CommonHelper.ReplaceImgSrc(Regex.Replace(post.Content.HtmlSantinizerStandard(), @"<img\s+[^>]*\s*src\s*=\s*['""]?(\S+\.\w{3,4})['""]?[^/>]*/>", "<img src=\"$1\"/>")).Replace("/thumb150/", "/large/");
            }

            ViewBag.CategoryId = new SelectList(CategoryService.LoadEntitiesNoTracking(c => c.Status == Status.Available), "Id", "Name", post.CategoryId);
            Post p = post.Mapper <Post>();

            p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            p.PostAccessRecord.Add(new PostAccessRecord()
            {
                AccessTime = DateTime.Today,
                ClickCount = 0
            });
            p = PostService.AddEntitySaved(p);
            if (p != null)
            {
                if (p.Status == Status.Pending)
                {
                    var    email = CommonHelper.SystemSettings["ReceiveEmail"];
                    string link  = Url.Action("Details", "Post", new
                    {
                        id = p.Id
                    }, Request.Scheme);
                    string content = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + "/template/publish.html").Replace("{{link}}", link).Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).Replace("{{title}}", p.Title);
                    BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, email));
                    return(ResultData(p.Mapper <PostOutputDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!"));
                }

                return(ResultData(p.Mapper <PostOutputDto>(), message: "文章发表成功!"));
            }

            return(ResultData(null, false, "文章发表失败!"));
        }
예제 #22
0
 public IActionResult AnalyseServerLogFiles()
 {
     BackgroundJob.Enqueue <IServerLogService>(s => s.BuildServerLogDatabaseEntries());
     return(RedirectToAction("Index"));
 }
예제 #23
0
        public async Task <ActionResult> Publish(PostInputDto post)
        {
            if (Regex.Match(post.Content, CommonHelper.BanRegex).Length > 0)
            {
                return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请注意改善您的言辞!"));
            }

            UserInfoOutputDto user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo);

            if (!CategoryService.Any(c => c.Id == post.CategoryId && c.Status == Status.Available))
            {
                return(ResultData(null, message: "请选择一个分类"));
            }

            if (string.IsNullOrEmpty(post.Label?.Trim()))
            {
                post.Label = null;
            }
            else if (post.Label.Trim().Length > 50)
            {
                post.Label = post.Label.Replace(",", ",").Trim().Substring(0, 50);
            }
            else
            {
                post.Label = post.Label.Replace(",", ",");
            }

            post.Status     = Status.Pending;
            post.PostDate   = DateTime.Now;
            post.ModifyDate = DateTime.Now;
            if (user != null && user.IsAdmin)
            {
                post.Status = Status.Pended;
            }
            else
            {
                post.Content = await _imagebedClient.ReplaceImgSrc(post.Content.HtmlSantinizerStandard().ClearImgAttributes());
            }

            ViewBag.CategoryId = new SelectList(CategoryService.LoadEntitiesNoTracking(c => c.Status == Status.Available), "Id", "Name", post.CategoryId);
            Post p = post.Mapper <Post>();

            p.IP = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            p    = PostService.AddEntitySaved(p);
            if (p != null)
            {
                if (p.Status == Status.Pending)
                {
                    var    email   = CommonHelper.SystemSettings["ReceiveEmail"];
                    string link    = Url.Action("Details", "Post", new { id = p.Id }, Request.Scheme);
                    string content = System.IO.File.ReadAllText(_hostingEnvironment.WebRootPath + "/template/publish.html")
                                     .Replace("{{link}}", link)
                                     .Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                                     .Replace("{{title}}", p.Title);
                    BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Title"] + "有访客投稿:", content, email));
                    return(ResultData(p.Mapper <PostOutputDto>(), message: "文章发表成功,待站长审核通过以后将显示到列表中!"));
                }

                return(ResultData(p.Mapper <PostOutputDto>(), message: "文章发表成功!"));
            }

            return(ResultData(null, false, "文章发表失败!"));
        }
예제 #24
0
        public void Execute()
        {
            var holds = _context.Holds
                        .Include(x => x.LibraryAsset)
                        .Include(x => x.LibraryCard)
                        .OrderBy(x => x.HoldPlaced);

            if (!holds.Any())
            {
                return;
            }

            //Search for holds that did not culminate in checkouts
            foreach (var hold in holds)
            {
                if (DateTime.Now > hold.HoldPlaced.AddHours(24) && hold.FirstHold == true)
                {
                    //Check whether the asset was checked out in 24 hours time since hold was placed on it
                    var checkout = _context.Checkouts
                                   .Include(x => x.LibraryAsset)
                                   .Include(x => x.LibraryCard)
                                   .FirstOrDefault(x => x.LibraryAsset.Id == hold.LibraryAsset.Id &&
                                                   x.LibraryCard.Id == hold.LibraryCard.Id &&
                                                   x.Since >= hold.HoldPlaced && x.Since <= hold.HoldPlaced.AddHours(24));

                    //If the asset was not checked out, send email to the patron
                    if (checkout == null)
                    {
                        var asset = _context.LibraryAssets
                                    .FirstOrDefault(x => x.Id == hold.LibraryAsset.Id);

                        var patron = _context.Users
                                     .FirstOrDefault(x => x.LibraryCard.Id == hold.LibraryCard.Id);

                        BackgroundJob.Enqueue <IEmailService>(x => x.SendEmailAsync(patron.FirstName, patron.Email,
                                                                                    $"Library asset is not available.",
                                                                                    $"The asset: '{asset.Title}' on which you have placed hold is not available. " +
                                                                                    $"The time in which you were to borrow the item has left."));

                        _context.Remove(hold);


                        //If there are not any more holds on the asset change its status to available
                        var holdsOnAsset = holds
                                           .Where(x => x.LibraryAsset.Id == asset.Id && x.Id != hold.Id);

                        if (!holdsOnAsset.Any())
                        {
                            _context.Update(asset);
                            asset.Status = _context.Statuses.FirstOrDefault(x => x.Name == "Available");
                        }
                        //If there are more holds on the asset send email to the next patron waiting for it
                        else
                        {
                            var earliestHold = holds
                                               .FirstOrDefault(x => x.Id != hold.Id &&
                                                               x.LibraryAsset.Id == hold.LibraryAsset.Id);

                            _context.Update(earliestHold);
                            earliestHold.FirstHold  = true;
                            earliestHold.HoldPlaced = DateTime.Now;

                            var nextPatron = _context.Users
                                             .FirstOrDefault(x => x.LibraryCard.Id == earliestHold.LibraryCard.Id);

                            BackgroundJob.Enqueue <IEmailService>(x => x.SendEmailAsync(nextPatron.FirstName, nextPatron.Email, "Library asset is available",
                                                                                        $"The asset: '{asset.Title}' on which you have placed hold is now available. " +
                                                                                        "Now you have to come to us and take the item in 24 hours time. " +
                                                                                        "If you will not take the item up to this time you will not be able to borrow it."));
                        }
                    }
                }
            }

            _context.SaveChanges();
        }
 public void Enqueue <T>(Expression <Action <T> > methodCall)
 {
     BackgroundJob.Enqueue <T>(methodCall);
 }
예제 #26
0
 public static void EnqueueForgotPassword(string email, string title, string newPassword)
 {
     BackgroundJob.Enqueue <SendMail>(s => s.SendMailResetPassword(email, title, newPassword));
 }
예제 #27
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                using (var dbConn = Helpers.OrmliteConnection.openConn())
                {
                    int count         = 0;
                    var existEmail    = dbConn.SingleOrDefault <tw_User>("email={0}", model.Email);
                    var existShopName = dbConn.SingleOrDefault <Merchant_Info>("ten_gian_hang={0}", model.ten_gian_hang);
                    var existUrl      = dbConn.SingleOrDefault <Merchant_Info>("website={0}", model.website);
                    if (existEmail != null)
                    {
                        ModelState.AddModelError("", Resources.Global._email_exited);
                        count++;
                    }
                    if (existShopName != null)
                    {
                        ModelState.AddModelError("", Resources.Global._shop_name_exsited);
                        count++;
                    }
                    if (existUrl != null)
                    {
                        ModelState.AddModelError("", Resources.Global._url_is_exsited);
                        count++;
                    }
                    if (count == 0)
                    {
                        var user = new ApplicationUser()
                        {
                            UserName = model.UserName, PhoneNumber = model.PhoneNumber, Email = model.Email
                        };
                        var result = await UserManager.CreateAsync(user, model.Password);

                        if (result.Succeeded)
                        {
                            // ADD USER
                            var newUser = new tw_User();
                            newUser.name       = model.UserName;
                            newUser.email      = model.Email;
                            newUser.phone      = model.PhoneNumber;
                            newUser.fullName   = model.FullName;
                            newUser.registerAt = DateTime.Now;
                            newUser.homePage   = "Home";
                            newUser.active     = false;
                            newUser.vendorAuth = "";
                            newUser.userKey    = user.Id;
                            //newUser.ma_gian_hang= dbConn.QueryScalar<string>("select MAX(ma_gian_hang) from Merchant_Info");
                            newUser.createdAt = DateTime.Now;
                            newUser.createdBy = "system";
                            dbConn.Insert(newUser);

                            // ADD MERCHANT_INFO
                            Merchant_Info merchantinfo = new Merchant_Info();
                            merchantinfo.ten_gian_hang = model.ten_gian_hang;
                            merchantinfo.website       = model.website;
                            //List<Merchant_Info> lstMerchant = new List<Merchant_Info>();
                            //lstMerchant.Add(merchantinfo);
                            Merchant_Info_DAO merchantDao = new Merchant_Info_DAO();
                            merchantDao.CreateMerchant(merchantinfo, model.UserName, AppConfigs.MCCConnectionString);



                            // ADD USERGROUP
                            Int64 userId  = (Int64)dbConn.GetLastInsertId();
                            var   groupId = dbConn.Scalar <Int64>("select id from tw_UserGroup where name = 'MerchantAdmin'");
                            if (groupId > 0)
                            {
                                var userInGroup = new tw_UserInGroup();
                                userInGroup.userId    = userId;
                                userInGroup.groupId   = groupId;
                                userInGroup.createdAt = DateTime.Now;
                                userInGroup.createdBy = "system";
                                dbConn.Insert(userInGroup);
                            }

                            // ADD USERACTIVATION
                            string         code      = Guid.NewGuid().ToString();;
                            UserActivation userActiv = new UserActivation();
                            userActiv.UserName       = model.UserName;
                            userActiv.Email          = model.Email;
                            userActiv.MerchantName   = model.ten_gian_hang;
                            userActiv.FullName       = model.FullName;
                            userActiv.Phone          = model.PhoneNumber;
                            userActiv.ActivationCode = code;
                            userActiv.Date           = DateTime.Now;
                            userActiv.DeadTime       = DateTime.Now.AddDays(3);// sau 3 ngay link active vo hieu luc
                            userActiv.ngay_tao       = DateTime.Now;
                            userActiv.nguoi_tao      = "system";
                            userActiv.ngay_cap_nhat  = DateTime.Now;
                            userActiv.nguoi_cap_nhat = "system";
                            dbConn.Insert(userActiv);

                            //SEND MAIL
                            string body = string.Empty;
                            using (StreamReader reader = new StreamReader(System.Web.Hosting.HostingEnvironment.MapPath("~/EmailTemplate/newUserTemplate.html")))
                            {
                                body = reader.ReadToEnd();
                            }
                            body = body.Replace("{username}", model.UserName);
                            body = body.Replace("{fullname}", model.FullName);
                            body = body.Replace("{phone}", model.PhoneNumber);
                            body = body.Replace("{email}", model.Email);

                            //xác thực bằng web
                            body = body.Replace("{activation}", AppConfigs.Url + "/Account/Activation?key=" + code + "&email=" + model.Email + "&username="******"&ten_gian_hang=" + model.ten_gian_hang);
                            //xác thực thông qua API
                            //body = body.Replace("{activation}", AllConstant.UrlAPI + "api/ActivationAccount/Activation?key=" + code + "&email=" + model.Email + "&username="******"&ten_gian_hang=" + model.ten_gian_hang);
                            BackgroundJob.Enqueue(() => new Helpers.SendMail().Send(model.Email, "", "Xin hoàn thành thủ tục đăng ký trên Thietbinhanh.com!", body, ""));
                            // new Helpers.SendMail().Send(model.Email, "", "Xin hoàn thành thủ tục đăng ký trên Thietbinhanh.com!", body, "");
                            //await SignInAsync(user, isPersistent: false);
                            return(View("~/Views/Account/Success.cshtml"));
                        }
                        else
                        {
                            AddErrors(result);
                        }
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #28
0
 public static void EnqueueRegister(string email, string title, string domainName, string verifyLink)
 {
     BackgroundJob.Enqueue <SendMail>(s => s.SendMailVerifyRegister(email, title, domainName, verifyLink));
 }
예제 #29
0
        public IActionResult Welcome(string userName)
        {
            var jobId = BackgroundJob.Enqueue(() => SendWelcomeMail(userName));

            return(Ok($"Job Id {jobId} Completed. Welcome Mail Sent!"));
        }
예제 #30
0
 public static void Register()
 {
     BackgroundJob.Enqueue <TJob>(job => job.Run());
 }