Example #1
0
        private void button2_Click(object sender, RoutedEventArgs e)
        {
            SnowFlake s = new SnowFlake();

            s.Show();
            this.Close();
        }
Example #2
0
        public ActionResult GetViewToken(string email)
        {
            if (string.IsNullOrEmpty(email) || !email.MatchEmail())
            {
                return(ResultData(null, false, "请输入正确的邮箱!"));
            }

            if (RedisHelper.Exists("get:" + email))
            {
                RedisHelper.Expire("get:" + email, 120);
                return(ResultData(null, false, "发送频率限制,请在2分钟后重新尝试发送邮件!请检查你的邮件,若未收到,请检查你的邮箱地址或邮件垃圾箱!"));
            }

            if (!BroadcastService.Any(b => b.Email.Equals(email) && b.SubscribeType == SubscribeType.ArticleToken))
            {
                return(ResultData(null, false, "您目前没有权限访问这个链接,请联系站长开通访问权限!"));
            }

            var token = SnowFlake.GetInstance().GetUniqueShortId(6);

            RedisHelper.Set("token:" + email, token, 86400);
            BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "博客访问验证码", $"{CommonHelper.SystemSettings["Domain"]}本次验证码是:<span style='color:red'>{token}</span>,有效期为24h,请按时使用!", email));
            RedisHelper.Set("get:" + email, token, 120);
            return(ResultData(null));
        }
Example #3
0
        public ActionResult GetViewToken(string email)
        {
            var validator = new IsEmailAttribute();

            if (!validator.IsValid(email))
            {
                return(ResultData(null, false, validator.ErrorMessage));
            }

            if (RedisHelper.Exists("get:" + email))
            {
                RedisHelper.Expire("get:" + email, 120);
                return(ResultData(null, false, "发送频率限制,请在2分钟后重新尝试发送邮件!请检查你的邮件,若未收到,请检查你的邮箱地址或邮件垃圾箱!"));
            }

            if (!UserInfoService.Any(b => b.Email.Equals(email)))
            {
                return(ResultData(null, false, "您目前没有权限访问这个链接,请联系站长开通访问权限!"));
            }

            var token = SnowFlake.GetInstance().GetUniqueShortId(6);

            RedisHelper.Set("token:" + email, token, 86400);
            BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "博客访问验证码", $"{Request.Host}本次验证码是:<span style='color:red'>{token}</span>,有效期为24h,请按时使用!", email, ClientIP));
            RedisHelper.Set("get:" + email, token, 120);
            return(ResultData(null));
        }
        public async Task <ActionResult> SendCode(string email)
        {
            if (string.IsNullOrEmpty(email) || !email.MatchEmail().isMatch)
            {
                return(ResultData(null, false, "请输入正确的邮箱!"));
            }

            if (await RedisHelper.ExistsAsync("get:" + email))
            {
                await RedisHelper.ExpireAsync("get:" + email, 120);

                return(ResultData(null, false, "发送频率限制,请在2分钟后重新尝试发送邮件!请检查你的邮件,若未收到,请检查你的邮箱地址或邮件垃圾箱!"));
            }

            string code = SnowFlake.GetInstance().GetUniqueShortId(6);
            await RedisHelper.SetAsync("code:" + email, code, 86400);

            BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "博客验证码", $"{Request.Host}本次验证码是:<span style='color:red'>{code}</span>,有效期为24h,请按时使用!", email, ClientIP));
            await RedisHelper.SetAsync("get:" + email, code, 120);

#if !DEBUG
            return(ResultData(null, true, "验证码发送成功!"));
#else
            return(ResultData(null, true, "验证码:" + code));
#endif
        }
        public ActionResult UploadFile(IFormFile file)
        {
            string path;
            string filename = SnowFlake.GetInstance().GetUniqueId() + Path.GetExtension(file.FileName);

            switch (file.ContentType)
            {
            case var _ when file.ContentType.StartsWith("image"):
                path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "images", filename);

                var dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    file.CopyTo(fs);
                }
                var(url, success) = CommonHelper.UploadImage(path);
                if (success)
                {
                    BackgroundJob.Enqueue(() => System.IO.File.Delete(path));
                    return(ResultData(url));
                }
                break;

            case var _ when file.ContentType.StartsWith("audio") || file.ContentType.StartsWith("video"):
                path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "media", filename);

                break;

            case var _ when file.ContentType.StartsWith("text") || (ContentType.Doc + "," + ContentType.Xls + "," + ContentType.Ppt + "," + ContentType.Pdf).Contains(file.ContentType):
                path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "docs", filename);

                break;

            default:
                path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "files", filename);
                break;
            }
            try
            {
                var dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    file.CopyTo(fs);
                }
                return(ResultData(path.Substring(_hostingEnvironment.WebRootPath.Length).Replace("\\", "/")));
            }
            catch (Exception e)
            {
                LogManager.Error(e);
                return(ResultData(null, false, "文件上传失败!"));
            }
        }
