private void logBt_Click(object sender, RoutedEventArgs e)
        {
            UserData     userData     = new UserData();
            MessagesData messagesData = new MessagesData();

            SetupData(userData);

            using (registerDbEntities db = new registerDbEntities())
            {
                if (NotEmpty(userData))
                {
                    if (LoginValid(userData, db))
                    {
                        OpenProfile();
                    }
                    else
                    {
                        msg.Content = messagesData.LoginValid;
                    }
                }
                else
                {
                    msg.Content = messagesData.MsgEmpty;
                }
            }
        }
Exemple #2
0
 private void CheckUser(UserData ud, registerDbEntities db, MessagesData messagesData)
 {
     foreach (User _user in ud.Users)
     {
         if (_user != null)
         {
             if (!Validation(ud))
             {
                 msg.Content = messagesData.MsgEmpty;
             }
             else
             {
                 if (IsValid(ud.Email))
                 {
                     if (ud.Password == ud.PassRepeat)
                     {
                         DbUpdate(_user, ud, db);
                     }
                 }
                 else
                 {
                     msg.Content = messagesData.MsgValidEmail;
                 }
             }
         }
     }
 }
Exemple #3
0
        public async Task GenerateNotificationsAsync_RelevantMention_ShouldReturnConfiguredNotificationText()
        {
            var subscriber = new Subscriber
            {
                ChatId        = 1,
                Configuration = new NotificationConfiguration
                {
                    Mentions = new List <MentionConfiguration>
                    {
                        new MentionConfiguration {
                            MentionedUsername = "******", NotificationText = "TestNotificationText"
                        }
                    }
                }
            };

            _subscriptionService.Setup(x => x.GetAllSubscriptionsAsync()).ReturnsAsync(new[] { subscriber });

            var testData = new MessagesData {
                LatestMessageTimeStamp = DateTime.Now, MentionedUsernames = new[] { "username" }
            };
            var actual = (await _notificationProvider.GenerateNotificationsAsync(testData).ConfigureAwait(false)).ToArray();

            Assert.AreEqual(1, actual.Length);
            Assert.AreEqual(subscriber.ChatId, actual.First().ChatId);
            Assert.AreEqual(subscriber.Configuration.Mentions.First().NotificationText, actual.First().Text);
        }
Exemple #4
0
        /// <summary>
        /// Generates notification message for subscriber based on messages data provided.
        /// </summary>
        /// <param name="subscriber">Subscriber info.</param>
        /// <param name="messages">Messages data.</param>
        /// <returns>Subscriber notification message.</returns>
        private Notification GenerateNotification(Subscriber subscriber, MessagesData messages)
        {
            if (messages.MentionedUsernames.Length == 0 || subscriber.Configuration == null)
            {
                return new Notification {
                           ChatId = subscriber.ChatId, Text = DefaultNotificationText
                }
            }
            ;

            var notification = new Notification {
                ChatId = subscriber.ChatId
            };

            var subscriberMentionsConfig = subscriber.Configuration.Mentions;

            foreach (var mentionedUsername in messages.MentionedUsernames)
            {
                var relevantConfig = subscriberMentionsConfig
                                     .FirstOrDefault(c => c.MentionedUsername.Equals(mentionedUsername, StringComparison.InvariantCultureIgnoreCase));

                if (relevantConfig == null)
                {
                    continue;
                }

                notification.Text = $"{notification.Text}{relevantConfig.NotificationText}{Environment.NewLine}";
            }

            notification.Text = string.IsNullOrWhiteSpace(notification.Text) ? DefaultNotificationText : notification.Text.Trim();
            return(notification);
        }
    }
Exemple #5
0
        /// <inheritdoc/>
        public async Task <IEnumerable <Notification> > GenerateNotificationsAsync(MessagesData data)
        {
            var subscribers = await _subscriptionService.GetAllSubscriptionsAsync().ConfigureAwait(false);

            var notifications = subscribers.Select(s => GenerateNotification(s, data));

            return(notifications);
        }
Exemple #6
0
        /// <summary>
        /// Notifies subscribers about the discovered message.
        /// </summary>
        /// <param name="recentMessages">Data on recent messages.</param>
        /// <returns>A task that represents the subscribers notification process.</returns>
        private async Task NotifySubscribersAsync(MessagesData recentMessages)
        {
            var notifications = await _notificationProvider.GenerateNotificationsAsync(recentMessages).ConfigureAwait(false);

            foreach (var notification in notifications)
            {
                await NotifyAsync(notification).ConfigureAwait(false);
            }
        }
