예제 #1
0
파일: Program.cs 프로젝트: Greeley/Samples
        static void Main(string[] args)
        {
            MapperProvider.Instance.RegisterAssembly(Assembly.GetExecutingAssembly());

            // allows us to create ADO.NET classes
            // without knowing the actual driver
            // and by just using the app/web.config
            var factory = new AppConfigConnectionFactory("DemoDb");
            var connection = factory.Create();

            var queries = new UserQueries(connection);

            var constraints = new QueryConstraints<User>()
                .SortBy(x => x.FirstName)
                .Page(2, 2);
            var result = queries.FindAll(constraints);
            foreach (var user in result.Items)
            {
                // Note that each user is not mapped until it's requested
                // as opposed to the entire collection being mapped first.
                Console.WriteLine(user.FirstName);
            }

            // and storage:
            var storage = new UserStorage(connection);
            var firstUser = storage.Load(1);
            Console.WriteLine(firstUser.FirstName);
        }
예제 #2
0
 public void Init(string path)
 {
     if(IsInit) return;
     IsInit = true;
     _filePath = path;
     _userStorage = UserStorageExt.LoadStorage(path);
     _lastUserInfoId = _userStorage.Max(x=>x.Id);
 }
예제 #3
0
 /// <summary>
 /// Asynchronously updates a user.
 /// </summary>
 /// <param name="user">The user.</param>
 /// <returns>The task representing the asynchronous operation.</returns>
 public virtual async Task<IdentityResult> UpdateAsync(TUser user)
 {
     return new IdentityResult(await UserStorage.UpdateAsync(user));
 }
예제 #4
0
 public virtual bool IsRegistered(Message message)
 => UserStorage.CheckUserDb(message.From.Id);
예제 #5
0
 public Identity(UserStorage userStorage)
 {
     this._userStorage = userStorage;
 }
예제 #6
0
 public async static Task <bool> CreateEvent(UserDisciplinaryEventStorage newEvent, UserStorage newUser)
 {
     return(await HandleEventCreated(newEvent, newUser));
 }
예제 #7
0
 private void OnUserClickedStart(string userName)
 {
     UserStorage.getInstance().UserName = userName;
     StartNewGame();
 }
예제 #8
0
        private void SetReadabilityUser(UserProfile user, string token, string secret, bool saveToDisk)
        {
            LoggedInReadabilityUser = user;
            _readabilityClient.AccessToken = new AccessToken(token, secret);

            if (saveToDisk)
            {
                var storage = new UserStorage<UserProfile>(user, token, secret);
                var json = JsonConvert.SerializeObject(storage);
                WriteAllTextAsync(Constants.StorageSettings.ReadabilityUserFile, json);
            }
        }
예제 #9
0
 public Request(UserStorage storage, TestContext context, ILogger logger) : base(context, logger)
 {
     this.storage = storage;
 }
예제 #10
0
        static void Main(string[] args)
        {
            var loginPrompt = new Prompt();

            loginPrompt.RegisterCommand(new Command("login", "login your user",
                                                    () =>
            {
                Console.Write("username: "******"password: "******"deposit", "deposit money into your account",
                                                          () =>
                {
                    var account = UserService.HandleAccountChoice(user);
                    Console.Write($"how much would you like to deposit into the account? ");
                    double amount = 0;
                    double.TryParse(Console.ReadLine(), out amount);
                    AccountService.Deposit(account, amount);
                    UserStorage.Write(user);
                    UserService.Display(user);
                }));
                accountPrompt.RegisterCommand(new Command("withdraw", "withdraw money from your account",
                                                          () =>
                {
                    var account = UserService.HandleAccountChoice(user);
                    Console.Write($"how much would you like to withdraw from the account? ");
                    double amount = 0;
                    double.TryParse(Console.ReadLine(), out amount);
                    AccountService.Withdraw(account, amount);
                    UserStorage.Write(user);
                    UserService.Display(user);
                }));
                accountPrompt.RegisterCommand(new Command("transfer", "transfer to another account",
                                                          () =>
                {
                    Console.WriteLine("select account to withdraw from");
                    var withdrawee = UserService.HandleAccountChoice(user);
                    Console.WriteLine("select account to deposit to");
                    var depositee = UserService.HandleAccountChoice(user);
                    Console.Write($"how much would you like to transfer? ");
                    double amount = 0;
                    double.TryParse(Console.ReadLine(), out amount);
                    AccountService.Transfer(withdrawee, depositee, amount);
                    UserStorage.Write(user);
                    UserService.Display(user);
                }));
                accountPrompt.RegisterCommand(new Command("close", "close account",
                                                          () =>
                {
                    Console.WriteLine($"{user.Name}, are you sure you would like to close your accounts?");
                    Console.WriteLine("write out \"yes\" to close your accounts");
                    var response = Console.ReadLine();
                    if (response == "yes")
                    {
                        UserStorage.Delete(user);
                        throw new Exception("exit");
                    }
                }));

                Console.WriteLine($"welcome {user.Name}!");
                accountPrompt.Run();
                Console.WriteLine("logging out");
            }));
            //loginPrompt.RegisterCommand(CreateTestCommand());

            loginPrompt.Run();
            Console.WriteLine("goodbye!");
            Console.ReadLine();
        }
