示例#1
0
        public void LoadAll(string fileUsers = "users.json", string fileOrders = "orders.json", string fileDrinks = "drinks.json")
        {
            if (File.Exists(fileDrinks))
            {
                List <JsonDrink> jsonDrinks = JsonConvert.DeserializeObject <List <JsonDrink> >(ReadFromFile(fileDrinks));
                this.drinks = new Dictionary <string, Drink>();
                foreach (var drink in jsonDrinks)
                {
                    this.drinks[drink.Name] = JsonDrink.importJsonDrink(drink, this);
                }
            }

            if (File.Exists(fileUsers))
            {
                List <JsonUser> jsonUsers = JsonConvert.DeserializeObject <List <JsonUser> >(ReadFromFile(fileUsers));
                this.users = new Dictionary <string, User>();
                foreach (var user in jsonUsers)
                {
                    this.users[user.Name] = JsonUser.importJsonUser(user, this);
                }
            }

            if (File.Exists(fileOrders))
            {
                List <JsonOrder> jsonOrders = JsonConvert.DeserializeObject <List <JsonOrder> >(ReadFromFile(fileOrders));
                this.orders = new List <Order>();
                foreach (var order in jsonOrders)
                {
                    this.orders.Add(JsonOrder.importJsonOrder(order, this));
                }
            }
        }
        public bool UpdateUser(JsonUser jsonFile)
        {
            var Items = new List <JsonUser>();

            using (StreamReader r = new StreamReader(_server.MapPath(jsonUserServerPath)))
            {
                string json = r.ReadToEnd();
                JavaScriptSerializer jss = new JavaScriptSerializer();
                Items = jss.Deserialize <List <JsonUser> >(json);

                var item = Items.Where(x => x.Id == jsonFile.Id).FirstOrDefault();

                item.Active     = jsonFile.Active;
                item.Name       = jsonFile.Name;
                item.Email      = jsonFile.Email;
                item.Role       = jsonFile.Role;
                item.Chargeable = jsonFile.Chargeable;

                item.ProjectId        = jsonFile.ProjectId;
                item.IterationPathTFS = jsonFile.Project.IterationPathTFS;
                item.ProjectNameTFS   = jsonFile.Project.ProjectNameTFS;
                item.TeamDivision     = jsonFile.Project.TeamDivision.Where(x => x.Id.ToString() == jsonFile.TeamDivision).FirstOrDefault().Division;

                item.Access = jsonFile.Access;
                item.Rate   = ReturnRateByRole(jsonFile.Role);

                Items[Items.FindIndex(ind => ind.Id == jsonFile.Id)] = item;
            }

            return(WriteJsonUserFile(Items));
        }
示例#3
0
 public async Task UserSetUsergroup(JsonUser user, JsonUserGroup userGroup)
 {
     await RestClient.UniFiPut($"api/s/{Site}/rest/user/{user._id}", new
     {
         usergroup_id = userGroup?._id ?? string.Empty
     });
 }
        /// <summary>
        /// Returns the user with the given ID.
        /// </summary>
        /// <param name="userID">the ID of the user</param>
        /// <returns>the user if found; otherwise a NotFoundExeption is thrown</returns>
        public static User GetUser(string userID)
        {
            if (userID == null || userID == "")
            {
                throw new ArgumentNullException();
            }

            try
            {
                string   jsonString = WebClient.DownloadString("users/" + userID);
                JsonUser jsonUser   = JsonConvert.DeserializeObject <JsonUser>(jsonString);
                return(new User(jsonUser));
            }
            catch (WebException e)
            {
                switch (e.HResult)
                {
                // User not found
                case -2146233079:
                    throw new NotFoundException("User");

                // Unknown exception
                default:
                    throw;
                }
            }
        }
示例#5
0
 public async Task UserUnsetUsergroup(JsonUser user)
 {
     await RestClient.UniFiPut($"api/s/{Site}/rest/user/{user._id}", new
     {
         usergroup_id = string.Empty
     });
 }
示例#6
0
        public async Task <bool> SignUp(Models.UserModel user)
        {
            try {
                // Create uri for server endpoint
                Uri functionUri = new Uri(Server.BaseUri + Server.SignUpEndpoint);
                //Uri functionUri = new Uri(baseUri, Server.SignUpEndpoint);

                // Create json object for user
                JsonUser jsonUser = new JsonUser(user);

                // serialize object to json
                string json = JsonConvert.SerializeObject(jsonUser);

                // do post get response
                HttpResponseMessage response = await PostAsync(functionUri, json);

                if (!response.IsSuccessStatusCode)
                {
                    string content = await response.Content.ReadAsStringAsync();

                    JsonError jsonError = JsonConvert.DeserializeObject <JsonError>(content);

                    //throw new HttpException(jsonError.Code, jsonError.Status, jsonError.Message);
                    // throw new Exception();
                }

                return(true);
            } catch (Exception e) {
                Debug.WriteLine(e);
                return(false);
            }
        }