Exemple #7
0
        public async Task GenerateNotificationsAsync_NoSubscribers_ShouldReturnEmpty()
        {
            _subscriptionService.Setup(x => x.GetAllSubscriptionsAsync()).ReturnsAsync(Array.Empty <Subscriber>());

            var testData = new MessagesData {
                LatestMessageTimeStamp = DateTime.Now, MentionedUsernames = new[] { "username" }
            };
            var actual = (await _notificationProvider.GenerateNotificationsAsync(testData).ConfigureAwait(false)).ToArray();

            Assert.AreEqual(0, actual.Length);
        }
        /// <summary>
        /// Default constructor
        /// </summary>
        public Game()
        {
            // Construct dungeons
            // Not doing this tidily and programmicably - 'cause it is going to change and we don't
            // want 10 identically boring levels
            DungeonStore["D01"] = DungeonGenerators.RoomsGenerator.Generate(40, 20, new List <Passage>()
            {
                new Passage(Passage.PassageTypeEnum.OneWay, "START"),
                new Passage(Passage.PassageTypeEnum.StairsDown, "D02")
            });

            DungeonStore["D02"] = DungeonGenerators.RoomsGenerator.Generate(40, 20, new List <Passage>()
            {
                new Passage(Passage.PassageTypeEnum.StairsUp, "D01"),
                new Passage(Passage.PassageTypeEnum.StairsDown, "D03")
            });

            DungeonStore["D03"] = DungeonGenerators.RoomsGenerator.Generate(40, 20, new List <Passage>()
            {
                new Passage(Passage.PassageTypeEnum.StairsUp, "D02"),
                new Passage(Passage.PassageTypeEnum.StairsDown, "D04")
            });

            DungeonStore["D04"] = DungeonGenerators.RoomsGenerator.Generate(40, 20, new List <Passage>()
            {
                new Passage(Passage.PassageTypeEnum.StairsUp, "D03"),
                new Passage(Passage.PassageTypeEnum.StairsDown, "D05")
            });

            DungeonStore["D05"] = DungeonGenerators.RoomsGenerator.Generate(40, 20, new List <Passage>()
            {
                new Passage(Passage.PassageTypeEnum.StairsUp, "D05")
            });

            // Set the Dungeon for each passage
            foreach (var dungeon in DungeonStore)
            {
                foreach (var passage in dungeon.Value.Passages)
                {
                    DungeonStore.TryGetValue(passage.DestinationID, out passage.Destination);
                }
            }

            Player = new Player(DungeonStore["D01"]);

            // Create empty messages list - prevent crash on first turn
            MessagesData.Add(new List <Message.Message>());
        }
Exemple #9
0
        public async Task GenerateNotificationsAsync_NoMentionsConfig_ShouldReturnDefaultNotification()
        {
            var subscriber = new Subscriber {
                ChatId = 1
            };

            _subscriptionService.Setup(x => x.GetAllSubscriptionsAsync()).ReturnsAsync(new[] { subscriber });

            var testData = new MessagesData {
                LatestMessageTimeStamp = DateTime.Now, MentionedUsernames = new[] { "username" }
            };
            var actual = (await _notificationProvider.GenerateNotificationsAsync(testData).ConfigureAwait(false)).ToArray();

            Assert.AreEqual(1, actual.Length);
            Assert.AreEqual(subscriber.ChatId, actual.First().ChatId);
            Assert.AreEqual("New Rocket.Chat message received", actual.First().Text);
        }
Exemple #10
0
        private void regBt_Click(object sender, RoutedEventArgs e)
        {
            msg.Content = string.Empty;
            UserData     userData     = new UserData();
            MessagesData messagesData = new MessagesData();

            SetupData(userData);
            DownloadData(userData);

            using (registerDbEntities db = new registerDbEntities())
            {
                if (NotEmpty(userData))
                {
                    AddUser(userData);
                    CheckUser(userData, db, messagesData);
                }
                else
                {
                    msg.Content = messagesData.MsgEmpty;
                }
            }
        }