Example #6
0
        private void timer1_Tick(object sender, EventArgs e)
        {
            SnowFlake s  = new SnowFlake();
            Random    rd = new Random();

            switch (rd.Next(1, 6))
            {
            case 1:
                timer1.Interval = 300;
                break;

            case 2:
                timer1.Interval = 900;
                break;

            case 3:
                timer1.Interval = 1200;
                break;
            }
            s.X         = rand.Next(-20, Width + 20);
            s.Y         = -10f;
            s.XVelocity = (float)(rand.NextDouble() - 0.5f) * 2f;
            s.YVelocity = (float)(rand.NextDouble() * 3) + 1f;
            //s.Rotation = rand.Next(0, 359);
            //s.RotVelocity = rand.Next(-3, 3) * 2;
            s.image = rd.Next(1, 4);
            //if (s.RotVelocity == 0)
            //{
            //    s.RotVelocity = 3;
            //}
            //s.Scale = (float)(rand.NextDouble() / 2) + 0.75f;
            SnowFlakes.Add(s);
        }
Example #7
0
        static void Main(string[] args)
        {
            SnowFlake   snowFlake = new SnowFlake(datacenterId: 1, machineId: 1);
            List <long> list      = new List <long>();

            for (int i = 1000 - 1; i >= 0; i--)
            {
                list.Add(snowFlake.NextId());
            }

            SnowFlake snowFlake1 = new SnowFlake(1, 2);

            for (int i = 1000 - 1; i >= 0; i--)
            {
                list.Add(snowFlake1.NextId());
            }

            SnowFlake snowFlake2 = new SnowFlake(1, 3);

            for (int i = 1000 - 1; i >= 0; i--)
            {
                list.Add(snowFlake2.NextId());
            }

            Console.WriteLine(list.DistinctBy(p => p).Count());
            Console.WriteLine("Hello World!");
        }
        public ActionResult GetViewToken([FromServices] IUserInfoService userInfoService, string email)
        {
            if (string.IsNullOrEmpty(email) || !email.MatchEmail().isMatch)
            {
                return(ResultData(null, false, "请输入正确的邮箱!"));
            }

            if (RedisHelper.Exists("get:" + email))
            {
                RedisHelper.Expire("get:" + email, 120);
                return(ResultData(null, false, "发送频率限制,请在2分钟后重新尝试发送邮件!请检查你的邮件,若未收到,请检查你的邮箱地址或邮件垃圾箱!"));
            }

            if (!userInfoService.Any(b => b.Email == email))
            {
                return(ResultData(null, false, "您目前没有权限访问这个链接,请联系站长开通访问权限!"));
            }

            var token = SnowFlake.GetInstance().GetUniqueShortId(6);

            RedisHelper.Set("token:" + email, token, 86400);
            BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "博客访问验证码", $"{Request.Host}本次验证码是:<span style='color:red'>{token}</span>,有效期为24h,请按时使用!", email, HttpContext.Connection.RemoteIpAddress.ToString()));
            RedisHelper.Set("get:" + email, token, 120);
            return(ResultData(null));
        }
Example #9
0
 public static void PrintReset()
 {
     Console.WriteLine("{0} Tweet ID: {1} ({2})", DateTime.Now, LastTweetID, SnowFlake.DatefromSnowFlake(LastTweetID));
     Console.WriteLine("{0} {1} / {2} Tweet Checked", DateTime.Now, TweetCheckHit.Get(), TweetToCheck.Get());
     Console.WriteLine("{0} {1} / {2} Media Gone", DateTime.Now, MediaGone.Get(), MediaTotal.Get());
     Console.WriteLine("{0} {1} / {2} Tweet Deleted", DateTime.Now, TweetDeleted.Get(), TweetToDelete.Get());
 }
Example #10
0
        public SnowFlake addSnowFlake(float x, float y, float scale)
        {
            SnowFlake obj = new SnowFlake(x, y, scale);

            addObject(obj, -5);
            return(obj);
        }