示例#7
0
        public static async Task <HttpStatusCode> EditUser(string id, JsonUser user)
        {
            var token = await AppToken();

            if (token == null)
            {
                return(HttpStatusCode.Forbidden);
            }

            var client = new RestClient(RaceDayConfiguration.Instance.APIUrl);

            client.AddHeader("Authorization", $"Bearer {token}");

            await client.SimpleApi($"{COMMAND_MFUSER}/{id}", "PUT", user);

            if (client.StatusCode == HttpStatusCode.Unauthorized)
            {
                token = await Authorize();

                if (token != null)
                {
                    client.ClearHeaders();
                    client.AddHeader("Authorization", $"Bearer {token}");
                    await client.SimpleApi($"{COMMAND_MFUSER}/{id}", "PUT", user);
                }
            }
            return(client.StatusCode);
        }
示例#8
0
        public virtual async Task <IHttpActionResult> SaveAsync(User user, bool isNew)
        {
            if (isNew)
            {
                // PasswordHash must contains user password NOT hash.
                //user.Email = user.Email ?? string.Format("{0}@{0}.{0}", user.UserName);
                IdentityResult result = await UserManager.CreateAsync(user, user.PasswordHash);

                if (!result.Succeeded)
                {
                    return(GetErrorResult(result));
                }
            }
            else
            {
                var currentUser = Db.Users.Include(u => u.Employees).First(x => x.Id == user.Id);
                currentUser.UserName = user.UserName;
                currentUser.Email    = user.Email;
                if (user.PasswordHash != null)
                {
                    currentUser.PasswordHash = UserManager.PasswordHasher.HashPassword(user.PasswordHash);
                }
                await Db.SaveChangesAsync();

                user = currentUser;
            }
            return(Ok(JsonUser.Create(user)));
        }
示例#9
0
 /// <summary>
 /// Display the levels the user has unlocked.
 /// </summary>
 private void DisplayUserSpecificLevels(JsonUser user)
 {
     for (int i = 0; i < user.Levels.Length; i++)
     {
         DisplayLevel(user.Levels[i].LevelName, user.Levels[i].LevelTitle);
     }
 }
示例#10
0
        public ActionResult SumbitLogon(VOUser user)
        {
            if (string.IsNullOrEmpty(user.UserName) || string.IsNullOrEmpty(user.Password))
            {
                return(RedirectToAction("Logon", "LogonForm", new { message = "登录名,密码不能为空!" }));
            }

            JsonUser jsonUser = UserService.CheckUserPassword(user.UserName, user.Password);

            CookieUtils.AddCookie("LogonID", user.UserName, System.Web.HttpContext.Current);

            if (user.RememberMe)
            {
                HttpCookie cookie = CookieUtils.GetCookie(System.Web.HttpContext.Current, "LogonID");
                cookie.Expires = DateTime.Now.AddDays(7);
            }
            GlobalVariables.CurrentUser = jsonUser;

            if (jsonUser == null)
            {
                return(RedirectToAction("Logon", "LogonForm", new { message = "用户名,密码验证失败!" }));
            }

            return(RedirectToAction("Index", "ParticipateConsultation"));
        }
示例#11
0
 public UserModel(JsonUser jsonUser)
 {
     Id        = jsonUser.Id;
     Firstname = jsonUser.FirstName;
     Lastname  = jsonUser.LastName;
     Email     = jsonUser.Email;
     Password  = jsonUser.Password;
 }
    static void Main(string[] args)
    {
        dynamic userDynamic = new JsonUser();

        Console.WriteLine(IsPropertyExist(() => userDynamic.first_name));
        Console.WriteLine(IsPropertyExist(() => userDynamic.address));
        Console.WriteLine(IsPropertyExist(() => userDynamic.last_name));
    }
示例#13
0
 /// <summary>
 /// Constructs a User from the provided Json object.
 /// </summary>
 /// <param name="jsonUser">Json object containing information related to a User</param>
 public User(JsonUser jsonUser)
 {
     ID          = jsonUser.ID;
     DisplayName = jsonUser.DisplayName;
     Email       = jsonUser.Email;
     Created     = jsonUser.Created;
     Modified    = jsonUser.Modified;
     Notebooks   = new List <Notebook>();
 }
示例#14
0
 public static void Update(int userId)
 {
     var user = new JsonUser()
     {
         Name = "testUpdate"
     };
     var client   = new HttpClient();
     var response = client.PutAsJsonAsync($"{baseUrl}api/clients/update/{userId}", user);
 }
