public static async Task <bool> UpdateUserAsync(string login)
        {
            try
            {
                string serverIP   = Properties.Settings.Default.ServerIp;
                int    serverPort = Properties.Settings.Default.ServerPort;
                string urlServer  = "http://" + serverIP + ":" + serverPort;
                var    client     = new RestClient(urlServer);
                client.Authenticator = new HttpBasicAuthenticator(publicApiLogin, publicApiMdp);
                var request  = new RestRequest("users/" + login, Method.GET);
                var response = await client.ExecuteTaskAsync(request);

                if (response.IsSuccessful)
                {
                    var User = JsonUserList.DeserializedJsonAlone(response.Content);
                    if (User != null)
                    {
                        var request2 = new RestRequest("users/" + login, Method.PUT);
                        var ctx      = await RemoteDatabase.GetDbContextAsync();

                        var dbUser = ctx.GrantedUsers.GetByServerId(User.user_id);
                        if (dbUser != null)
                        {
                            request2.AddParameter("login", dbUser.Login);
                            request2.AddParameter("password", dbUser.Password);
                            request2.AddParameter("lname", dbUser.LastName);
                            request2.AddParameter("fname", dbUser.FirstName);
                            request2.AddParameter("badge_num", dbUser.BadgeNumber);
                            var dbFingers = ctx.Fingerprints.Where(fp => fp.GrantedUserId == dbUser.GrantedUserId).ToList();

                            if (dbFingers != null)
                            {
                                foreach (SmartDrawerDatabase.DAL.Fingerprint fp in dbFingers)
                                {
                                    request2.AddParameter("finger_index", fp.Index.ToString());
                                    request2.AddParameter("ftemplate", fp.Template);
                                }
                            }
                            var response2 = await client.ExecuteTaskAsync(request2);

                            return(response2.IsSuccessful);
                        }
                    }
                    return(false);
                }
            }
            catch (Exception error)
            {
                ExceptionMessageBox exp = new ExceptionMessageBox(error, "Error update user");
                exp.ShowDialog();
            }
            return(false);
        }
        public static string SerializedJsonAlone(JsonUserList jsl)
        {
            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();

            return(jsSerializer.Serialize(jsl));
        }
        public static async Task <bool> GetAndStoreUserAsync()
        {
            try
            {
                string serverIP   = Properties.Settings.Default.ServerIp;
                int    serverPort = Properties.Settings.Default.ServerPort;

                //serverIP = "157.230.97.196";
                //serverPort = 3000;

                string urlServer = "http://" + serverIP + ":" + serverPort;
                var    client    = new RestClient(urlServer);
                client.Authenticator = new HttpBasicAuthenticator(publicApiLogin, publicApiMdp);
                var request = new RestRequest("/users", Method.GET);
                client.Timeout           = timeout;
                client.ReadWriteTimeout  = timeout;
                request.Timeout          = timeout;
                request.ReadWriteTimeout = timeout;

                var response = await client.ExecuteTaskAsync(request);

                if (response.IsSuccessful)
                {
                    // remove  granted standard users
                    var ctx = await RemoteDatabase.GetDbContextAsync();

                    /* ctx.GrantedAccesses.Clear();
                    *  await ctx.SaveChangesAsync();*/

                    //get device
                    Device mydev = ctx.Devices.GetBySerialNumber(Properties.Settings.Default.WallSerial);

                    if (mydev == null)
                    {
                        return(false);
                    }

                    var lstUser = JsonUserList.DeserializedJsonList(response.Content);
                    if ((lstUser != null) && (lstUser.Length > 0))
                    {
                        foreach (JsonUserList jsl in lstUser)
                        {
                            var original  = ctx.GrantedUsers.GetByServerId(jsl.user_id);
                            var original2 = ctx.GrantedUsers.GetByLogin(jsl.login);
                            if ((original != null) && (original.Login != "Admin"))
                            {
                                TimeSpan ts = jsl.updated_at - original.UpdateAt;
                                if (Math.Abs(ts.TotalSeconds) > 1)  // Not the latest but avoid ms
                                {
                                    original.ServerGrantedUserId = jsl.user_id;
                                    original.Login            = jsl.login;
                                    original.Password         = jsl.password;
                                    original.FirstName        = jsl.fname;
                                    original.LastName         = jsl.lname;
                                    original.BadgeNumber      = string.IsNullOrEmpty(jsl.badge_num) ? "000000" : jsl.badge_num;
                                    original.UserRankId       = 3;
                                    original.UpdateAt         = jsl.updated_at;
                                    ctx.Entry(original).State = EntityState.Modified;
                                    await ctx.SaveChangesAsync();

                                    //deletefingerprint for this user if exists

                                    var fpUser = ctx.Fingerprints.Where(gu => gu.GrantedUserId == original.GrantedUserId).ToList();
                                    if ((fpUser != null) && (fpUser.Count > 0))
                                    {
                                        foreach (SmartDrawerDatabase.DAL.Fingerprint fp in fpUser)
                                        {
                                            ctx.Fingerprints.Remove(fp);
                                        }
                                        await ctx.SaveChangesAsync();
                                    }

                                    if ((jsl.ftemplate != null) & (jsl.ftemplate.Count > 0))
                                    {
                                        for (int loop = 0; loop < jsl.ftemplate.Count; loop++)
                                        {
                                            if (!string.IsNullOrEmpty(jsl.ftemplate[loop]) && !string.IsNullOrEmpty(jsl.finger_index[loop]))
                                            {
                                                ctx.Fingerprints.Add(new SmartDrawerDatabase.DAL.Fingerprint
                                                {
                                                    GrantedUserId = original.GrantedUserId,
                                                    Index         = Convert.ToInt32(jsl.finger_index[loop]),
                                                    Template      = jsl.ftemplate[loop],
                                                });
                                            }
                                        }
                                        await ctx.SaveChangesAsync();
                                    }
                                    ctx.GrantedAccesses.AddOrUpdateAccess(original, mydev, ctx.GrantTypes.All());
                                    await ctx.SaveChangesAsync();
                                }
                            }
                            else if (original2 != null)
                            {
                                TimeSpan ts = jsl.updated_at - original2.UpdateAt;
                                if (Math.Abs(ts.TotalSeconds) > 1)  // Not the latest but avoid ms
                                {
                                    original2.ServerGrantedUserId = jsl.user_id;
                                    original2.Login            = jsl.login;
                                    original2.Password         = jsl.password;
                                    original2.FirstName        = jsl.fname;
                                    original2.LastName         = jsl.lname;
                                    original2.BadgeNumber      = string.IsNullOrEmpty(jsl.badge_num) ? "000000" : jsl.badge_num;
                                    original2.UserRankId       = 3;
                                    original2.UpdateAt         = jsl.updated_at;
                                    ctx.Entry(original2).State = EntityState.Modified;
                                    await ctx.SaveChangesAsync();

                                    //deletefingerprint for this user if exists

                                    var fpUser = ctx.Fingerprints.Where(gu => gu.GrantedUserId == original2.GrantedUserId).ToList();
                                    if ((fpUser != null) && (fpUser.Count > 0))
                                    {
                                        foreach (SmartDrawerDatabase.DAL.Fingerprint fp in fpUser)
                                        {
                                            ctx.Fingerprints.Remove(fp);
                                        }
                                        await ctx.SaveChangesAsync();
                                    }

                                    if ((jsl.ftemplate != null) & (jsl.ftemplate.Count > 0))
                                    {
                                        for (int loop = 0; loop < jsl.ftemplate.Count; loop++)
                                        {
                                            if (!string.IsNullOrEmpty(jsl.ftemplate[loop]) && !string.IsNullOrEmpty(jsl.finger_index[loop]))
                                            {
                                                ctx.Fingerprints.Add(new SmartDrawerDatabase.DAL.Fingerprint
                                                {
                                                    GrantedUserId = original2.GrantedUserId,
                                                    Index         = Convert.ToInt32(jsl.finger_index[loop]),
                                                    Template      = jsl.ftemplate[loop],
                                                });
                                            }
                                        }
                                        await ctx.SaveChangesAsync();
                                    }
                                    ctx.GrantedAccesses.AddOrUpdateAccess(original2, mydev, ctx.GrantTypes.All());
                                    await ctx.SaveChangesAsync();
                                }
                            }
                            else if ((original == null) && (original2 == null))
                            {
                                GrantedUser newUser = new GrantedUser()
                                {
                                    ServerGrantedUserId = jsl.user_id,
                                    Login       = jsl.login,
                                    Password    = jsl.password,
                                    FirstName   = jsl.fname,
                                    LastName    = jsl.lname,
                                    BadgeNumber = string.IsNullOrEmpty(jsl.badge_num) ? "000000" : jsl.badge_num,
                                    UpdateAt    = jsl.updated_at,
                                    UserRankId  = 3,
                                };
                                ctx.GrantedUsers.Add(newUser);
                                await ctx.SaveChangesAsync();

                                if ((jsl.ftemplate != null) & (jsl.ftemplate.Count > 0))
                                {
                                    for (int loop = 0; loop < jsl.ftemplate.Count; loop++)
                                    {
                                        if (!string.IsNullOrEmpty(jsl.ftemplate[loop]) && !string.IsNullOrEmpty(jsl.finger_index[loop]))
                                        {
                                            ctx.Fingerprints.Add(new SmartDrawerDatabase.DAL.Fingerprint
                                            {
                                                GrantedUserId = newUser.GrantedUserId,
                                                Index         = Convert.ToInt32(jsl.finger_index[loop]),
                                                Template      = jsl.ftemplate[loop],
                                            });
                                        }
                                    }
                                    await ctx.SaveChangesAsync();
                                }
                                ctx.GrantedAccesses.AddOrUpdateAccess(newUser, mydev, ctx.GrantTypes.All());
                                await ctx.SaveChangesAsync();
                            }
                        }
                        ctx.Database.Connection.Close();
                        ctx.Dispose();
                        return(true);
                    }
                    return(true);
                }
                return(false);
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                      eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                          ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }
            catch (Exception error)
            {
                ExceptionMessageBox exp = new ExceptionMessageBox(error, "Error getting user");
                exp.ShowDialog();
                return(false);
            }
        }