Example #11
0
 public void TestMethod1()
 {
     for (var i = 0; i < 10; i++)
     {
         Trace.Write(SnowFlake.NewId());
         Trace.Write(Environment.NewLine);
     }
 }
Example #12
0
        /// <summary>
        /// 每天的任务
        /// </summary>
        public void EverydayJob()
        {
            CommonHelper.IPErrorTimes.RemoveWhere(kv => kv.Value < 100);                      //将访客访问出错次数少于100的移开
            RedisHelper.Set("ArticleViewToken", SnowFlake.GetInstance().GetUniqueShortId(6)); //更新加密文章的密码
            RedisHelper.IncrBy("Interview:RunningDays");
            DateTime time = DateTime.Now.AddMonths(-1);

            _searchDetailsService.DeleteEntitySaved(s => s.SearchTime < time);
        }
Example #13
0
        private void Snow()
        {
            if (ViewBox.Opacity != 0.1)
            {
                ViewBox.Opacity          = 0.1;
                ViewBox.IsHitTestVisible = false;
            }

            var xAmount      = _random.Next(-500, (int)LayoutRoot.ActualWidth - 100);
            var yAmount      = -100;
            var s            = _random.Next(5, 15) * 0.1;
            var rotateAmount = _random.Next(0, 270);

            RotateTransform    rotateTransform    = new RotateTransform(rotateAmount);
            ScaleTransform     scaleTransform     = new ScaleTransform(s, s);
            TranslateTransform translateTransform = new TranslateTransform(xAmount, yAmount);

            var flake = new SnowFlake
            {
                RenderTransform = new TransformGroup
                {
                    Children = new TransformCollection {
                        rotateTransform, scaleTransform, translateTransform
                    }
                },

                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Top,
            };

            RenderOptions.SetBitmapScalingMode(flake, BitmapScalingMode.LowQuality);
            LayoutRoot.Children.Add(flake);

            Duration duration = new Duration(TimeSpan.FromSeconds(_random.Next(1, 4)));

            xAmount += _random.Next(100, 500);
            var xAnimation = GenerateAnimation(xAmount, duration, flake, "RenderTransform.Children[2].X");

            yAmount += (int)(LayoutRoot.ActualHeight + 100 + 100);
            var yAnimation = GenerateAnimation(yAmount, duration, flake, "RenderTransform.Children[2].Y");

            rotateAmount += _random.Next(90, 360);
            var rotateAnimation = GenerateAnimation(rotateAmount, duration, flake, "RenderTransform.Children[0].Angle");

            Storyboard story = new Storyboard();

            story.Completed += (sender, e) => LayoutRoot.Children.Remove(flake);
            story.Children.Add(xAnimation);
            story.Children.Add(yAnimation);
            story.Children.Add(rotateAnimation);
            flake.Loaded += (sender, args) => story.Begin();

            screenSaverTimer.Stop();
            screenSaverTimer.Interval = TimeSpan.FromMilliseconds(screenSaverTimerSnowInterval);
            screenSaverTimer.Start();
        }
        public async Task <ActionResult> UploadFile(IFormFile file)
        {
            string path;
            string filename = SnowFlake.GetInstance().GetUniqueId() + Path.GetExtension(file.FileName);

            switch (file.ContentType)
            {
            case var _ when file.ContentType.StartsWith("image"):
                var(url, success) = await ImagebedClient.UploadImage(file.OpenReadStream(), file.FileName);

                if (success)
                {
                    return(ResultData(url));
                }

                path = Path.Combine(HostEnvironment.WebRootPath, "upload", "images", filename);
                var dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                await using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    file.CopyTo(fs);
                }

                break;

            case var _ when file.ContentType.StartsWith("audio") || file.ContentType.StartsWith("video"):
                path = Path.Combine(HostEnvironment.WebRootPath, "upload", "media", filename);

                break;

            case var _ when file.ContentType.StartsWith("text") || (ContentType.Doc + "," + ContentType.Xls + "," + ContentType.Ppt + "," + ContentType.Pdf).Contains(file.ContentType):
                path = Path.Combine(HostEnvironment.WebRootPath, "upload", "docs", filename);

                break;

            default:
                path = Path.Combine(HostEnvironment.WebRootPath, "upload", "files", filename);
                break;
            }
            try
            {
                await SaveFile(file, path);

                return(ResultData(path.Substring(HostEnvironment.WebRootPath.Length).Replace("\\", "/")));
            }
            catch (Exception e)
            {
                LogManager.Error(e);
                return(ResultData(null, false, "文件上传失败!"));
            }
        }