示例#15
0
        /**
         * Method that finds the username for a given user ID.
         * @param token - The token for the app.
         * @param userId - The ID to find the username for.
         * @return Task<string> The username.
         */
        public static async Task <string> UserIdToName(string token, string userId)
        {
            JsonUser user = await new GetUser(token, userId).Get();

            if (user == null || !user.Ok)
            {
                return("");
            }
            return(user.User.Name);
        }
示例#16
0
            internal bool UpdateUser(JsonUser jsonUser)
            {
                if (_userMap.TryGetValue(jsonUser.Id, out User user))
                {
                    user.UpdateFromRestUser(jsonUser);
                    return(true);
                }

                return(false);
            }
示例#17
0
        public JsonMessage Map(Message message)
        {
            var pathToProfilePhotos = Path.Combine(_environment.ContentRootPath, _photoOptions.Value.UsersPhotosPath);

            var senderJson = new JsonUser(message.Sender.UserName,
                                          Path.Combine(pathToProfilePhotos, message.Sender.ProfilePhotoName));
            var receiverJson = new JsonUser(message.Receiver.UserName,
                                            Path.Combine(pathToProfilePhotos, message.Receiver.ProfilePhotoName));

            return(new JsonMessage(receiver: receiverJson, sender: senderJson, text: message.Text, sendDate: message.SendDate));
        }
示例#18
0
        internal override void UpdateFromRestUser(JsonUser jsonUser)
        {
            base.UpdateFromRestUser(jsonUser);

            Email          = jsonUser.Email ?? Email;
            Phone          = jsonUser.Phone ?? Phone;
            Verified       = jsonUser.Verified ?? Verified;
            MfaEnabled     = jsonUser.MfaEnabled ?? MfaEnabled;
            NSFWAllowed    = jsonUser.NSFWAllowed ?? NSFWAllowed;
            PurchasedFlags = jsonUser.PurchasedFlags ?? PurchasedFlags;
            Locale         = jsonUser.Locale ?? Locale;
        }
示例#19
0
 public static void Add()
 {
     var user = new JsonUser()
     {
         Name    = "testFromClient",
         SurName = "rasdasdqwe",
         Balance = 2000,
         Phone   = "800000000000"
     };
     var client   = new HttpClient();
     var response = client.PostAsJsonAsync($"{baseUrl}api/clients/add/", user);
 }
示例#20
0
            internal User GetOrAddUser(JsonUser jsonUser)
            {
                if (_userMap.TryGetValue(jsonUser.Id, out User? user))
                {
                    return(user);
                }

                AddUser(jsonUser);
                user = GetUser(jsonUser.Id);
                Guard.IsNotNull(user, nameof(user));
                return(user);
            }
示例#21
0
 private TEntity PrepareResultEntity<TEntity>(object p)
 {
     var u = p as User;
     if (u != null)
     {
         var jsonUser = JsonUser.Create(u);
         if (typeof (TEntity) == typeof (JsonUser))
             p = jsonUser;
         else
             p = jsonUser.ToUser();
     }
     return (TEntity)p;
 }
示例#22
0
        internal SelfUser(JsonUser restUser, QuarrelClient context) :
            base(restUser, context)
        {
            Guard.IsNotNull(restUser.PurchasedFlags, nameof(restUser.PurchasedFlags));

            Email          = restUser.Email;
            Phone          = restUser.Phone;
            Verified       = restUser.Verified;
            MfaEnabled     = restUser.MfaEnabled;
            NSFWAllowed    = restUser.NSFWAllowed;
            PurchasedFlags = restUser.PurchasedFlags.Value;
            Locale         = restUser.Locale;
        }
        public static EventParticipant FromJson(JsonUser user)
        {
            EventParticipant p = new EventParticipant()
            {
                UserId    = user.UserId,
                FirstName = user.FirstName,
                LastName  = user.LastName,
                FullName  = user.Name,
                Image     = string.Empty,
            };

            return(p);
        }