예제 #11
0
 /// <summary>
 /// 退出登录
 /// </summary>
 public void Logout()
 {
     UserStorage.Clear();//直接清除Session
 }
예제 #12
0
 public HomeController(UserStorage userStorage, Config config, ForumStorageReader forumStorageReader, PhotoMetaDataStorage photoMetaDataStorage)
     : base(userStorage, config)
 {
     this.forumStorageReader   = forumStorageReader;
     this.photoMetaDataStorage = photoMetaDataStorage;
 }
예제 #13
0
 /// <summary>
 /// ユーザーを設定します。<para />
 /// NullかString.Emptyが指定されると、ユーザー編集モードに入ります。
 /// </summary>
 internal void SetUser(string screenName)
 {
     if (String.IsNullOrEmpty(screenName))
     {
         User      = null;
         InputMode = true;
         this.Messenger.Raise(new Livet.Messaging.InteractionMessage("FocusToInput"));
     }
     else
     {
         InputMode      = false;
         screenName     = screenName.TrimStart('@', ' ', '\t');
         this.IsStandby = false;
         Task.Factory.StartNew(() =>
         {
             try
             {
                 var user = UserStorage.Lookup(screenName);
                 if (user == null)
                 {
                     var cred = AccountStorage.GetRandom();
                     if (cred != null)
                     {
                         var ud = ApiHelper.ExecApi(() => cred.GetUserByScreenName(screenName));
                         if (ud == null)
                         {
                             DispatcherHelper.BeginInvoke(() => this.Messenger.Raise(new Livet.Messaging.InformationMessage(
                                                                                         "ユーザー @" + screenName + " の情報を取得できません。" + Environment.NewLine +
                                                                                         "ユーザーが存在しない可能性があります。",
                                                                                         "ユーザー情報取得エラー", System.Windows.MessageBoxImage.Warning,
                                                                                         "InformationMessage")));
                             this.User = null;
                             return;
                         }
                         else
                         {
                             user = UserStorage.Get(ud);
                         }
                     }
                 }
                 if (user == null)
                 {
                     throw new Exception("ユーザー情報がありません。");
                 }
                 User = user;
             }
             catch (Exception e)
             {
                 ExceptionStorage.Register(e, ExceptionCategory.TwitterError, "ユーザー @" + screenName + " の情報を取得できませんでした。");
                 DispatcherHelper.BeginInvoke(() => this.Messenger.Raise(new Livet.Messaging.InformationMessage(
                                                                             "ユーザー @" + screenName + "の情報を取得できません。",
                                                                             "ユーザー情報取得エラー", System.Windows.MessageBoxImage.Warning,
                                                                             "InformationMessage")));
                 this.User = null;
             }
             finally
             {
                 IsStandby = true;
             }
         });
     }
 }
예제 #14
0
        private void SetInstapaperUser(User user, string token, string secret, bool saveToDisk)
        {
            LoggedInInstapaperUser = user;
            _instapaperClient.AccessToken = new AccessToken(token, secret);

            if (saveToDisk)
            {
                var storage = new UserStorage<User>(user, token, secret);
                var json = JsonConvert.SerializeObject(storage);
                WriteAllTextAsync(Constants.StorageSettings.InstapaperUserFile, json);
            }
        }
예제 #15
0
 public DevController(UserStorage userStorage, ForumStorageWriter forumStorageWriter, Config config) : base(userStorage, config)
 {
     this.userStorage        = userStorage;
     this.forumStorageWriter = forumStorageWriter;
 }
예제 #16
0
 public DefaultController()
 {
     _userStorage = new UserStorage();
 }