Example #15
0
        /// <summary>
        /// Creates, moves and deletes snowflakes
        /// Causes form redraw
        /// </summary>
        /// <param name="sender">-</param>
        /// <param name="args">-</param>
        private void OnTick(object sender, EventArgs args)
        {
            //Tick..
            Tick++;

            //Spawn new Flakes
            if (Tick % 3 == 0 && Random.NextDouble() < 0.70)
            {
                SnowFlake s = new SnowFlake();
                s.X           = Random.Next(-50, Width + 50); //All over the screen...
                s.Y           = Random.Next(-20, -7);         //Customize height further
                s.XVelocity   = (float)(Random.NextDouble() - 0.5f) * 2f;
                s.YVelocity   = (float)(Random.NextDouble() * 3) + 1f;
                s.Rotation    = Random.Next(0, 359);
                s.RotVelocity = Random.Next(-3, 3) * 2;

                if (s.RotVelocity == 0)
                {
                    s.RotVelocity = 3;                     //No rotation suxx, really.
                }

                s.Scale = (float)(Random.NextDouble() / 2) + 0.75f;
                SnowFlakes.Add(s);
            }

            //Move current flakes (and add them to del list, if they exceed the screen)
            List <SnowFlake> del = new List <SnowFlake>();

            foreach (SnowFlake s in SnowFlakes)
            {
                s.X        += s.XVelocity;
                s.Y        += s.YVelocity;
                s.Rotation += s.RotVelocity;

                //Make them move snowflake like
                s.XVelocity += ((float)Random.NextDouble() - 0.5f) * 0.7f;
                s.XVelocity  = Math.Max(s.XVelocity, -2f);
                s.XVelocity  = Math.Min(s.XVelocity, +2f);

                if (s.YVelocity > Height + 10)                 //Out of Screen
                {
                    del.Add(s);
                }
            }

            //Delete them
            foreach (SnowFlake s in del)
            {
                SnowFlakes.Remove(s);
            }

            //Redraw our control
            Refresh();
        }
Example #16
0
        public List <string> CreateId()
        {
            var set = new HashSet <string>();

            for (int i = 0; i < 100; i++)
            {
                set.Add(SnowFlake.GetInstance().GetUniqueId());
            }

            return(set.ToList());
        }
        public ActionResult ViewToken()
        {
            if (!RedisHelper.Exists("ArticleViewToken"))
            {
                RedisHelper.Set("ArticleViewToken", SnowFlake.GetInstance().GetUniqueShortId(6));
            }

            var token = RedisHelper.Get("ArticleViewToken");

            return(ResultData(token));
        }
        /// <summary>
        /// 创建一个会议室
        /// </summary>
        /// <param name="creator">创建者</param>
        /// <returns></returns>
        public static MeetingRoom Create(string creator)
        {
            var code = SnowFlake.GetInstance().GetUniqueShortId(8).ToUpper();

            var room = new MeetingRoom(code);

            var message = new Message(null, "System", $"{creator} 创建了会议", "zh-cn");

            room._messages.Add(message);

            return(room);
        }
Example #19
0
        public async Task <ActionResult> UploadFile([FromServices] ImagebedClient imagebedClient, IFormFile file, CancellationToken cancellationToken)
        {
            string path;
            string filename = SnowFlake.GetInstance().GetUniqueId() + Path.GetExtension(file.FileName);
            var    pathBase = CommonHelper.SystemSettings.GetOrAdd("UploadPath", "upload").Trim('/', '\\');

            switch (file.ContentType)
            {
            case var _ when file.ContentType.StartsWith("image"):
            {
                await using var stream = file.OpenReadStream();
                var(url, success)      = await imagebedClient.UploadImage(stream, file.FileName, cancellationToken);

                if (success)
                {
                    return(ResultData(url));
                }

                path = Path.Combine(HostEnvironment.WebRootPath, pathBase, "images", filename);
                var dir = Path.GetDirectoryName(path);
                Directory.CreateDirectory(dir);
                await using var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                await file.CopyToAsync(fs);

                break;
            }

            case var _ when file.ContentType.StartsWith("audio") || file.ContentType.StartsWith("video"):
                path = Path.Combine(HostEnvironment.WebRootPath, pathBase, "media", filename);

                break;

            case var _ when file.ContentType.StartsWith("text") || (ContentType.Doc + "," + ContentType.Xls + "," + ContentType.Ppt + "," + ContentType.Pdf).Contains(file.ContentType):
                path = Path.Combine(HostEnvironment.WebRootPath, pathBase, "docs", filename);

                break;

            default:
                path = Path.Combine(HostEnvironment.WebRootPath, pathBase, "files", filename);
                break;
            }
            try
            {
                await SaveFile(file, path);

                return(ResultData(path.Substring(HostEnvironment.WebRootPath.Length).Replace("\\", "/")));
            }
            catch (Exception e)
            {
                LogManager.Error(e);
                return(ResultData(null, false, "文件上传失败!"));
            }
        }
