public async static void Reload() { if (_deviceEntity == null) { _deviceEntity = DevicesHandler.GetDeviceEntity(); if (_deviceEntity == null) { return; } } try { var ctx = await RemoteDatabase.GetDbContextAsync(); // Get all users who have accesses on this device, and Administrators. Include Fingerprints to the request, as they're needed by FPReaderHandle. //Cache = ctx.GrantedUsers.Where(gu => gu.GrantedAccesses.Any(ga => ga.DeviceId == _deviceEntity.DeviceId) || gu.UserRank.Rank == UserRank.Administrator).Include(gu => gu.Fingerprints).ToList(); Cache = ctx.GrantedUsers.Include(gu => gu.Fingerprints).ToList(); ctx.Database.Connection.Close(); ctx.Dispose(); } catch (Exception error) { ExceptionMessageBox exp = new ExceptionMessageBox(error, "Unable to get data from local DB [Users Cache]"); exp.ShowDialog(); } }
async void PopulateDevice() { try { var ctx = await RemoteDatabase.GetDbContextAsync(); var lstDev = ctx.Devices.ToList(); EditedDevice = new Device(); DataDevice.Clear(); foreach (var dv in lstDev) { DataDevice.Add(dv); } ctx.Database.Connection.Close(); ctx.Dispose(); } catch (Exception error) { await mainview0.Dispatcher.BeginInvoke(new System.Action(() => { ExceptionMessageBox exp = new ExceptionMessageBox(error, "Error in Populate Device"); exp.ShowDialog(); })); } }
public static async Task <SmartDrawerDatabase.DAL.Device> GetDeviceEntityAsync() { if (_deviceEntity != null) { return(_deviceEntity); } if ((Device == null) || string.IsNullOrWhiteSpace(Device.SerialNumber)) { return(null); } try { var ctx = await RemoteDatabase.GetDbContextAsync(); _deviceEntity = ctx.Devices .Where(d => d.RfidSerial == Device.SerialNumber) .Include(d => d.DeviceType) .FirstOrDefault(); ctx.Database.Connection.Close(); ctx.Dispose(); return(_deviceEntity); } catch (Exception error) { ///Trace.TraceError("{0} Unable to get data from local DB [Device].", DateTime.Now.ToString("g")); //return null; ExceptionMessageBox exp = new ExceptionMessageBox(error, "GetDeviceEntityAsync"); exp.ShowDialog(); return(null); } }
private async void RemoveGrantDevice() { if ((SelectedDeviceGranted != null) && (SelectedGrantedUser != null)) { try { var ctx = await RemoteDatabase.GetDbContextAsync(); var user = ctx.GrantedUsers.Find(SelectedGrantedUser.Id); if (user != null) { ctx.GrantedAccesses.RemoveAccess(user, SelectedDeviceGranted); await ctx.SaveChangesAsync(); ctx.Database.Connection.Close(); ctx.Dispose(); } } catch (Exception error) { await mainview0.Dispatcher.BeginInvoke(new System.Action(() => { ExceptionMessageBox exp = new ExceptionMessageBox(error, "Error in remove access"); })); } } PopulateDeviceGranted(); }
public async Task <string> PullItem(Stream streamdata) { try { StreamReader reader = new StreamReader(streamdata); string res = reader.ReadToEnd(); reader.Close(); reader.Dispose(); JsonItemToPull jitp = JsonConvert.DeserializeObject <JsonItemToPull>(res); if (jitp != null) { var ctx = await RemoteDatabase.GetDbContextAsync(); var currentpullItem = ctx.PullItems.GetByServerId(jitp.ServerPullItemId); if (currentpullItem != null) { ctx.PullItems.Remove(currentpullItem); await ctx.SaveChangesAsync(); } var user = ctx.GrantedUsers.GetByServerId(jitp.userId); var pullItemToAdd = new SmartDrawerDatabase.DAL.PullItem { ServerPullItemId = jitp.ServerPullItemId, PullItemDate = jitp.pullItemDate, Description = string.IsNullOrEmpty(jitp.description) ? " " : jitp.description, GrantedUser = user, TotalToPull = jitp.listOfTagToPull.Length, }; ctx.PullItems.Add(pullItemToAdd); foreach (string uid in jitp.listOfTagToPull) { RfidTag tag = ctx.RfidTags.AddIfNotExisting(uid); ctx.PullItemsDetails.Add(new PullItemDetail { PullItem = pullItemToAdd, RfidTag = tag, }); } await ctx.SaveChangesAsync(); ctx.Database.Connection.Close(); ctx.Dispose(); if (MyHostEvent != null) { MyHostEvent(this, new MyHostEventArgs("PullItemsRequest", null)); } return("Success : " + pullItemToAdd.ServerPullItemId); } return("Error : Bad Parameters"); } catch (Exception exp) { return("Exception : " + exp.InnerException + "-" + exp.Message); } }
private async void SaveDevice() { if (EditedDevice != null) { var ctx = await RemoteDatabase.GetDbContextAsync(); if (SelectedDevice != null) //Update existing { if (string.IsNullOrEmpty(EditedDevice.DeviceName) || string.IsNullOrEmpty(EditedDevice.DeviceSerial)) { await mainview0.ShowMessageAsync("INFORMATION", "Please Fill device Name and RFID Serial before saving"); return; } else { var original = ctx.Devices.Find(SelectedDevice.DeviceId); if (original != null) { original.DeviceName = EditedDevice.DeviceName; original.DeviceSerial = EditedDevice.DeviceSerial; original.RfidSerial = EditedDevice.RfidSerial; original.IpAddress = EditedDevice.IpAddress; ctx.Entry(original).State = EntityState.Modified; ctx.SaveChanges(); } } } else //save new { if (string.IsNullOrEmpty(EditedDevice.DeviceName) || string.IsNullOrEmpty(EditedDevice.RfidSerial)) { await mainview0.ShowMessageAsync("INFORMATION", "Please Fill device Name and RFID Serial before saving"); return; } else { ctx.Devices.Add(new Device { DeviceTypeId = 15, DeviceName = EditedDevice.DeviceName, DeviceSerial = EditedDevice.DeviceSerial, RfidSerial = EditedDevice.RfidSerial, IpAddress = EditedDevice.IpAddress }); ctx.SaveChanges(); } } ctx.Database.Connection.Close(); ctx.Dispose(); PopulateDevice(); } }
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 async Task <string> AddOrUpdateUserFingerprint(Stream streamdata) { try { StreamReader reader = new StreamReader(streamdata); string res = reader.ReadToEnd(); reader.Close(); reader.Dispose(); JsonUserFingerprint juf = JsonConvert.DeserializeObject <JsonUserFingerprint>(res); if (juf != null) { var ctx = await RemoteDatabase.GetDbContextAsync(); var user = ctx.GrantedUsers.GetByServerId(juf.GrantedUserId); if (user != null) //user Exist { var fingerprint = ctx.Fingerprints.FirstOrDefault(fp => fp.Index == juf.Index && fp.GrantedUserId == user.GrantedUserId); if (fingerprint != null) { ctx.Fingerprints.Remove(fingerprint); } ctx.Fingerprints.Add(new SmartDrawerDatabase.DAL.Fingerprint { Index = juf.Index, GrantedUserId = user.GrantedUserId, Template = juf.Template }); await ctx.SaveChangesAsync(); ctx.Database.Connection.Close(); ctx.Dispose(); MyHostEvent(this, new MyHostEventArgs("UpdateUserInfoList", null)); return("Success : " + user.GrantedUserId); } else //create { return("Failed : " + juf.GrantedUserId); } } return("Error : Bad Parameters"); } catch (Exception exp) { return("Exception : " + exp.InnerException + "-" + exp.Message); } }
private async void DeleteUser() { if (SelectedUser != null) //Update existing { var ctx = await RemoteDatabase.GetDbContextAsync(); var original = ctx.GrantedUsers.Find(SelectedUser.Id); if (original != null) { ctx.GrantedUsers.Remove(original); } ctx.SaveChanges(); ctx.Database.Connection.Close(); ctx.Dispose(); PopulateUser(); } }
private async void PopulateDeviceGranted() { try { DataDeviceAvailable.Clear(); DataDeviceGranted.Clear(); if (SelectedGrantedUser != null) { var ctx = await RemoteDatabase.GetDbContextAsync(); var user = ctx.GrantedUsers.Find(SelectedGrantedUser.Id); if (user != null) { var lstDev = ctx.GrantedAccesses.GetByUser(user); foreach (var dv in lstDev) { DataDeviceGranted.Add(dv.Device); } foreach (var dv in DataDevice) { if (DataDeviceGranted.Where(d => d.DeviceId == dv.DeviceId).FirstOrDefault() == null) { DataDeviceAvailable.Add(dv); } } } ctx.Database.Connection.Close(); ctx.Dispose(); } } catch (Exception error) { await mainview0.Dispatcher.BeginInvoke(new System.Action(() => { ExceptionMessageBox exp = new ExceptionMessageBox(error, "Error in Populate Device"); exp.ShowDialog(); })); } }
public async Task <string> RemoveUser(Stream streamdata) { try { StreamReader reader = new StreamReader(streamdata); string res = reader.ReadToEnd(); int IdToRemove; reader.Close(); reader.Dispose(); if (int.TryParse(res, out IdToRemove)) { var ctx = await RemoteDatabase.GetDbContextAsync(); var user = ctx.GrantedUsers.GetByServerId(IdToRemove); if (user != null) { ctx.GrantedUsers.Remove(user); await ctx.SaveChangesAsync(); ctx.Database.Connection.Close(); ctx.Dispose(); if (MyHostEvent != null) { MyHostEvent(this, new MyHostEventArgs("UpdateUserInfoList", null)); } return("Success : " + IdToRemove); } else { ctx.Database.Connection.Close(); ctx.Dispose(); return("Failed : " + IdToRemove); } } return("Error : Bad Parameters"); } catch (Exception exp) { return("Exception : " + exp.InnerException + "-" + exp.Message); } }
public async Task <string> RemoveUserByLogin(Stream streamdata) { try { StreamReader reader = new StreamReader(streamdata); string Login = reader.ReadToEnd(); reader.Close(); reader.Dispose(); var ctx = await RemoteDatabase.GetDbContextAsync(); var user = ctx.GrantedUsers.GetByLogin(Login); if (user != null) { ctx.GrantedUsers.Remove(user); await ctx.SaveChangesAsync(); ctx.Database.Connection.Close(); ctx.Dispose(); if (MyHostEvent != null) { MyHostEvent(this, new MyHostEventArgs("UpdateUserInfoList", null)); } return("Success : " + Login); } else { ctx.Database.Connection.Close(); ctx.Dispose(); return("Failed : " + Login); } } catch (Exception exp) { return("Exception : " + exp.InnerException + "-" + exp.Message); } }
private async void EnrollUser() { if (SelectedUser != null) //Update existing { var ctx = await RemoteDatabase.GetDbContextAsync(); var original = ctx.GrantedUsers.Find(SelectedUser.Id); if (original != null) { var enrollForm = new EnrollFingersForm(original); if (!enrollForm.IsDisposed) { enrollForm.ShowDialog(); } } } else { await mainview0.ShowMessageAsync("INFORMATION", "Please create and save an user before enroll any fingerprint"); return; } PopulateUser(); }
private async void PopulateUser() { try { var ctx = await RemoteDatabase.GetDbContextAsync(); var lstDev = ctx.GrantedUsers .Where(u => u.UserRankId > 1).ToList(); EditedUser = new UsersViewModel(); DataUser.Clear(); foreach (var dv in lstDev) { UsersViewModel uvm = new UsersViewModel() { Id = dv.GrantedUserId, Login = dv.Login, FirstName = dv.FirstName, LastName = dv.LastName, BadgeId = dv.BadgeNumber, Fingerprints = dv.Fingerprints.Count }; DataUser.Add(uvm); } ctx.Database.Connection.Close(); ctx.Dispose(); } catch (Exception error) { await mainview0.Dispatcher.BeginInvoke(new System.Action(() => { ExceptionMessageBox exp = new ExceptionMessageBox(error, "Error in Populate Device"); exp.ShowDialog(); })); } }
private async void myDatagrid_Loaded(object sender, RoutedEventArgs e) { try { var ctx = await RemoteDatabase.GetDbContextAsync(); if (ctx.Columns != null && ctx.Columns.Count() > 0) { foreach (Column col in ctx.Columns) { myDatagrid.Columns[col.ColumnIndex].IsHidden = false; myDatagrid.Columns[col.ColumnIndex].HeaderText = col.ColumnName; } } myDatagrid.Columns["Drawer"].IsHidden = false; ctx.Database.Connection.Close(); ctx.Dispose(); } catch (Exception err) { ExceptionMessageBox exp = new ExceptionMessageBox(err, "Error Datagrid loaded"); exp.ShowDialog(); } }
private async void SaveUser() { if (EditedUser != null) { var ctx = await RemoteDatabase.GetDbContextAsync(); if (SelectedUser != null) //Update existing { if (string.IsNullOrEmpty(EditedUser.Login) || string.IsNullOrEmpty(EditedUser.FirstName) || string.IsNullOrEmpty(EditedUser.LastName)) { await mainview0.ShowMessageAsync("INFORMATION", "Please Fill user Login , Firstname and Lastname before saving"); return; } var original = ctx.GrantedUsers.Find(SelectedUser.Id); if (original != null) { original.Login = SelectedUser.Login; if (!string.IsNullOrWhiteSpace(SelectedUser.Password)) { original.Password = PasswordHashing.Sha256Of(SelectedUser.Password); } original.LastName = SelectedUser.LastName; original.FirstName = SelectedUser.FirstName; original.BadgeNumber = SelectedUser.BadgeId; ctx.Entry(original).State = EntityState.Modified; ctx.SaveChanges(); } } else //save new { if (string.IsNullOrEmpty(EditedUser.Login) || string.IsNullOrEmpty(EditedUser.FirstName) || string.IsNullOrEmpty(EditedUser.LastName)) { await mainview0.ShowMessageAsync("INFORMATION", "Please Fill user Login , Firstname and Lastname before saving"); return; } else { if (!string.IsNullOrWhiteSpace(EditedUser.Password)) { var original = ctx.GrantedUsers.Add(new GrantedUser() { Login = EditedUser.Login, Password = PasswordHashing.Sha256Of(EditedUser.Password), FirstName = EditedUser.FirstName, LastName = EditedUser.LastName, BadgeNumber = EditedUser.BadgeId, UserRankId = 3, }); } else { var original = ctx.GrantedUsers.Add(new GrantedUser() { Login = EditedUser.Login, FirstName = EditedUser.FirstName, LastName = EditedUser.LastName, BadgeNumber = EditedUser.BadgeId, UserRankId = 3, }); } } } ctx.Database.Connection.Close(); ctx.Dispose(); PopulateUser(); } }
public static async Task <bool> PostInventoryForDrawer(Device device, int drawerId, Inventory inventory) { 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(privateApiLogin, privateApiMdp); var request = new RestRequest("stockhistories", Method.POST); client.Timeout = timeout; client.ReadWriteTimeout = timeout; request.Timeout = timeout; request.ReadWriteTimeout = timeout; request.AddParameter("serial_num", device.DeviceSerial); request.AddParameter("drawer", drawerId.ToString()); request.AddParameter("created_at", inventory.InventoryDate.ToUniversalTime().ToString("u")); foreach (InventoryProduct ip in inventory.InventoryProducts) { switch (ip.MovementType) { case -1: request.AddParameter("removed_tags", ip.RfidTag.TagUid); break; case 0: request.AddParameter("present_tags", ip.RfidTag.TagUid); break; case 1: request.AddParameter("added_tags", ip.RfidTag.TagUid); break; } } var ctx = await RemoteDatabase.GetDbContextAsync(); var invUser = ctx.EventDrawerDetails.GetEventForDrawerByInventoryID(device, drawerId, inventory.InventoryId); if (invUser != null) { foreach (EventDrawerDetail edd in invUser) { if ((edd.GrantedUser != null) && (!string.IsNullOrEmpty(edd.GrantedUser.Login))) { request.AddParameter("user_login", edd.GrantedUser.Login); } } } var response = await client.ExecuteTaskAsync(request); LogToFile.LogMessageToFile(response.ResponseStatus.ToString()); LogToFile.LogMessageToFile(response.Content.ToString()); return(response.IsSuccessful); } catch (Exception error) { LogToFile.LogMessageToFile(error.InnerException.ToString()); LogToFile.LogMessageToFile(error.Message); LogToFile.LogMessageToFile(error.StackTrace); } return(false); }
public async Task <string> AddOrUpdateUser(Stream streamdata) { try { StreamReader reader = new StreamReader(streamdata); string res = reader.ReadToEnd(); reader.Close(); reader.Dispose(); JsonUser ju = JsonConvert.DeserializeObject <JsonUser>(res); if (ju != null) { var ctx = await RemoteDatabase.GetDbContextAsync(); var user = ctx.GrantedUsers.GetByServerId(ju.ServerUserId); if (user != null) //update { if (ju.Password != null) { user.Password = PasswordHashing.Sha256Of(ju.Password); } user.FirstName = ju.FirstName; user.LastName = ju.LastName; user.BadgeNumber = ju.BadgeNumber; ctx.Entry(user).State = EntityState.Modified; await ctx.SaveChangesAsync(); foreach (var dev in ctx.Devices) { ctx.GrantedAccesses.AddOrUpdateAccess(user, dev, ctx.GrantTypes.All()); } await ctx.SaveChangesAsync(); ctx.Database.Connection.Close(); ctx.Dispose(); return("Success : " + user.ServerGrantedUserId); } else //create { GrantedUser gu = new GrantedUser() { Login = ju.Login, ServerGrantedUserId = ju.ServerUserId, Password = ju.Password != null?PasswordHashing.Sha256Of(ju.Password) : PasswordHashing.Sha256Of("123456"), FirstName = ju.FirstName, LastName = ju.LastName, BadgeNumber = ju.BadgeNumber, UserRank = ctx.UserRanks.User(), }; ctx.GrantedUsers.Add(gu); await ctx.SaveChangesAsync(); foreach (var dev in ctx.Devices) { ctx.GrantedAccesses.AddOrUpdateAccess(gu, dev, ctx.GrantTypes.All()); } await ctx.SaveChangesAsync(); ctx.Database.Connection.Close(); ctx.Dispose(); if (MyHostEvent != null) { MyHostEvent(this, new MyHostEventArgs("UpdateUserInfoList", null)); } return("Success : " + gu.ServerGrantedUserId); } } return("Error : Bad Parameters"); } catch (Exception exp) { return("Exception : " + exp.InnerException + "-" + exp.Message); } }
public static async Task <bool> GetAndStoreSelectionAsync() { 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("selections", Method.GET); client.Timeout = timeout; client.ReadWriteTimeout = timeout; request.Timeout = timeout; request.ReadWriteTimeout = timeout; var response = await client.ExecuteTaskAsync(request); if (response.IsSuccessful) { var ctx = await RemoteDatabase.GetDbContextAsync(); ctx.PullItems.Clear(); await ctx.SaveChangesAsync(); lock (somePublicStaticObject) { var lstSelection = JsonSelectionList.DeserializedJsonList(response.Content); if ((lstSelection != null) && (lstSelection.Length > 0)) { foreach (var sel in lstSelection) { if (sel == null) { LogToFile.LogMessageToFile("------- Start Error in selection --------"); LogToFile.LogMessageToFile(response.Content); LogToFile.LogMessageToFile("------- End Error in selection --------"); break; } } lastSelection = lstSelection; } else { lastSelection = null; } ctx.Database.Connection.Close(); ctx.Dispose(); 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); } } return(false); } catch (Exception error) { ExceptionMessageBox exp = new ExceptionMessageBox(error, "Error getting selection"); exp.ShowDialog(); return(false); } }
public async Task <JsonDrawerInventory> getLastDrawerInventory(Stream streamdata) { try { StreamReader reader = new StreamReader(streamdata); string res = reader.ReadToEnd(); int drawerNb; reader.Close(); reader.Dispose(); if (int.TryParse(res, out drawerNb)) { if ((drawerNb <= 0) || (drawerNb > 7)) { JsonDrawerInventory ret = new JsonDrawerInventory(); ret.Status = "Failed"; ret.Reason = "Error : Bad Parameters"; ret.listOfTags = null; ret.listOfUserEvent = null; return(ret); } var ctx = await RemoteDatabase.GetDbContextAsync(); var LastDrawerInv = ctx.Inventories.GetLastInventoryforDrawer(drawerNb); if (LastDrawerInv != null) { JsonDrawerInventory ret = new JsonDrawerInventory(); ret.Status = "Success"; //ret.ServerDeviceId = LastDrawerInv.Device.ServerDeviceID; ret.DrawerNumber = LastDrawerInv.DrawerNumber; ret.InventoryDate = LastDrawerInv.InventoryDate; ret.TotalAdded = LastDrawerInv.TotalAdded; ret.TotalPresent = LastDrawerInv.TotalPresent; ret.TotalRemoved = LastDrawerInv.TotalRemoved; var invProducts = LastDrawerInv.InventoryProducts; if (invProducts != null) { List <TagInfo> lstTags = new List <TagInfo>(); int nIndex = 0; foreach (var tag in LastDrawerInv.InventoryProducts) { TagInfo ti = new TagInfo() { DrawerId = tag.Shelve, tagUID = tag.RfidTag.TagUid, Movement = tag.MovementType }; lstTags.Add(ti); } ret.listOfTags = lstTags.ToArray(); } var ListEvent = ctx.EventDrawerDetails.GetEventForDrawerByInventoryID(LastDrawerInv.Device, drawerNb, LastDrawerInv.InventoryId); if ((ListEvent != null)) { List <UserEventInfo> lstUserEventInfo = new List <UserEventInfo>(); foreach (var userEvent in ListEvent) { UserEventInfo uei = new UserEventInfo() { ServerGrantedUserId = userEvent.GrantedUser.ServerGrantedUserId, EventDrawerDate = userEvent.EventDrawerDate }; lstUserEventInfo.Add(uei); } ret.listOfUserEvent = lstUserEventInfo.ToArray(); } ctx.Database.Connection.Close(); ctx.Dispose(); return(ret); } else { JsonDrawerInventory ret = new JsonDrawerInventory(); ret.Status = "Failed"; ret.Reason = "No Inventory found"; ret.listOfTags = null; ret.listOfUserEvent = null; ctx.Database.Connection.Close(); ctx.Dispose(); return(ret); } } else { JsonDrawerInventory ret = new JsonDrawerInventory(); ret.Status = "Failed"; ret.Reason = "Error : Bad Parameters"; ret.listOfTags = null; ret.listOfUserEvent = null; return(ret); } } catch (Exception exp) { JsonDrawerInventory ret = new JsonDrawerInventory(); ret.Status = "Failed"; ret.Reason = "Exception : " + exp.InnerException + " - " + exp.Message; ret.listOfTags = null; ret.listOfUserEvent = null; return(ret); } }
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); } }