예제 #17
0
 public AccountController(UserStorage userStorage)
 {
     this.userStorage = userStorage;
 }
예제 #18
0
 public RavenController(UserStorage userStorage, Config config)
 {
     this.userStorage = userStorage;
     this.Config      = config;
 }
예제 #19
0
파일: JsonHelper.cs 프로젝트: fbmnds/GitMe
        public static dynamic DeserializeToStorage(string storageType, string storageText)
        {
            JsonObject storageJsonObject;
            JsonArray  storageJsonArray;

            dynamic jsonStore;

            switch (storageType)
            {
            case "Notifications":
                jsonStore = new NotificationStorage();
                break;

            case "Repositories":
                jsonStore = new RepositoryStorage();
                break;

            case "Users":
                jsonStore = new UserStorage();
                break;

            default:
                throw new System.ArgumentException(storageType);
            }

            try
            {
                storageJsonObject = JsonObject.Parse(storageText);
                storageJsonArray  = storageJsonObject[storageType].GetArray();
            }
            catch
            {
                return(jsonStore);
            }

            foreach (JsonValue storageValue in storageJsonArray)
            {
                try
                {
                    dynamic storageItem;

                    switch (storageType)
                    {
                    case "Notifications":
                        storageItem = Serializer.DeserializeToNotification(storageValue.Stringify());
                        storageItem.SubjectTitle = DecodeBase64(storageItem.SubjectTitle);
                        storageItem.Body         = DecodeBase64(storageItem.Body);
                        jsonStore.UpdateOrInsert(storageItem.Id, storageItem);
                        break;

                    case "Repositories":
                        storageItem = Serializer.DeserializeToRepository(storageValue.Stringify());
                        jsonStore.UpdateOrInsert(storageItem.Id, storageItem);
                        break;

                    case "Users":
                        storageItem = Serializer.DeserializeToUser(storageValue.Stringify());
                        jsonStore.UpdateOrInsert(storageItem.Id, storageItem);
                        break;

                    default:
                        throw new System.ArgumentException(storageType);
                    }
                }
                catch
                {
                    throw;
                }
            }
            return(jsonStore);
        }
예제 #20
0
        private static async Task <bool> HandleEventCreated(UserDisciplinaryEventStorage newEvent, UserStorage newUser)
        {
            try
            {
                var newActiveEvent = BuildActiveTimedEvent(newEvent);
                ActiveEvents.Add(newActiveEvent);
                var result = await StorageManager.StoreTimedEventAsync(newEvent, newUser);

                newActiveEvent.DisciplinaryEventId = result.Key;
                newActiveEvent.Reason = newEvent.Reason;

                return(result.Value);
            }
            catch (Exception ex)
            {
                await ExceptionManager.LogExceptionAsync(ex);

                throw;
            }
        }