Example #20
0
        private static DoubleAnimation GenerateAnimation(int x, Duration duration, SnowFlake flake, string propertyPath)
        {
            DoubleAnimation animation = new DoubleAnimation
            {
                To       = x,
                Duration = duration
            };

            Storyboard.SetTarget(animation, flake);
            Storyboard.SetTargetProperty(animation, new PropertyPath(propertyPath));
            return(animation);
        }
Example #21
0
        private void timer_Tick(object sender, EventArgs e)
        {
            Graphics g = Graphics.FromImage(screenImage);

            g.SmoothingMode   = SmoothingMode.HighSpeed;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.Clear(Color.Transparent);
            for (int i = 0; i < SnowFlakes.Count; i++)
            {
                SnowFlake s1 = SnowFlakes[i];
                if (s1.X < -10 || s1.X > Width - 10)
                {
                    SnowFlakes.RemoveAt(i);
                }
                if (s1.Y >= Height - 15 - TaskBarSize.Height && s1.Y < Height - 8)//落到任务栏上
                {
                    s1.Y += 0.8f;
                    g.ResetTransform();
                    g.TranslateTransform(-16, -16, MatrixOrder.Append); //pan
                    //g.ScaleTransform(s1.Scale, s1.Scale, MatrixOrder.Append); //scale
                    //g.RotateTransform(s1.Rotation, MatrixOrder.Append); //rotate
                    g.TranslateTransform(s1.X, s1.Y, MatrixOrder.Append); //pan
                    g.DrawImage(bmp[s1.image], 0, 0);                     //draw
                    continue;
                }
                s1.Y += s1.YVelocity;
                if (飘动ToolStripMenuItem.Checked)
                {
                    s1.X += s1.XVelocity;
                    //s1.Rotation += s1.RotVelocity;
                    s1.XVelocity += ((float)rand.NextDouble() - 0.5f) * 0.7f;
                    s1.XVelocity  = Math.Max(s1.XVelocity, -2f);
                    s1.XVelocity  = Math.Min(s1.XVelocity, +2f);
                }

                if (s1.Y > Height)
                {
                    SnowFlakes.RemoveAt(i);
                }
                else
                {
                    g.ResetTransform();
                    g.TranslateTransform(-16, -16, MatrixOrder.Append); //pan
                    //g.ScaleTransform(s1.Scale, s1.Scale, MatrixOrder.Append); //scale
                    //g.RotateTransform(s1.Rotation, MatrixOrder.Append); //rotate
                    g.TranslateTransform(s1.X, s1.Y, MatrixOrder.Append); //pan
                    g.DrawImage(bmp[s1.image], 0, 0);                     //draw
                }
            }
            g.Dispose();
            SetBackground(screenImage);
        }
Example #22
0
        private void RemoveSnow()
        {
            int intTotalChildren = LayoutRoot.Children.Count - 1;

            for (int intCounter = intTotalChildren; intCounter > 0; intCounter--)
            {
                if (LayoutRoot.Children[intCounter].GetType() == typeof(SnowFlake))
                {
                    SnowFlake ucCurrentChild = (SnowFlake)LayoutRoot.Children[intCounter];
                    LayoutRoot.Children.Remove(ucCurrentChild);
                }
            }
        }