Exemple #11
0
        public async Task GenerateNotificationsAsync_SeveralSubscribers_ShouldReturnSeveralNotifications()
        {
            var subscriber1 = new Subscriber {
                ChatId = 1
            };
            var subscriber2 = new Subscriber {
                ChatId = 2
            };

            _subscriptionService.Setup(x => x.GetAllSubscriptionsAsync()).ReturnsAsync(new[] { subscriber1, subscriber2 });

            var testData = new MessagesData {
                LatestMessageTimeStamp = DateTime.Now, MentionedUsernames = Array.Empty <string>()
            };
            var actual = (await _notificationProvider.GenerateNotificationsAsync(testData).ConfigureAwait(false)).ToArray();

            Assert.AreEqual(2, actual.Length);
            Assert.AreEqual(subscriber1.ChatId, actual[0].ChatId);
            Assert.AreEqual(subscriber2.ChatId, actual[1].ChatId);
            Assert.AreEqual("New Rocket.Chat message received", actual[0].Text);
            Assert.AreEqual("New Rocket.Chat message received", actual[1].Text);
        }
Exemple #12
0
        /// <summary>
        /// Do a turn in the game
        /// </summary>
        public void DoTurn()
        {
            var turnMessages = CurrentDungeon.DoTurn();

            MessagesData.Add(turnMessages);

            if (Player.Dead)
            {
                GameOver    = true;
                EndGameText = new List <string>()
                {
                    "Would you like your corpse identified?",
                    "Congratulations!",
                    "Your journey end here. In many pieces",
                    "Rest in many pieces",
                    "Death was too good for you!",
                    "Y. A. S. D",
                    "How sad. I'm sorry. I really am. <beat> I'm not."
                }.RandomItem();
                EndGameTitle = "You have died";
            }
        }
        /// <summary>
        /// Do a turn in the game
        /// </summary>
        public void DoTurn()
        {
            var turnMessages = CurrentDungeon.DoTurn();

            MessagesData.Add(turnMessages);
        }
Exemple #14
0
        /// <summary>
        /// 上传图片,不生成相关大小配置图片
        /// </summary>
        /// <param name="key">秘钥</param>
        /// <param name="nodeDir">目录</param>
        /// <returns></returns>
        public string UploadImg(IFormFile file, string key = "", string nodeDir = "")
        {
            MessagesData <FileViewModel> r = new MessagesData <FileViewModel>()
            {
                Success = false,
                Msg     = "服务无响应"
            };

            try
            {
                if (key == AS.Singleton.FileServerMD5Key)
                {
                    if (file != null)
                    {
                        long fileSize = file.Length;
                        if (fileSize > AS.Singleton.UploadImgMaxSize * 1024)
                        {
                            r.Msg = "上传图片大小不能超过" + AS.Singleton.UploadImgMaxSize + "KB";
                        }
                        else
                        {
                            //获取文件名
                            string uploadFileName = file.FileName;
                            //获取文件扩展名
                            string extension = Path.GetExtension(uploadFileName).ToLowerInvariant();
                            if (AS.Singleton.UploadImgExt.Contains(extension.TrimStart('.')))
                            {
                                //路径格式化
                                string path = PathFormatter.Format(AS.Singleton.UploadFilePathRule, nodeDir);
                                //文件名格式化
                                string fileName = FileNameFormatter.Format(uploadFileName, AS.Singleton.FileNameRule);
                                //保存路径
                                string savePath = AS.Singleton.UploadDir + "\\" + path.Replace("/", "\\");
                                //访问地址
                                string url = $"{AS.Singleton.UploadUrl}/";
                                //若设置为上传至共享目录,否则上传至当前服务目录wwwroot中
                                if (AS.Singleton.EnabledUploadShare == "false")
                                {
                                    savePath = fileProvider.Combine(hostingEnv.WebRootPath, savePath);
                                    url     += $"{AS.Singleton.UploadDir}/";
                                }
                                //创建保存目录
                                fileProvider.CreateDirectory(savePath);
                                //文件全名(包括路径和文件名)
                                string fileFullName = fileProvider.Combine(savePath, fileName);
                                using (FileStream fs = File.Create(fileFullName))
                                {
                                    file.CopyTo(fs);
                                    fs.Flush();
                                }
                                url      += $"{path}/{fileName}";
                                r.Success = true;
                                r.Msg     = "上传成功";
                                //将图片URL加密成guid,用于上传时可删除图片操作
                                r.Data = new FileViewModel(desEncrypt.Encrypt(url), url, null, null);
                            }
                            else
                            {
                                r.Msg = "上传图片扩展名只允许为" + AS.Singleton.UploadImgExt;
                            }
                        }
                    }
                    else
                    {
                        r.Msg = "上传图片大小为0";
                    }
                }
                else
                {
                    r.Msg = "无上传图片权限";
                }
            }
            catch (UnauthorizedAccessException)
            {
                r.Msg = "文件系统权限不足";
            }
            catch (DirectoryNotFoundException)
            {
                r.Msg = "路径不存在";
            }
            catch (IOException)
            {
                r.Msg = "文件系统读取错误";
            }
            catch (Exception)
            {
                r.Msg = "上传出错";
            }
            return(r.ToJson());
        }