예제 #21
0
        public static async Task <KeyValuePair <ulong, bool> > StoreTimedEventAsync(UserDisciplinaryEventStorage newEvent, UserStorage newUser)
        {
            try
            {
                using (UserContext db = new UserContext())
                {
                    var findResult = await db.UserStorageTable.FindAsync(newUser.UserID);

                    if (findResult == null)
                    {
                        await db.UserStorageTable.AddAsync(newUser);
                    }

                    var existingDisciplinaryEvent = await db.UserDisciplinaryEventStorageTable.AsQueryable().FirstOrDefaultAsync(x => x.UserID == newUser.UserID && x.DiscipinaryEventType == newEvent.DiscipinaryEventType);

                    if (existingDisciplinaryEvent != null && newEvent.DiscipinaryEventType != DisciplinaryEventEnum.WarnEvent)
                    {
                        existingDisciplinaryEvent = newEvent;
                        await db.SaveChangesAsync();

                        return(new KeyValuePair <ulong, bool>(newEvent.DisciplineEventID, true));
                    }
                    else
                    {
                        await db.UserDisciplinaryEventStorageTable.AddAsync(newEvent);

                        await db.SaveChangesAsync();

                        return(new KeyValuePair <ulong, bool>(newEvent.DisciplineEventID, false));
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.HandleException(ErrMessages.StorageException, ex);
                throw;
            }
        }
예제 #22
0
 public RegistrationController(UserStorage storage, ILogger <RegistrationController> regLogger, LeaderboardStorage leaderboard)
 {
     _users       = storage;
     _logger      = regLogger;
     _leaderboard = leaderboard;
 }
예제 #23
0
        public static async Task <bool> StoreDisciplinaryPermanentEventAsync(UserDisciplinaryPermanentStorage obj, UserStorage user)
        {
            try
            {
                using (UserContext db = new UserContext())
                {
                    if (!await db.UserStorageTable.AsQueryable().AnyAsync(x => x.UserID == user.UserID))
                    {
                        await db.AddAsync(user);
                    }


                    var existingEvent = await db.UserDisciplinaryPermanentStorageTable.AsQueryable().FirstOrDefaultAsync(x => x.UserID == user.UserID);

                    if (existingEvent != null)
                    {
                        existingEvent = obj;
                        await db.SaveChangesAsync();

                        return(true);
                    }
                    else
                    {
                        await db.AddAsync(obj);

                        await db.SaveChangesAsync();

                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.HandleException(ErrMessages.StorageException, ex);
                throw;
            }
        }
예제 #24
0
        public void Can_Have_Default_Users_Present()
        {
            var store = new UserStorage();

            Assert.AreEqual(2, store.Count());
        }
예제 #25
0
        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("ed = {0}, Tom = {1}", "cool", "less cool"));
            //SRP
            Console.WriteLine("SRP");
            UserStorage  s = new UserStorage();
            EmailStorage e = new EmailStorage();

            SRPService main = new SRPService(s, e);

            Console.WriteLine("_________________________________");
            Console.WriteLine("OCP");
            //OCP
            OCPService ocp = new OCPService();

            Console.WriteLine("_________________________________");
            Console.WriteLine("LSP");
            //LSP
            LSPService lsp = new LSPService();

            Console.WriteLine("_________________________________");
            Console.WriteLine("ISP");
            //ISP
            ISPService isp = new ISPService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("DIP");
            //DIP
            DIPService sip = new DIPService();

            Console.WriteLine("_________________________________");
            Console.WriteLine("Law of Demeter");
            //Law of demeter
            Demeter dim = new Demeter();

            Console.WriteLine("_________________________________");
            Console.WriteLine("Factory pattern");
            //factory
            FactoryService factory = new FactoryService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("Adaptor Pattern");
            //Adaptor pattern
            AdaptorService adaptorService = new AdaptorService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("Decorator Pattern");
            //decorator pattern
            DecoratorService decoratorService = new DecoratorService();

            Console.WriteLine("_________________________________");


            Console.WriteLine("Repository Pattern");
            //Repository pattern
            RepositoryService RepositoryService = new RepositoryService();

            Console.WriteLine("_________________________________");


            Console.WriteLine("Tree Traversal");
            //BinaryTree Traversal
            BinaryTreeService BinaryTreeService = new BinaryTreeService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("Number Swap");
            //Number Swap
            NumberSwapService NumberSwapService = new NumberSwapService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("Multiply");
            //Multiply
            MultiplyService MultiplyService = new MultiplyService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("OverflowChecked");
            //OverflowCheckedService
            OverflowCheckedService OverflowChecked = new OverflowCheckedService();

            Console.WriteLine("_________________________________");

            Console.WriteLine("By Ref");
            //pass by reference
            ByRefService ByRefService = new ByRefService();

            Console.WriteLine("_________________________________");

            Console.WriteLine(" EF Code FirstService");
            //EFCodeFirstService
            //EFCodeFirstService EFCodeFirstService = new EFCodeFirstService();
            Console.WriteLine("_________________________________");
            //read
            Console.ReadLine();
        }
예제 #26
0
        public AccountController(IConfiguration Configuration)
        {
            string dbCon = Configuration.GetConnectionString("DefaultConnection");

            userStorage = new UserStorage(dbCon);
        }
예제 #27
0
        public async Task <string> CreateAsync(UserStorage user)
        {
            await _userCollection.InsertOneAsync(user);

            return(user.Id);
        }
예제 #28
0
 public void SetAllUsers(List <User> users)
 {
     _userStorage = new UserStorage(users);
 }
예제 #29
0
 public ParticipantService(UserStorage userStorage, IParticipantService participantService, IGroupService groupService)
 {
     _userStorage        = userStorage;
     _participantService = participantService;
     _groupService       = groupService;
 }
예제 #30
0
 /// <summary>
 /// Asynchronously updates a users password.
 /// </summary>
 /// <param name="user">The user.</param>
 /// <param name="newPassword">The new password.</param>
 /// <returns>The task representing the asynchronous operation.</returns>
 public virtual async Task<IdentityResult> UpdatePassword(TUser user, string newPassword)
 {
     user.PasswordHash = PasswordHasher.HashPassword(newPassword);
     return new IdentityResult(await UserStorage.UpdateAsync(user));
 }
예제 #31
0
        public static void WriteUserStorage(UserStorage userStorage)
        {
            string jsonToWrite = JsonConvert.SerializeObject(userStorage);

            CoreMethod.WriteStringToFile(jsonToWrite, true, CoreMethod.GetFileLocation("UserStorage.json"));
        }
예제 #32
0
 public UserSettingChangesService(UserStorage storage)
 {
     _storage = storage;
 }
        public static async Task ProhibitedWordsHandler(SocketMessage message)
        {
            //Return is sender is a bot
            if (message.Author.IsBot)
            {
                return;
            }

            CultureInfo   culture      = new CultureInfo("en-CA", false);
            List <string> blockedWords = new List <string>();

            bool userWhiteListed  = GetIsUserWhitelisted(message);
            bool sendSwearWarning = false;

            //Prohibited word detection

            //Reads list of prohibited words from file, checks if message contains words
            var prohibitedWords = File.ReadAllLines(CoreMethod.GetFileLocation("ProhibitedWords.txt"));

            foreach (var forbiddenWord in prohibitedWords)
            {
                if (culture.CompareInfo.IndexOf(message.Content, forbiddenWord, CompareOptions.IgnoreCase) >= 0 && message.Author.IsBot != true)
                {
                    blockedWords.Add(forbiddenWord);
                    sendSwearWarning = true;
                }
            }

            //Sends swear warning to user if previous statement detected swear word
            if (sendSwearWarning == true && userWhiteListed == false)
            {
                string userReturnString = string.Join(", ", blockedWords);

                bool sendWarning = false;
                if (!UserTracker.TryGetValue(message.Author.Id, out var selectedUserTracker))
                {
                    //If user does not exist in tracker, add it
                    UserTracker.Add(message.Author.Id, new ProhibitedWordsUserTracker
                    {
                        SentProhibitedWords = blockedWords,
                        SentTime            = DateTime.UtcNow
                    });

                    sendWarning = true;
                }
                //If user has not sent the same words
                else
                {
                    foreach (var badWord in blockedWords)
                    {
                        if (!selectedUserTracker.SentProhibitedWords.Contains(badWord))
                        {
                            sendWarning = true;

                            //Set blocked words to current words
                            UserTracker[message.Author.Id].SentProhibitedWords = blockedWords;
                        }
                    }
                }

                //Send swear warning
                if (sendWarning == true)
                {
                    await message.Channel.SendMessageAsync(message.Author.Mention + " HEY `" + message.Author.Username + "` WATCH IT! THIS IS A F*****G CHRISTIAN F*****G DISCORD SERVER, `" + userReturnString + "` IS NOT ALLOWED HERE");
                }



                //Logs user swear amount to local counter
                //Get user storage
                var userStorage = XmlManager.FromXmlFile <UserStorage>(CoreMethod.GetFileLocation(@"\UserStorage") + @"\" + message.Author.Id + ".xml");

                userStorage.UserInfo[message.Author.Id].UserProhibitedWordsStorage.SwearCount = userStorage.UserInfo[message.Author.Id].UserProhibitedWordsStorage.SwearCount + 1;

                //write new swear count to user profile
                var userRecord = new UserStorage
                {
                    UserInfo = userStorage.UserInfo
                };

                XmlManager.ToXmlFile(userRecord, CoreMethod.GetFileLocation(@"\UserStorage") + @"\" + message.Author.Id + ".xml");
            }
        }
예제 #34
0
 public AccountController(LoginService loginService, UserStorage userStorage, Config config) : base(userStorage, config)
 {
     this.loginService = loginService;
     this.userStorage  = userStorage;
 }
예제 #35
0
 static private async Task DownloadImage(string fileName, string url)
 {
     var uri = new Uri(url);
     var request = WebRequest.CreateHttp(url);
     using (var response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null))
     {
         using (var stream = response.GetResponseStream())
         {
             using (var userStorage = new UserStorage())
             {
                 using (var writer = userStorage.OpenFile(fileName, System.IO.FileMode.Create))
                 {
                     await stream.CopyToAsync(writer);
                     AppLogs.WriteInfo("DownloadImage", url);
                 }
             }
         }
     }
 }