Example #23
0
        //画像が削除されて意味がなくなったツイートを消す
        //URL転載したやつの転載元ツイートが消された場合
        public int RemoveOrphanTweet()
        {
            const int    BulkUnit      = 100;
            const int    RangeSeconds  = 300;
            const string head          = @"DELETE FROM tweet WHERE tweet_id IN";
            string       BulkDeleteCmd = BulkCmdStrIn(BulkUnit, head);

            TransformBlock <long, DataTable> GetTweetBlock = new TransformBlock <long, DataTable>(async(long id) =>
            {
                using (MySqlCommand Cmd = new MySqlCommand(@"SELECT tweet_id
FROM tweet
WHERE retweet_id IS NULL
AND NOT EXISTS (SELECT * FROM tweet_media WHERE tweet_media.tweet_id = tweet.tweet_id)
AND tweet_id BETWEEN @begin AND @end
ORDER BY tweet_id DESC;"))
                {
                    Cmd.Parameters.AddWithValue("@begin", id);
                    Cmd.Parameters.AddWithValue("@end", id + SnowFlake.msinSnowFlake * RangeSeconds * 1000 - 1);
                    return(await SelectTable(Cmd, IsolationLevel.RepeatableRead));
                }
            }, new ExecutionDataflowBlockOptions {
                MaxDegreeOfParallelism = Environment.ProcessorCount
            });


            DateTimeOffset date = DateTimeOffset.UtcNow.AddHours(-1);

            for (int i = 0; i < 20; i++)
            {
                GetTweetBlock.Post(SnowFlake.SecondinSnowFlake(date, false));
                date = date.AddHours(-1);
            }
            while (true)
            {
                DataTable Table = GetTweetBlock.Receive();
                if (Table.Rows.Count > 0)
                {
                    using (MySqlCommand delcmd = new MySqlCommand(BulkCmdStrIn(Table.Rows.Count, head)))
                    {
                        for (int n = 0; n < Table.Rows.Count; n++)
                        {
                            delcmd.Parameters.AddWithValue("@" + n.ToString(), Table.Rows[n].Field <long>(0));
                        }
                        Console.WriteLine("{0} {1} Tweets removed", date, ExecuteNonQuery(delcmd));
                    }
                }
                GetTweetBlock.Post(SnowFlake.SecondinSnowFlake(date, false));
                date = date.AddSeconds(-RangeSeconds);
            }
        }
Example #24
0
        /// <summary>
        /// 通用文件上传
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        private async Task <ResultInfo> FileUpload(IFormFile file)
        {
            if (file == null)
            {
                return(FailResp("上传文件为空!"));
            }
            string filename = $"{DateTime.Now:yyyyMMddHHmmss}" + SnowFlake.GetInstance().GetUniqueShortId(9) + Path.GetExtension(file.FileName);
            string path;

            switch (file.ContentType)
            {
            case var _ when file.ContentType.StartsWith("image"):
                path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "images", $"{DateTime.Now:yyyy}/{DateTime.Now:MM}/{DateTime.Now:dd}", filename);

                break;

            case var _ when file.ContentType.StartsWith("audio") || file.ContentType.StartsWith("video"):
                path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "media", $"{DateTime.Now:yyyy}/{DateTime.Now:MM}/{DateTime.Now:dd}", filename);

                break;

            case var _ when file.ContentType.StartsWith("text") || (ContentType.Doc + "," + ContentType.Xls + "," + ContentType.Ppt + "," + ContentType.Pdf).Contains(file.ContentType):
                path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "docs", $"{DateTime.Now:yyyy}/{DateTime.Now:MM}/{DateTime.Now:dd}", filename);

                break;

            default:
                path = Path.Combine(_hostingEnvironment.WebRootPath, "upload", "files", $"{DateTime.Now:yyyy}/{DateTime.Now:MM}/{DateTime.Now:dd}", filename);
                break;
            }
            try
            {
                var dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    await file.CopyToAsync(fs);
                }
                return(SuccResp(path.Substring(_hostingEnvironment.WebRootPath.Length).Replace("\\", "/")));
            }
            catch (Exception e)
            {
                LogManager.Error(GetType(), e);
                return(FailResp("文件上传失败!"));
            }
        }
Example #25
0
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="users"></param>
        /// <returns></returns>
        public string Reg(Models.Users user)
        {
            if (Count(x => x.Email == user.Email) > 0)
            {
                return(ERROR.EMAIL_EXIST);
            }
            user.UID           = SnowFlake.CreateId();
            user.GID           = 0;
            user.CreateDate    = DateTime.Now;
            user.UpdateDate    = DateTime.Now;
            user.Status        = "";
            user.Salt          = RandomUtil.Random(6);
            user.EmailActivate = false;
            user.Password      = Algorithm.MD5.ComputeHash(user.Password + Algorithm.MD5.ComputeHash(user.Salt));
            object obj = Insert(user);

            return("");
        }
