private void butUnlock_Click(object sender, EventArgs e) { if (!MsgBox.Show(this, true, "Users can become locked when invalid credentials have been entered several times in a row.\r\n" + "Unlock this user so that more log in attempts can be made?")) { return; } UserCur.DateTFail = DateTime.MinValue; UserCur.FailedAttempts = 0; try { Userods.Update(UserCur); //This will also commit other things about the user if they've changed. Oh well. MsgBox.Show(this, "User has been unlocked."); } catch (Exception) { MsgBox.Show(this, "There was a problem unlocking this user. Please call support or wait the allotted lock time."); } }
public void Authentication_UpdatePasswordSchema() { Userod user = Security.CurUser; bool result = Authentication.UpdatePasswordUserod(user, "brandSpankinNewPassword", HashTypes.SHA3_512); //If this is middletier, we need the password to match in our current user object to refill the cache Security.PasswordTyped = "brandSpankinNewPassword"; Userods.RefreshCache(); user = Userods.GetUser(user.UserNum); Assert.IsTrue(result); result = Authentication.CheckPassword(user, "brandSpankinNewPassword"); Assert.IsTrue(result); //Reset Security.CurUser password back to the unit test password Authentication.UpdatePasswordUserod(user, UnitTestPassword, HashTypes.SHA3_512); //Reset typed password Security.PasswordTyped = UnitTestPassword; Userods.RefreshCache(); Security.CurUser = Userods.GetUser(user.UserNum); }
public static void CreateUnitTestUser() { if (Userods.GetUserByName(UnitTestUserName, false) == null) { Userod newUser = new Userod() { UserName = UnitTestUserName, Password = Userods.HashPassword(UnitTestPassword), }; try { Userods.Insert(newUser, new List <long> { 1 }); Userods.RefreshCache(); } catch (Exception e) { throw new Exception("Unable to create the default Unit Test user.", e); } } }
public static void SetupClass(TestContext testContext) { _defRegionN = DefT.CreateDefinition(DefCat.Regions, "RegionN", "RegionN"); _defRegionS = DefT.CreateDefinition(DefCat.Regions, "RegionS", "RegionS"); _clinicN = ClinicT.CreateClinic("ClinicN", regionDef: _defRegionN); _clinicNW = ClinicT.CreateClinic("ClinicNW", regionDef: _defRegionN); _clinicS = ClinicT.CreateClinic("ClinicS", regionDef: _defRegionS); _patN = PatientT.CreatePatient("Tasks", clinicNum: _clinicN.ClinicNum, lName: _clinicN.Description, fName: "Patient"); _patS = PatientT.CreatePatient("Tasks", clinicNum: _clinicS.ClinicNum, lName: _clinicS.Description, fName: "Patient"); _userA = UserodT.CreateUser(userName: "******", clinicNum: _clinicN.ClinicNum, isClinicIsRestricted: false); _userNW = UserodT.CreateUser(userName: "******", clinicNum: _clinicNW.ClinicNum, isClinicIsRestricted: true); Userods.RefreshCache(); List <UserClinic> listUserClinics = new List <UserClinic>() { new UserClinic(_clinicNW.ClinicNum, _userNW.UserNum) }; if (UserClinics.Sync(listUserClinics, _userNW.UserNum)) //Either syncs new list, or clears old list if no longer restricted. { UserClinics.RefreshCache(); } }
private void FillListBox() { Userods.RefreshCache(); UserGroups.RefreshCache(); GroupPermissions.RefreshCache(); listUser.BeginUpdate(); listUser.Items.Clear(); if (PrefC.GetBool(PrefName.UserNameManualEntry)) { //Because _listUsers is used to verify the user name typed in, we need to include both non-hidden and CEMT users for offices that type in their credentials instead of picking. _listUsers = Userods.GetUsers(true); } else //This will be the most common way to fill the user list. Includes CEMT users. { _listUsers = Userods.GetUsers(true); } for (int i = 0; i < _listUsers.Count; i++) { listUser.Items.Add(_listUsers[i]); } listUser.SelectedIndex = 0; listUser.EndUpdate(); }
public static void Initialize(TestContext context) { if (!UnitTestsCore.DatabaseTools.SetDbConnection("unittest", "localhost", "3306", "root", "", false)) //Put this in a config file in the future. { UnitTestsCore.DatabaseTools.SetDbConnection("", "localhost", "3306", "root", "", false); DatabaseTools.FreshFromDump("localhost", "3306", "root", "", false); //this also sets database to be unittest. } else { //Clear the database before running the unittests (instead of after) for two reasons //1- if the cleanup is done using [TestCleanup], the cleanup will not be run if the user cancels in the middle of a test while debugging //2- if a test fails, we may want to look at the data in the db to see why it failed. UnitTestsCore.DatabaseTools.ClearDb(); } #if !DEBUG throw new Exception("You're running tests in release. BAD!!!"); #endif CreateUnitTestUser(); //Get the Admin user, should always exist Security.CurUser = Userods.GetUserByName(UnitTestUserName, false); Security.PasswordTyped = UnitTestPassword; //For middle tier unit tests. //Uncomment the next line in order to run every single unit test method like it is using the middle tier. //RunTestsAgainstMiddleTier(); }
public void SetupTest() { TaskListT.ClearTaskListTable(); TaskT.ClearTaskTable(); TaskSubscriptionT.ClearTaskSubscriptionTable(); SignalodT.ClearSignalodTable(); _taskListParent = TaskListT.CreateTaskList(descript: "TaskListParent"); _taskListChild = TaskListT.CreateTaskList(descript: "TaskListChild", parent: _taskListParent.TaskListNum, parentDesc: _taskListParent.Descript); _taskListGrandchild = TaskListT.CreateTaskList(descript: "TaskListGrandchild", parent: _taskListChild.TaskListNum, parentDesc: _taskListChild.Descript); _task = TaskT.CreateTask(_taskListGrandchild.TaskListNum, descript: "Test Task", fromNum: Security.CurUser.UserNum, priorityDefNum: 1); //Starts in _taskListGrandchild TaskSubscriptionT.CreateTaskSubscription(Security.CurUser.UserNum, _taskListParent.TaskListNum); //current user subscribes to top level tasklist. Security.CurUser.TaskListInBox = _taskListParent.TaskListNum; //Set inbox for current user to _taskListParent. try { Userods.Update(Security.CurUser); Userods.RefreshCache(); } catch { Assert.Fail("Failed to update current user task list inbox."); //Error updating user. } _formTaskEditInstance = new FormTaskEdit(_task); _formTaskEditAccessor = new PrivateObject(_formTaskEditInstance); _formTaskEditAccessor.Invoke("LoadTask"); }
///<summary>Inserts the new user, refreshes the cache and then returns UserNum</summary> public static Userod CreateUser(string userName = "", string password = "", List <long> userGroupNumbers = null, long clinicNum = 0, bool isClinicIsRestricted = false) { if (userName == "") { userName = "******" + MiscUtils.CreateRandomAlphaNumericString(8); } if (password == "") { password = "******"; } if (userGroupNumbers == null) { userGroupNumbers = new List <long> { 1 }; } Userod newUser = new Userod(); newUser.UserName = userName; newUser.LoginDetails = Authentication.GenerateLoginDetails(password, HashTypes.SHA3_512); newUser.ClinicNum = clinicNum; newUser.ClinicIsRestricted = isClinicIsRestricted; do { //In case the username is already taken try { newUser.UserNum = Userods.Insert(newUser, userGroupNumbers); } catch { newUser.UserName = "******" + MiscUtils.CreateRandomAlphaNumericString(8); } }while(newUser.UserNum == 0); Userods.RefreshCache(); UserGroupAttaches.RefreshCache(); return(newUser); }
public void Userods_CheckUserAndPassword_IncreaseFailedAttemptsAfterUserHasLoggedInButPasswordIsNotCorrect() { //First, setup the test scenario. //This test is intended to be tested on middle tier. long group1 = UserGroupT.CreateUserGroup("usergroup1"); Userod myUser = UserodT.CreateUser(MethodBase.GetCurrentMethod().Name + DateTime.Now.Ticks, "reallystrongpassword", userGroupNumbers: new List <long>() { group1 }); RunTestsAgainstMiddleTier(new OpenDentBusiness.WebServices.OpenDentalServerMockIIS(user: myUser.UserName, password: myUser.Password)); Security.CurUser = myUser; Security.PasswordTyped = "passwordguess#1"; CredentialsFailedAfterLoginEvent.Fired += CredentialsFailedAfterLoginEvent_Fired1; //make a single bad password attempt. ODException.SwallowAnyException(() => { Userods.CheckUserAndPassword(myUser.UserName, "passwordguess#1", false); }); //Get our user from the DB RunTestsAgainstDirectConnection(); myUser = Userods.GetUserByNameNoCache(myUser.UserName); //Asssert that the failed attempt got incremented correctly. Assert.AreEqual(1, myUser.FailedAttempts); }
///<summary>Syncs the database to reflect what is contained within listNew. Compares entries based on UserNumCEMT rather than primary keys.</summary> public static void Sync(List <Userod> listNew, ref List <Userod> listDB) { //Adding items to lists changes the order of operation. All inserts are completed first, then updates, then deletes. List <Userod> listIns = new List <Userod>(); List <Userod> listUpdNew = new List <Userod>(); List <Userod> listUpdDB = new List <Userod>(); List <Userod> listDel = new List <Userod>(); listNew.Sort((Userod x, Userod y) => { return(x.UserNumCEMT.CompareTo(y.UserNumCEMT)); }); //Anonymous function, sorts by compairing PK. Lambda expressions are not allowed, this is the one and only exception. JS approved. listDB.Sort((Userod x, Userod y) => { return(x.UserNumCEMT.CompareTo(y.UserNumCEMT)); }); //Anonymous function, sorts by compairing PK. Lambda expressions are not allowed, this is the one and only exception. JS approved. int idxNew = 0; int idxDB = 0; Userod fieldNew; Userod fieldDB; //Because both lists have been sorted using the same criteria, we can now walk each list to determine which list contians the next element. The next element is determined by Primary Key. //If the New list contains the next item it will be inserted. If the DB contains the next item, it will be deleted. If both lists contain the next item, the item will be updated. while (idxNew < listNew.Count || idxDB < listDB.Count) { fieldNew = null; if (idxNew < listNew.Count) { fieldNew = listNew[idxNew]; } fieldDB = null; if (idxDB < listDB.Count) { fieldDB = listDB[idxDB]; } //begin compare if (fieldNew != null && fieldDB == null) //listNew has more items, listDB does not. { listIns.Add(fieldNew); idxNew++; continue; } else if (fieldNew == null && fieldDB != null) //listDB has more items, listNew does not. { listDel.Add(fieldDB); idxDB++; continue; } else if (fieldNew.UserNumCEMT < fieldDB.UserNumCEMT) //newPK less than dbPK, newItem is 'next' { listIns.Add(fieldNew); idxNew++; continue; } else if (fieldNew.UserNumCEMT > fieldDB.UserNumCEMT) //dbPK less than newPK, dbItem is 'next' { listDel.Add(fieldDB); idxDB++; continue; } //Both lists contain the 'next' item, update required listUpdNew.Add(fieldNew); listUpdDB.Add(fieldDB); idxNew++; idxDB++; } //Commit changes to DB for (int i = 0; i < listIns.Count; i++) { Userods.InsertNoCache(listIns[i]); listDB.Add(listIns[i]); } for (int i = 0; i < listUpdNew.Count; i++) { Userods.UpdateCEMT(listUpdNew[i]); //listUpdNew gets populated by the list coming from the CEMT. Userods.Update uses primary key to update. Won't work. Need to make new update. } //for(int i=0;i<listDel.Count;i++) {//Userods can never be deleted. // Userods.DeleteCEMT(listDel[i].SuperUserNum); //} }
private void butOK_Click(object sender, EventArgs e) { Prefs.UpdateString(PrefName.CentralManagerPassHash, Userods.EncryptPassword(textPassword.Text)); Prefs.RefreshCache(); DialogResult = DialogResult.OK; }
public static void ClearPasswords() { var users = Userods.GetAll(); users.ForEach(x => { x.Password = ""; Userods.Update(x); }); }
///<summary>Generic function that launches different thread methods depending on how isSyncUsers and isSyncLocks are set. Set only one or the other to true.</summary> private static string SyncAll(List <CentralConnection> listConns, bool isSyncUsers, bool isSyncLocks) { //Get CEMT users, groups, and associated permissions ListSyncErrors = new List <string>(); _listCEMTUsers = Userods.GetUsersForCEMT(); _securityLockDate = PrefC.GetDate(PrefName.SecurityLockDate).ToShortDateString(); _securityLockDays = PrefC.GetInt(PrefName.SecurityLockDays); _securityLockAdmin = PrefC.GetBool(PrefName.SecurityLockIncludesAdmin); _securityCentralLock = PrefC.GetBool(PrefName.CentralManagerSecurityLock); _syncCode = PrefC.GetString(PrefName.CentralManagerSyncCode); _listAlertSubs = AlertSubs.GetAll(); List <CentralUserData> listCentralUserData = new List <CentralUserData>(); List <UserGroup> listUserGroups = UserGroups.GetCEMTGroups(); foreach (UserGroup userGroup in listUserGroups) //for each CEMT user group //get all usergroupattaches, userods, and grouppermissions. { List <UserGroupAttach> listUserGroupAttaches = UserGroupAttaches.GetForUserGroup(userGroup.UserGroupNum); List <Userod> listUserOds = Userods.GetForGroup(userGroup.UserGroupNum); List <GroupPermission> listGroupPermissions = GroupPermissions.GetPerms(userGroup.UserGroupNum); //then create a new CentralUserData and add it to the list. listCentralUserData.Add(new CentralUserData(userGroup, listUserOds, listGroupPermissions, listUserGroupAttaches)); } string failedConns = ""; string nameConflicts = ""; string failedSyncCodes = ""; for (int i = 0; i < listConns.Count; i++) { List <CentralUserData> listCentralDataForThreads = new List <CentralUserData>(); for (int j = 0; j < listCentralUserData.Count; j++) { listCentralDataForThreads.Add(listCentralUserData[j].Copy()); } ODThread odThread = null; if (isSyncUsers) { odThread = new ODThread(ConnectAndSyncUsers, new object[] { listConns[i], listCentralDataForThreads }); odThread.AddExceptionHandler(new ODThread.ExceptionDelegate(SyncExceptionHelper)); } else if (isSyncLocks) { odThread = new ODThread(ConnectAndSyncLocks, new object[] { listConns[i] }); odThread.AddExceptionHandler(new ODThread.ExceptionDelegate(SyncExceptionHelper)); } else { odThread = new ODThread(ConnectAndSyncAll, new object[] { listConns[i], listCentralDataForThreads }); odThread.AddExceptionHandler(new ODThread.ExceptionDelegate(SyncExceptionHelper)); } odThread.GroupName = "Sync"; odThread.Start(false); } ODThread.JoinThreadsByGroupName(Timeout.Infinite, "Sync"); List <ODThread> listComplThreads = ODThread.GetThreadsByGroupName("Sync"); for (int i = 0; i < listComplThreads.Count; i++) { if (listComplThreads[i].Tag == null) { continue; //Failed due to lacking credentials } failedConns += ((List <string>)listComplThreads[i].Tag)[0]; nameConflicts += ((List <string>)listComplThreads[i].Tag)[1]; failedSyncCodes += ((List <string>)listComplThreads[i].Tag)[2]; listComplThreads[i].QuitAsync(); } string errorText = ""; if (failedConns == "" && nameConflicts == "" && failedSyncCodes == "") { errorText += "Done"; } if (failedConns != "") { errorText = "Failed Connections:\r\n" + failedConns + "Please try these connections again.\r\n"; } if (nameConflicts != "") { errorText += "Name Conflicts:\r\n" + nameConflicts + "Please rename users and try again.\r\n"; } if (failedSyncCodes != "") { errorText += "Incorrect Sync Codes:\r\n" + failedSyncCodes + "\r\n"; } return(errorText); }
///<summary>Function used by threads to connect to remote databases and sync user settings.</summary> private static void ConnectAndSyncUsers(ODThread odThread) { CentralConnection connection = (CentralConnection)odThread.Parameters[0]; List <CentralUserData> listCentralUserData = (List <CentralUserData>)odThread.Parameters[1]; string serverName = ""; if (connection.ServiceURI != "") { serverName = connection.ServiceURI; } else { serverName = connection.ServerName + ", " + connection.DatabaseName; } if (!CentralConnectionHelper.UpdateCentralConnection(connection, false)) //No updating the cache since we're going to be connecting to multiple remote servers at the same time. { odThread.Tag = new List <string>() { serverName + "\r\n", "", "" }; connection.ConnectionStatus = "OFFLINE"; return; } string remoteSyncCode = PrefC.GetStringNoCache(PrefName.CentralManagerSyncCode); if (remoteSyncCode != _syncCode) { if (remoteSyncCode == "") { Prefs.UpdateStringNoCache(PrefName.CentralManagerSyncCode, _syncCode); //Lock in the sync code for the remote server. } else { odThread.Tag = new List <string>() { serverName + "\r\n", "", remoteSyncCode }; return; } } //Get remote users, usergroups, associated permissions, and alertsubs List <Userod> listRemoteUsers = Userods.GetUsersNoCache(); #region Detect Conflicts //User conflicts bool nameConflict = false; string nameConflicts = ""; for (int i = 0; i < _listCEMTUsers.Count; i++) { for (int j = 0; j < listRemoteUsers.Count; j++) { if (listRemoteUsers[j].UserName == _listCEMTUsers[i].UserName && listRemoteUsers[j].UserNumCEMT == 0) //User doesn't belong to CEMT { nameConflicts += listRemoteUsers[j].UserName + " already exists in " + serverName + "\r\n"; nameConflict = true; break; } } } if (nameConflict) { odThread.Tag = new List <string>() { serverName + "\r\n", nameConflicts, "" }; return; //Skip on to the next connection. } #endregion Detect Conflicts List <UserGroup> listRemoteCEMTUserGroups = UserGroups.GetCEMTGroupsNoCache(); List <UserGroup> listCEMTUserGroups = new List <UserGroup>(); List <AlertSub> listRemoteAlertSubs = AlertSubs.GetAll(); List <Clinic> listRemoteClinics = Clinics.GetClinicsNoCache(); List <AlertSub> listAlertSubsToInsert = new List <AlertSub>(); for (int i = 0; i < listCentralUserData.Count; i++) { listCEMTUserGroups.Add(listCentralUserData[i].UserGroup.Copy()); } //SyncUserGroups returns the list of UserGroups for deletion so it can be used after syncing Users and GroupPermissions. List <UserGroup> listRemoteCEMTUserGroupsForDeletion = CentralUserGroups.Sync(listCEMTUserGroups, listRemoteCEMTUserGroups); listRemoteCEMTUserGroups = UserGroups.GetCEMTGroupsNoCache(); for (int i = 0; i < listCentralUserData.Count; i++) { List <GroupPermission> listGroupPerms = new List <GroupPermission>(); for (int j = 0; j < listRemoteCEMTUserGroups.Count; j++) { if (listCentralUserData[i].UserGroup.UserGroupNumCEMT == listRemoteCEMTUserGroups[j].UserGroupNumCEMT) { for (int k = 0; k < listCentralUserData[i].ListGroupPermissions.Count; k++) { listCentralUserData[i].ListGroupPermissions[k].UserGroupNum = listRemoteCEMTUserGroups[j].UserGroupNum; //fixing primary keys to be what's in remote db } listGroupPerms = GroupPermissions.GetPermsNoCache(listRemoteCEMTUserGroups[j].UserGroupNum); } } CentralUserods.Sync(listCentralUserData[i].ListUsers, listRemoteUsers); CentralGroupPermissions.Sync(listCentralUserData[i].ListGroupPermissions, listGroupPerms); } //Sync usergroup attaches SyncUserGroupAttaches(listCentralUserData); for (int j = 0; j < listRemoteCEMTUserGroupsForDeletion.Count; j++) { UserGroups.DeleteNoCache(listRemoteCEMTUserGroupsForDeletion[j]); } if (_listAlertSubs.Count > 0) { listRemoteUsers = Userods.GetUsersNoCache(); //Refresh users so we can do alertsubs. } //For each AlertSub, make a copy of that AlertSub for each Clinic. foreach (AlertSub alertSub in _listAlertSubs) { foreach (Clinic clinic in listRemoteClinics) { AlertSub alert = new AlertSub(); alert.ClinicNum = clinic.ClinicNum; alert.Type = alertSub.Type; alert.UserNum = listRemoteUsers.Find(x => x.UserName == _listCEMTUsers.Find(y => y.UserNum == alertSub.UserNum).UserName).UserNum; listAlertSubsToInsert.Add(alert); } } AlertSubs.DeleteAndInsertForSuperUsers(_listCEMTUsers, listAlertSubsToInsert); //Refresh server's cache of userods Signalods.SetInvalidNoCache(InvalidType.Security); SecurityLogs.MakeLogEntryNoCache(Permissions.SecurityAdmin, 0, "Enterprise Management Tool synced users."); odThread.Tag = new List <string>() { "", "", "" }; //No errors. }
public string ProcessRequest(string dtoString) { //The web service (xml) serializer/deserializer is removing the '\r' portion of our newlines during the data transfer. //Replacing the string is not the best solution but it works for now. The replacing happens here (server side) and after result is returned on the client side. //It's done server side for usage purposes within the methods being called (exampe: inserting into db) and then on the client side for displaying purposes. dtoString = dtoString.Replace("\n", "\r\n"); #if DEBUG //System.Threading.Thread.Sleep(100);//to test slowness issues with web service. #endif DataTransferObject dto = DataTransferObject.Deserialize(dtoString); //XmlSerializer serializer; try { Type type = dto.GetType(); if (type == typeof(DtoGetTable)) { DtoGetTable dtoGetTable = (DtoGetTable)dto; Userods.CheckCredentials(dtoGetTable.Credentials); //will throw exception if fails. string className = dtoGetTable.MethodName.Split('.')[0]; string methodName = dtoGetTable.MethodName.Split('.')[1]; string assemb = Assembly.GetAssembly(typeof(Db)).FullName; //any OpenDentBusiness class will do. Type classType = Type.GetType("OpenDentBusiness." + className + "," + assemb); DtoObject[] parameters = dtoGetTable.Params; Type[] paramTypes = DtoObject.GenerateTypes(parameters, assemb); MethodInfo methodInfo = classType.GetMethod(methodName, paramTypes); if (methodInfo == null) { throw new ApplicationException("Method not found with " + parameters.Length.ToString() + " parameters: " + dtoGetTable.MethodName); } object[] paramObjs = DtoObject.GenerateObjects(parameters); DataTable dt = (DataTable)methodInfo.Invoke(null, paramObjs); String response = XmlConverter.TableToXml(dt); return(response); } else if (type == typeof(DtoGetTableLow)) { DtoGetTableLow dtoGetTableLow = (DtoGetTableLow)dto; Userods.CheckCredentials(dtoGetTableLow.Credentials); //will throw exception if fails. DtoObject[] parameters = dtoGetTableLow.Params; object[] paramObjs = DtoObject.GenerateObjects(parameters); DataTable dt = Reports.GetTable((string)paramObjs[0]); String response = XmlConverter.TableToXml(dt); return(response); } else if (type == typeof(DtoGetDS)) { DtoGetDS dtoGetDS = (DtoGetDS)dto; Userods.CheckCredentials(dtoGetDS.Credentials); //will throw exception if fails. string className = dtoGetDS.MethodName.Split('.')[0]; string methodName = dtoGetDS.MethodName.Split('.')[1]; string assemb = Assembly.GetAssembly(typeof(Db)).FullName; //any OpenDentBusiness class will do. Type classType = Type.GetType("OpenDentBusiness." + className + "," + assemb); DtoObject[] parameters = dtoGetDS.Params; Type[] paramTypes = DtoObject.GenerateTypes(parameters, assemb); MethodInfo methodInfo = classType.GetMethod(methodName, paramTypes); if (methodInfo == null) { throw new ApplicationException("Method not found with " + parameters.Length.ToString() + " parameters: " + dtoGetDS.MethodName); } object[] paramObjs = DtoObject.GenerateObjects(parameters); DataSet ds = (DataSet)methodInfo.Invoke(null, paramObjs); String response = XmlConverter.DsToXml(ds); return(response); } else if (type == typeof(DtoGetLong)) { DtoGetLong dtoGetLong = (DtoGetLong)dto; Userods.CheckCredentials(dtoGetLong.Credentials); //will throw exception if fails. string className = dtoGetLong.MethodName.Split('.')[0]; string methodName = dtoGetLong.MethodName.Split('.')[1]; string assemb = Assembly.GetAssembly(typeof(Db)).FullName; //any OpenDentBusiness class will do. Type classType = Type.GetType("OpenDentBusiness." + className + "," + assemb); DtoObject[] parameters = dtoGetLong.Params; Type[] paramTypes = DtoObject.GenerateTypes(parameters, assemb); MethodInfo methodInfo = classType.GetMethod(methodName, paramTypes); if (methodInfo == null) { throw new ApplicationException("Method not found with " + parameters.Length.ToString() + " parameters: " + dtoGetLong.MethodName); } object[] paramObjs = DtoObject.GenerateObjects(parameters); long longResult = (long)methodInfo.Invoke(null, paramObjs); return(longResult.ToString()); } else if (type == typeof(DtoGetInt)) { DtoGetInt dtoGetInt = (DtoGetInt)dto; Userods.CheckCredentials(dtoGetInt.Credentials); //will throw exception if fails. string className = dtoGetInt.MethodName.Split('.')[0]; string methodName = dtoGetInt.MethodName.Split('.')[1]; string assemb = Assembly.GetAssembly(typeof(Db)).FullName; //any OpenDentBusiness class will do. Type classType = Type.GetType("OpenDentBusiness." + className + "," + assemb); DtoObject[] parameters = dtoGetInt.Params; Type[] paramTypes = DtoObject.GenerateTypes(parameters, assemb); MethodInfo methodInfo = classType.GetMethod(methodName, paramTypes); if (methodInfo == null) { throw new ApplicationException("Method not found with " + parameters.Length.ToString() + " parameters: " + dtoGetInt.MethodName); } object[] paramObjs = DtoObject.GenerateObjects(parameters); int intResult = (int)methodInfo.Invoke(null, paramObjs); return(intResult.ToString()); } else if (type == typeof(DtoGetVoid)) { DtoGetVoid dtoGetVoid = (DtoGetVoid)dto; Userods.CheckCredentials(dtoGetVoid.Credentials); //will throw exception if fails. string className = dtoGetVoid.MethodName.Split('.')[0]; string methodName = dtoGetVoid.MethodName.Split('.')[1]; string assemb = Assembly.GetAssembly(typeof(Db)).FullName; //any OpenDentBusiness class will do. Type classType = Type.GetType("OpenDentBusiness." + className + "," + assemb); DtoObject[] parameters = dtoGetVoid.Params; Type[] paramTypes = DtoObject.GenerateTypes(parameters, assemb); MethodInfo methodInfo = classType.GetMethod(methodName, paramTypes); if (methodInfo == null) { throw new ApplicationException("Method not found with " + parameters.Length.ToString() + " parameters: " + dtoGetVoid.MethodName); } object[] paramObjs = DtoObject.GenerateObjects(parameters); methodInfo.Invoke(null, paramObjs); return("0"); } else if (type == typeof(DtoGetObject)) { DtoGetObject dtoGetObject = (DtoGetObject)dto; string className = dtoGetObject.MethodName.Split('.')[0]; string methodName = dtoGetObject.MethodName.Split('.')[1]; if (className != "Security" || methodName != "LogInWeb") //because credentials will be checked inside that method { Userods.CheckCredentials(dtoGetObject.Credentials); //will throw exception if fails. } string assemb = Assembly.GetAssembly(typeof(Db)).FullName; //any OpenDentBusiness class will do. Type classType = Type.GetType("OpenDentBusiness." + className + "," + assemb); DtoObject[] parameters = dtoGetObject.Params; Type[] paramTypes = DtoObject.GenerateTypes(parameters, assemb); MethodInfo methodInfo = classType.GetMethod(methodName, paramTypes); if (methodInfo == null) { throw new ApplicationException("Method not found with " + parameters.Length.ToString() + " parameters: " + dtoGetObject.MethodName); } if (className == "Security" && methodName == "LogInWeb") { string mappedPath = Server.MapPath("."); parameters[2] = new DtoObject(mappedPath, typeof(string)); //because we can't access this variable from within OpenDentBusiness. RemotingClient.RemotingRole = RemotingRole.ServerWeb; } object[] paramObjs = DtoObject.GenerateObjects(parameters); Object objResult = methodInfo.Invoke(null, paramObjs); Type returnType = methodInfo.ReturnType; return(XmlConverter.Serialize(returnType, objResult)); } else if (type == typeof(DtoGetString)) { DtoGetString dtoGetString = (DtoGetString)dto; Userods.CheckCredentials(dtoGetString.Credentials); //will throw exception if fails. string className = dtoGetString.MethodName.Split('.')[0]; string methodName = dtoGetString.MethodName.Split('.')[1]; string assemb = Assembly.GetAssembly(typeof(Db)).FullName; //any OpenDentBusiness class will do. Type classType = Type.GetType("OpenDentBusiness." + className + "," + assemb); DtoObject[] parameters = dtoGetString.Params; Type[] paramTypes = DtoObject.GenerateTypes(parameters, assemb); MethodInfo methodInfo = classType.GetMethod(methodName, paramTypes); if (methodInfo == null) { throw new ApplicationException("Method not found with " + parameters.Length.ToString() + " parameters: " + dtoGetString.MethodName); } object[] paramObjs = DtoObject.GenerateObjects(parameters); string strResult = (string)methodInfo.Invoke(null, paramObjs); //strResult=strResult.Replace("\r","\\r"); //return XmlConverter.Serialize(typeof(string),strResult); return(strResult); } else if (type == typeof(DtoGetBool)) { DtoGetBool dtoGetBool = (DtoGetBool)dto; Userods.CheckCredentials(dtoGetBool.Credentials); //will throw exception if fails. string className = dtoGetBool.MethodName.Split('.')[0]; string methodName = dtoGetBool.MethodName.Split('.')[1]; string assemb = Assembly.GetAssembly(typeof(Db)).FullName; //any OpenDentBusiness class will do. Type classType = Type.GetType("OpenDentBusiness." + className + "," + assemb); DtoObject[] parameters = dtoGetBool.Params; Type[] paramTypes = DtoObject.GenerateTypes(parameters, assemb); MethodInfo methodInfo = classType.GetMethod(methodName, paramTypes); if (methodInfo == null) { throw new ApplicationException("Method not found with " + parameters.Length.ToString() + " parameters: " + dtoGetBool.MethodName); } object[] paramObjs = DtoObject.GenerateObjects(parameters); bool boolResult = (bool)methodInfo.Invoke(null, paramObjs); return(boolResult.ToString()); } else { throw new NotSupportedException("Dto type not supported: " + type.FullName); } } catch (Exception e) { DtoException exception = new DtoException(); if (e.InnerException == null) { exception.Message = e.Message; } else { exception.Message = e.InnerException.Message; } return(exception.Serialize()); } }
public void AlertItems_CreateAlertsForNewWebmail() { //Test Sections: //Create 5 users, part of 2 providers. //Test adding an email for each provider, then clear alerts table. //Test adding 4 emails for each provider //Test adding 3 additional emails for 1 provider //Test marking 2 emails as read for 1 provider //Test marking all emails as read for 1 provider EmailMessageT.ClearEmailMessageTable(); //Clear out the emailmessage table List <Userod> listTestUsers = new List <Userod>(); //Create or reuse 5 users, and set their provnum to 1 or 2. There'll be 3 provnum=1 and 2 provnum=2 //In queries always filter by usernum because there may be users left over from other/old tests. for (int i = 0; i < 5; i++) { Userod user = UserodT.CreateUser(); user.ProvNum = i % 2 + 1; listTestUsers.Add(user); Userods.Update(user); } listTestUsers = listTestUsers.Distinct().ToList(); long examplePatnum = 2; //Patnum can be anything, needed for webmail. //Create one email for each provider. foreach (long provnum in listTestUsers.Select(x => x.ProvNum).Distinct()) { EmailMessageT.CreateWebMail(provnum, examplePatnum); } AlertItems_CreateAlertsForWebmailMethodCall(); //Count the total # of alertitem entries, not what the description is. string alertCount = DataCore.GetScalar("SELECT COUNT(*) FROM alertitem WHERE UserNum IN (" + string.Join(",", listTestUsers.Select(x => POut.Long(x.UserNum))) + ") AND Type=" + POut.Int((int)AlertType.WebMailRecieved)); Assert.AreEqual("5", alertCount); // //Clear out ALERT table and add some new emails AlertItemT.ClearAlertItemTable(); foreach (long provnum in listTestUsers.Select(x => x.ProvNum).Distinct()) { EmailMessageT.CreateWebMail(provnum, examplePatnum); EmailMessageT.CreateWebMail(provnum, examplePatnum); EmailMessageT.CreateWebMail(provnum, examplePatnum); EmailMessageT.CreateWebMail(provnum, examplePatnum); } //This section tests adding more unread emails, and changing the description of the alertitem Userod selectedUser = listTestUsers.First(); AlertItems_CreateAlertsForWebmailMethodCall(); alertCount = DataCore.GetScalar("SELECT Description FROM alertitem WHERE Type=" + POut.Int((int)AlertType.WebMailRecieved) + " AND UserNum=" + selectedUser.UserNum); Assert.AreEqual("5", alertCount); // //Add 3 more unread emails. EmailMessageT.CreateWebMail(selectedUser.ProvNum, examplePatnum); EmailMessageT.CreateWebMail(selectedUser.ProvNum, examplePatnum); EmailMessageT.CreateWebMail(selectedUser.ProvNum, examplePatnum); AlertItems_CreateAlertsForWebmailMethodCall(); alertCount = DataCore.GetScalar("SELECT Description FROM alertitem WHERE Type=" + POut.Int((int)AlertType.WebMailRecieved) + " AND UserNum=" + selectedUser.UserNum); Assert.AreEqual("8", alertCount); // //Mark 2 of the emails as read, to decrease the amount of unread emails string command = "UPDATE emailmessage SET SentOrReceived=" + POut.Int((int)EmailSentOrReceived.WebMailRecdRead) + " WHERE SentOrReceived=" + POut.Int((int)EmailSentOrReceived.WebMailReceived) + " AND ProvNumWebMail=" + POut.Long(selectedUser.ProvNum) + " LIMIT 2"; DataCore.NonQ(command); AlertItems_CreateAlertsForWebmailMethodCall(); alertCount = DataCore.GetScalar("SELECT Description FROM alertitem WHERE Type=" + POut.Int((int)AlertType.WebMailRecieved) + " AND UserNum=" + selectedUser.UserNum); Assert.AreEqual("6", alertCount); // //Now we mark all of this user's emails as read, as if that user has read all of their webmail. command = "UPDATE emailmessage SET SentOrReceived=" + POut.Int((int)EmailSentOrReceived.WebMailRecdRead) + " WHERE SentOrReceived=" + POut.Int((int)EmailSentOrReceived.WebMailReceived) + " AND ProvNumWebMail=" + POut.Long(selectedUser.ProvNum); DataCore.NonQ(command); AlertItems_CreateAlertsForWebmailMethodCall(); alertCount = DataCore.GetScalar("SELECT COUNT(*) FROM alertitem WHERE Type=" + POut.Int((int)AlertType.WebMailRecieved) + " AND UserNum=" + selectedUser.UserNum); Assert.AreEqual("0", alertCount); }