Exemple #15
0
        /// <summary>
        /// 上传商品图片
        /// </summary>
        /// <param name="key">秘钥</param>
        /// <returns></returns>
        public string UploadProductImg(IFormFile file, string key = "")
        {
            MessagesData <FileViewModel> r = new MessagesData <FileViewModel>()
            {
                Success = false,
                Msg     = "服务无响应"
            };

            try
            {
                if (key == AS.Singleton.FileServerMD5Key)
                {
                    if (file != null)
                    {
                        long fileSize = file.Length;
                        if (fileSize > AS.Singleton.UploadImgMaxSize * 1024)
                        {
                            r.Msg = "上传图片大小不能超过" + AS.Singleton.UploadImgMaxSize + "KB";
                        }
                        else
                        {
                            //获取上传文件名
                            string uploadFileName = file.FileName;
                            //获取文件扩展名
                            string extension = Path.GetExtension(uploadFileName).ToLowerInvariant();
                            if (AS.Singleton.UploadImgExt.Contains(extension.TrimStart('.')))
                            {
                                //路径格式化
                                string dirPath = PathFormatter.Format(AS.Singleton.UploadFilePathRule, "product");
                                //原图路径
                                string sourceDirPath = dirPath + "/source";
                                //文件名格式化
                                string fileName = FileNameFormatter.Format(uploadFileName, AS.Singleton.FileNameRule);
                                //定义原图保存路径
                                string saveSourcePath = AS.Singleton.UploadDir + "\\" + sourceDirPath.Replace("/", "\\");
                                //访问地址
                                string url = $"{AS.Singleton.UploadUrl}/";
                                //若设置为上传至共享目录,否则上传至当前服务目录wwwroot中
                                if (AS.Singleton.EnabledUploadShare == "false")
                                {
                                    saveSourcePath = fileProvider.Combine(hostingEnv.WebRootPath, saveSourcePath);
                                    url           += $"{AS.Singleton.UploadDir}/";
                                }
                                //创建保存原图目录
                                fileProvider.CreateDirectory(saveSourcePath);
                                //原文件全名
                                string fileFullName = fileProvider.Combine(saveSourcePath, fileName);
                                using (FileStream fs = File.Create(fileFullName))
                                {
                                    file.CopyTo(fs);
                                    fs.Flush();
                                }
                                if (AS.Singleton.WatermarkType == 1)//文字水印
                                {
                                    string path = string.Format("{0}\\{1}_text{2}", saveSourcePath, fileName.Substring(0, fileName.LastIndexOf('.')), extension);
                                    IOHelper.GenerateTextWatermark(fileFullName, path, AS.Singleton.WatermarkText, AS.Singleton.WatermarkTextSize, AS.Singleton.WatermarkTextFont, AS.Singleton.WatermarkPosition, AS.Singleton.WatermarkQuality);
                                    fileFullName = path;
                                }
                                else if (AS.Singleton.WatermarkType == 2)//图片水印
                                {
                                    string path = string.Format("{0}\\{1}_img{2}", saveSourcePath, fileName.Substring(0, fileName.LastIndexOf('.')), extension);
                                    //放在本应用图片目录下的水印图片路径
                                    string watermarkPath = hostingEnv.WebRootPath + @"\images\" + AS.Singleton.WatermarkImg;
                                    //创建水印图片
                                    IOHelper.GenerateImageWatermark(fileFullName, watermarkPath, path, AS.Singleton.WatermarkPosition, AS.Singleton.WatermarkImgOpacity, AS.Singleton.WatermarkQuality);
                                    fileFullName = path;
                                }
                                string[] sizeList = StringHelper.SplitString(AS.Singleton.ProductShowThumbSize);
                                foreach (string size in sizeList)
                                {
                                    string thumbDirPath = string.Format("{0}/thumb{1}/", dirPath, size);
                                    thumbDirPath = AS.Singleton.UploadDir + "\\" + thumbDirPath.Replace("/", "\\");
                                    //若设置为上传至共享目录,否则上传至当前服务目录wwwroot中
                                    if (AS.Singleton.EnabledUploadShare == "false")
                                    {
                                        thumbDirPath = fileProvider.Combine(hostingEnv.WebRootPath, thumbDirPath);
                                    }
                                    //创建缩略图目录
                                    fileProvider.CreateDirectory(thumbDirPath);
                                    string[] widthAndHeight = StringHelper.SplitString(size, "_");
                                    IOHelper.GenerateThumb(fileFullName,
                                                           thumbDirPath + fileName,
                                                           widthAndHeight[0].AsInt(),
                                                           widthAndHeight[1].AsInt(),
                                                           "H");
                                }
                                url      += $"{sourceDirPath}/{fileName}";
                                r.Success = true;
                                r.Msg     = "上传成功";
                                r.Data    = new FileViewModel(desEncrypt.Encrypt(url), url, null, null);
                            }
                            else
                            {
                                r.Msg = "上传图片扩展名只允许为" + AS.Singleton.UploadImgExt;
                            }
                        }
                    }
                    else
                    {
                        r.Msg = "上传图片大小为0";
                    }
                }
                else
                {
                    r.Msg = "无上传图片权限";
                }
            }
            catch (UnauthorizedAccessException)
            {
                r.Msg = "文件系统权限不足";
            }
            catch (DirectoryNotFoundException)
            {
                r.Msg = "路径不存在";
            }
            catch (IOException)
            {
                r.Msg = "文件系统读取错误";
            }
            catch (Exception)
            {
                r.Msg = "上传出错";
            }
            return(r.ToJson());
        }