Example #26
0
        /// <summary>
        /// 上传图片到人民网图床
        /// </summary>
        /// <returns></returns>
        public static (string url, bool success) UploadPeople(Stream stream, string ext)
        {
            bool success = false;

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.UserAgent.Add(ProductInfoHeaderValue.Parse("Chrome/72.0.3626.96"));
                using (var sc = new StreamContent(stream))
                {
                    using (var mc = new MultipartFormDataContent
                    {
                        { sc, "Filedata", SnowFlake.GetInstance().GetUniqueId() + ext },
                        { new StringContent(ext), "filetype" }
                    })
                    {
                        var str = httpClient.PostAsync("http://bbs1.people.com.cn/postImageUpload.do", mc).ContinueWith(t =>
                        {
                            if (t.IsCompletedSuccessfully)
                            {
                                var res = t.Result;
                                if (res.IsSuccessStatusCode)
                                {
                                    string result = res.Content.ReadAsStringAsync().Result;
                                    string url    = "http://bbs1.people.com.cn" + (string)JObject.Parse(result)["imageUrl"];
                                    if (url.EndsWith(ext))
                                    {
                                        success = true;
                                        return(url);
                                    }
                                }
                            }

                            return("");
                        }).Result;
                        if (!success)
                        {
                            Console.WriteLine("人民网图床上传接口都挂掉了,重试sm.ms图床");
                            return(UploadImageFallback(stream, ext));
                        }
                        return(str, success);
                    }
                }
            }
        }
        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            bool b = CheckIsLocalIp(_machineId.ToString()).Result;

            if (b)
            {
                _cacheAsync.Expire(Name + _datacenterId + _machineId, 60 * 60 * 24);
            }
            else
            {
                // IP冲突
                // 重新生成机器ID,并且更改雪花中的机器ID
                GetRandomMachineId();
                //重新生成并注册机器ID
                CreateMachineId().Wait();
                // 更改雪花中的机器ID
                SnowFlake.SetMachineId(_machineId);
            }
        }
Example #28
0
        public async Task OnGetAsync()
        {
            var sw = Stopwatch.StartNew();

            //一瞬でも速くしたいので先にTaskを作って必要なところでawaitする
            Params = new FeaturedParameters();
            var ParamsTask = Params.InitValidate(HttpContext);

            var ThisDate = Date.HasValue ? DateTimeOffset.FromUnixTimeSeconds(Date.Value) : DateTimeOffset.UtcNow;

            await ParamsTask.ConfigureAwait(false);

            Tweets = await DB.SimilarMediaFeatured(3, SnowFlake.SecondinSnowFlake(ThisDate - TimeSpan.FromHours(1), false), SnowFlake.SecondinSnowFlake(ThisDate, true), Params.Featured_Order.Value).ConfigureAwait(false);

            if (Tweets.Length == 0)
            {
                HttpContext.Response.StatusCode = StatusCodes.Status404NotFound;
            }
            QueryElapsedMilliseconds = sw.ElapsedMilliseconds;
        }
Example #29
0
            /// <summary>
            /// Draws a snow flake.
            /// </summary>
            /// <param name="g">The System.Drawing.Graphics to draw on.</param>
            /// <param name="snowFlake">The snowflake to draw.</param>
            private void DrawSnowFlake(Graphics g, SnowFlake snowFlake)
            {
                g.ResetTransform();
                // Tranform to upper left corner before rotating.
                // This produces a nice wobbling effect.
                g.TranslateTransform(-snowFlake.Size / 2, -snowFlake.Size / 2, MatrixOrder.Append);
                g.ScaleTransform((float)snowFlake.Size / 6.0f, (float)snowFlake.Size / 6.0f);
                g.RotateTransform((float)snowFlake.Rotation, MatrixOrder.Append);
                g.TranslateTransform(snowFlake.Location.X, snowFlake.Location.Y, MatrixOrder.Append);
                using (SolidBrush brush = new SolidBrush(Color.White))
                    using (Pen pen = new Pen(Color.Gray))
                        using (Pen glowPen = new Pen(Color.FromArgb(96, Color.White), 2.0f))
                        {
                            g.DrawPath(glowPen, flake);
                            g.FillPath(brush, flake);
                            g.DrawPath(pen, flake);
                        }

                g.ResetTransform();
            }