示例#24
0
        internal override JsonUser ToRestUser()
        {
            JsonUser restUser = base.ToRestUser();

            restUser.Email          = Email;
            restUser.Phone          = Phone;
            restUser.Verified       = Verified;
            restUser.MfaEnabled     = MfaEnabled;
            restUser.NSFWAllowed    = NSFWAllowed;
            restUser.PurchasedFlags = PurchasedFlags;
            restUser.Locale         = Locale;
            return(restUser);
        }
 private void OnUpdatePageCommand(object obj)
 {
     if (obj.ToString() == "Home")
     {
         IsHomePageVisible       = true;
         IsHistoryPageVisible    = false;
         IsChangeCurrencyVisible = false;
     }
     else if (obj.ToString() == "History")
     {
         HistoryUsers = new ObservableCollection <UserModel>();
         TotalValue   = 0;
         ObservableCollection <UserModel> users = new ObservableCollection <UserModel>();
         IsHistoryPageVisible    = true;
         IsHomePageVisible       = false;
         IsChangeCurrencyVisible = false;
         ObservableCollection <UserModel> historyUsers = Task.Run(() => JsonUser.GetHistoryUsers()).Result;
         if (HistoryUsers == historyUsers)
         {
             return;
         }
         foreach (var item in historyUsers)
         {
             HistoryUsers.Add(item);
         }
         if (HistoryUsers.Any(x => x.EndTime.Day != DateTime.Now.Day))
         {
             var removeUsers = HistoryUsers.Where(x => x.EndTime.Day != DateTime.Now.Day).ToArray();
             foreach (var item in removeUsers)
             {
                 HistoryUsers.Remove(item);
                 NotifyPropertyChanged(nameof(HistoryUsers));
             }
             JsonUser.AddCollectionToHistory(HistoryUsers);
         }
         foreach (var item in HistoryUsers)
         {
             TotalValue += item.Cash;
         }
         NotifyPropertyChanged(nameof(HistoryUsers));
         NotifyPropertyChanged(nameof(TotalValue));
     }
     else if (obj.ToString() == "ChangeCurrency")
     {
         IsChangeCurrencyVisible = true;
         IsHistoryPageVisible    = false;
         IsHomePageVisible       = false;
     }
 }
示例#26
0
        internal virtual void UpdateFromRestUser(JsonUser jsonUser)
        {
            Guard.IsEqualTo(Id, jsonUser.Id, nameof(Id));

            Username      = jsonUser.Username;
            Discriminator = int.Parse(jsonUser.Discriminator);
            Avatar        = jsonUser.Avatar ?? Avatar;
            Bio           = jsonUser.Bio ?? Bio;
            Banner        = jsonUser.Banner ?? Banner;
            BannerColor   = jsonUser.BannerColor ?? BannerColor;
            AccentColor   = jsonUser.AccentColor ?? AccentColor;
            Bot           = jsonUser.Bot ?? Bot;
            Flags         = jsonUser.Flags ?? Flags;
            PublicFlags   = jsonUser.PublicFlags ?? PublicFlags;
        }
示例#27
0
 internal User(JsonUser restUser, QuarrelClient context) :
     base(context)
 {
     Id            = restUser.Id;
     Username      = restUser.Username;
     Discriminator = int.Parse(restUser.Discriminator);
     Avatar        = restUser.Avatar;
     Bio           = restUser.Bio;
     Banner        = restUser.Banner;
     BannerColor   = restUser.BannerColor;
     AccentColor   = restUser.AccentColor;
     Bot           = restUser.Bot;
     Flags         = restUser.Flags;
     PublicFlags   = restUser.PublicFlags;
 }
示例#28
0
        /// <summary>
        /// Function to determine what level data to display.
        /// It is called whenever the level select UI panel is opened
        /// </summary>
        public void DisplayLevels()
        {
            DestroyLevelPrefabs();
            JsonUser user = GetUser(StaticLevel.username);

            if (user != null)
            {
                //Display unlocked levels
                DisplayUserSpecificLevels(user);
            }
            else
            {
                //Display all levels
                DisplayDefaultLevels();
            }
        }
示例#29
0
        public static User ParseUserFromJson(JsonUser jsonUser)
        {
            if (jsonUser == null)
            {
                return(null);
            }

            User user = new User
            {
                Id     = jsonUser.UserId,
                Level  = jsonUser.UserLevel,
                Gold   = jsonUser.Gold,
                Energy = jsonUser.Energy
            };

            return(user);
        }
示例#30
0
        public static async Task <HttpStatusCode> UserCreate(string name, string firstName, string lastName, string email, string password)
        {
            var token = await AppToken();

            if (token == null)
            {
                return(HttpStatusCode.Forbidden);
            }

            // Create input
            //
            var newUser = new JsonUser
            {
                FirstName = firstName,
                LastName  = lastName,
                Name      = name,
                Email     = email,
                Password  = password,
                UserId    = string.Empty
            };

            // Post to REST client and get response
            //
            var client = new RestClient(RaceDayConfiguration.Instance.APIUrl);

            client.AddHeader("Authorization", $"Bearer {token}");
            var userResult = await client.PostApi <string>(COMMAND_MFUSER, newUser, HttpStatusCode.Created);

            if (client.StatusCode == HttpStatusCode.Unauthorized)
            {
                token = await Authorize();

                if (token != null)
                {
                    client.ClearHeaders();
                    client.AddHeader("Authorization", $"Bearer {token}");
                    userResult = await client.PostApi <string>(COMMAND_MFUSER, newUser, HttpStatusCode.Created);
                }
            }

            return(client.StatusCode);
        }