Exemple #16
0
        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="getAssetStream">Asset stream getter - if not default (filesystem)</param>
        public Game(TGetAssetStream getAssetStream = null)
        {
            // Set GetAssetStream if changed from default
            GetAssetStream = getAssetStream ?? GetAssetStream;

            // Load the data from Monsters.Json into the Monster Factory
            using (var monsterFileReader = new StreamReader(GetAssetStream("monsters.json")))
            {
                var monsterFileText = monsterFileReader.ReadToEnd();
                var deserializedMonsterPrototypes =
                    JsonConvert.DeserializeObject <Dictionary <String, JObject> >(monsterFileText);
                foreach (var prototype in deserializedMonsterPrototypes)
                {
                    MonsterFactory.AddPrototype(prototype.Key, prototype.Value);
                }
            }

            // Construct dungeons
            // We get the parameters for building them, then we build them
            Dictionary <string, DungeonPrototype> dungeonsToDig;

            using (var dungeonsFileReader = new StreamReader(GetAssetStream("dungeons.json")))
            {
                var dungeonsFileText = dungeonsFileReader.ReadToEnd();
                dungeonsToDig = JsonConvert.DeserializeObject <Dictionary <string, DungeonPrototype> >
                                    (dungeonsFileText);
            }
            foreach (var dungeonToDig in dungeonsToDig)
            {
                var dungeon = dungeonToDig.Value.Generator.Generate(
                    width: dungeonToDig.Value.Width,
                    height: dungeonToDig.Value.Height,
                    passages: dungeonToDig.Value.Passages);
                DungeonStore.Add(dungeonToDig.Key, dungeon);

                // Place enemies per the dungeon to dig
                for (int i = 0; i < 20; ++i)
                {
                    var monster   = dungeonToDig.Value.MonstersToBuild.RandomItem();
                    var spawnArea = dungeon.SpawnAreas.RandomItem();
                    if (spawnArea.Area.Count > 0)
                    {
                        var spawnLocation = spawnArea.Area.RandomItem();
                        spawnArea.Area.Remove(spawnLocation);
                        MonsterFactory.CreateMonster(this, dungeon, monster, spawnLocation);
                    }
                }
            }

            // Set the Dungeon for each passage
            foreach (var dungeon in DungeonStore)
            {
                foreach (var passage in dungeon.Value.Passages)
                {
                    DungeonStore.TryGetValue(passage.DestinationID, out passage.Destination);
                }
            }

            // Find the start passage - and what dungeon it's in
            var start = DungeonStore.SelectMany(i => i.Value.Passages)
                        .First(i => i.DestinationID == "START");
            var startDungeon = DungeonStore.First(i => i.Value.Passages.Contains(start)).Value;

            Player = new Player(startDungeon);

            // Create empty messages list - prevent crash on first turn
            MessagesData.Add(new List <Message.Message>());
        }