Example #30
0
        /// <summary>
        /// 每天的任务
        /// </summary>
        public void EverydayJob()
        {
            CommonHelper.IPErrorTimes.RemoveWhere(kv => kv.Value < 100);                      //将访客访问出错次数少于100的移开
            RedisHelper.Set("ArticleViewToken", SnowFlake.GetInstance().GetUniqueShortId(6)); //更新加密文章的密码
            RedisHelper.IncrBy("Interview:RunningDays");
            DateTime time = DateTime.Now.AddMonths(-1);

            _searchDetailsService.DeleteEntitySaved(s => s.SearchTime < time);
            foreach (var p in _postService.GetAll().AsParallel())
            {
                try
                {
                    p.AverageViewCount = p.PostAccessRecord.Average(r => r.ClickCount);
                    p.TotalViewCount   = p.PostAccessRecord.Sum(r => r.ClickCount);
                    _postService.UpdateEntity(p);
                    _postService.SaveChanges();
                }
                catch (Exception)
                {
                }
            }
        }
Example #31
0
 public SnowFlake addSnowFlake(float x, float y, float scale)
 {
     SnowFlake obj = new SnowFlake(x, y, scale);
     addObject(obj, -5);
     return obj;
 }
            /// <summary>
            /// Draws a snow flake.
            /// </summary>
            /// <param name="g">The System.Drawing.Graphics to draw on.</param>
            /// <param name="snowFlake">The snowflake to draw.</param>
            private void DrawSnowFlake(Graphics g, SnowFlake snowFlake)
            {
                g.ResetTransform();
                // Tranform to upper left corner before rotating.
                // This produces a nice wobbling effect.
                g.TranslateTransform(-snowFlake.Size / 2, -snowFlake.Size / 2, MatrixOrder.Append);
                g.ScaleTransform((float)snowFlake.Size / 6.0f, (float)snowFlake.Size / 6.0f);
                g.RotateTransform((float)snowFlake.Rotation, MatrixOrder.Append);
                g.TranslateTransform(snowFlake.Location.X, snowFlake.Location.Y, MatrixOrder.Append);
                using (SolidBrush brush = new SolidBrush(Color.White))
                using (Pen pen = new Pen(Color.Gray))
                using (Pen glowPen = new Pen(Color.FromArgb(96, Color.White), 2.0f))
                {
                    g.DrawPath(glowPen, flake);
                    g.FillPath(brush, flake);
                    g.DrawPath(pen, flake);
                }

                g.ResetTransform();
            }
            /// <summary>
            /// Updates snow flakes at each timer tick.
            /// </summary>
            /// <param name="state">Not used, null.</param>
            private void UpdateTimerCallback(object state)
            {
                if (inTimer) return;
                inTimer = true;

                bool redraw = false;

                lock (lockObject)
                {
                    if (displayBounds.IsEmpty)
                    {
                        inTimer = false;
                        return;
                    }

                    if (flakes == null)
                        flakes = new List<SnowFlake>();

                    // Add new snow flakes
                    currentGeneration++;
                    if (currentGeneration == flakeGeneration)
                    {
                        currentGeneration = 0;
                        if (flakes.Count < maxFlakeCount)
                        {
                            SnowFlake snowFlake = new SnowFlake(random.Next(minFlakeSize, maxFlakeSize));
                            snowFlake.Rotation = 360.0 * random.NextDouble();
                            snowFlake.Location = new Point(random.Next(displayBounds.Left, displayBounds.Right), -20);
                            flakes.Add(snowFlake);
                        }
                    }

                    // Move snow flakes
                    for (int i = flakes.Count - 1; i >= 0; i--)
                    {
                        SnowFlake snowFlake = flakes[i];
                        if (snowFlake.Location.Y > displayBounds.Height)
                            flakes.Remove(snowFlake);
                        else
                        {
                            snowFlake.Location = new Point(snowFlake.Location.X, snowFlake.Location.Y + snowFlake.Size * fallSpeed / 10);
                            snowFlake.Rotation += 360.0 / 40.0;
                            if (snowFlake.Rotation > 360.0) snowFlake.Rotation -= 360.0;
                        }
                    }

                    // Do we need a refresh?
                    if ((DateTime.Now - lastRedraw).Milliseconds > refreshPeriod)
                        redraw = true;
                }

                if (redraw)
                {
                    try
                    {
                        if (ImageListView != null && ImageListView.IsHandleCreated && !ImageListView.IsDisposed)
                        {
                            if (ImageListView.InvokeRequired)
                                ImageListView.BeginInvoke((MethodInvoker)delegate { ImageListView.Refresh(); });
                            else
                                ImageListView.Refresh();
                        }
                    }
                    catch
                    {
                        ;
                    }
                }

                inTimer = false;
            }