Set role employee from favorite - D365
Song Nghia - Technical Consultantclass SCA_SetRoleEmployeeDepentFavotite extends RunBaseBatch { FilePath filePath; Filename filename; CommaTextIo fileIO; Set fileSet; CommaIo commaIo; str currentFile; container lineCon; DialogField fieldUserId; UserId userId; UserInfo userInfo; SCA_PrivilegesOfUser privilegsOfUser; FromTime startTime; str elapsed; #AviFiles SysOperationProgress progressor; int timeOfDayTmp; #OCCRetryCount #File #AviFiles #define.CurrentVersion(1) #localmacro.CurrentList userId #endmacro Public static void main(Args _args) { SCA_SetRoleEmployeeDepentFavotite readFileData = SCA_SetRoleEmployeeDepentFavotite::construct(); ; if (readFileData.prompt()) { readFileData.run(); } } public static SCA_SetRoleEmployeeDepentFavotite construct() { return new SCA_SetRoleEmployeeDepentFavotite(); } public void run() { Name rolesName; startTime = timeNow(); // Set Dialog field value to find CustTable if (userId) { this.getFavoriteItemOfEmployee(userId); rolesName = this.createRoleForUser(userId); if(rolesName) this.addRoleToUser(userId, rolesName); Info(strFmt("User Id: %1, Roles name: %2 completed", userId, rolesName)); } else { error( 'Customer Account not found!'); } elapsed = timeConsumed(startTime, timeNow()); info(strFmt("Time run: %1", elapsed)); } public boolean getFromDialog() { // Retrieve values from Dialog userId = fieldUserId.value(); return super(); } public Object dialog() { Dialog dialog; ; dialog = super(); // Set a title for dialog dialog.caption( 'Create role for user'); // Add a new field to Dialog fieldUserId = dialog.addField( extendedTypeStr(UserId), 'UserId' ); return dialog; } public container pack() { return [#CurrentVersion, #CurrentList]; } public boolean unpack(container _packedClass) { Version version = RunBase::getVersion(_packedClass); switch (version) { case #CurrentVersion: [version,#CurrentList] = _packedClass; break; default: return false; } return true; } private void getAllMenuItemLoop(str _userId, str _menuItemName) { Name privilegeName, grantType, grantAllow; [privilegeName, grantType, grantAllow] = this.findPrivileges(_menuItemName); if(privilegeName && grantType && grantAllow) { try { ttsbegin; if(!SCA_PrivilegesOfUser::find(_userId, privilegeName)) { privilegsOfUser.clear(); privilegsOfUser.UserId = _userId; privilegsOfUser.Privilege = privilegeName; privilegsOfUser.PrivilegeDescription = strFmt("Privilege of user: %1", _userId); privilegsOfUser.GrantType = grantType; privilegsOfUser.GrantAllow = grantAllow; privilegsOfUser.insert(); } ttscommit; if(privilegeName && grantType && grantType) { Info(strFmt("%1 %2 %3 ", privilegeName, grantType, grantAllow)); } } catch { throw Error(strFmt("Cannot insert privilegs of user: %1", _userId )); } } } public void getDisplayInForm(str displayName) { Form myForm; FormBuildDesign design; FormBuildControl control; int cnt = 0; Set buttonsSet = new Set(Types::Class); Args args; Object _Object; FormControl _FormControl; FormMenuButtonControl _buttonControl; FormBuildFunctionButtonControl _menuButton; Name privilegeName, grantType, grantAllow; void findButtons(FormBuildControl _buildControl) { FormBuildControl buildControl; int i; ; if (_buildControl.controlCount() > 0) { for (i = 1; i <= _buildControl.controlCount(); i++) { try { _menuButton = _buildControl.controlNum(i); if(_menuButton.menuItemType() == MenuItemType::Display) { //info(_menuButton.menuItemName()); [privilegeName, grantType, grantAllow] = this.findPrivileges(_menuButton.menuItemName()); if(privilegeName && grantType && grantAllow) { try { ttsbegin; if(!SCA_PrivilegesOfUser::find(userId, privilegeName)) { privilegsOfUser.clear(); privilegsOfUser.UserId = userId; privilegsOfUser.Privilege = privilegeName; privilegsOfUser.PrivilegeDescription = strFmt("Privilege of user: %1", userId); privilegsOfUser.GrantType = grantType; privilegsOfUser.GrantAllow = grantAllow; privilegsOfUser.insert(); } ttscommit; if(privilegeName && grantType && grantType) { progressor.setText(strFmt("%1 %2 %3 ", privilegeName, grantType, grantAllow)); progressor.incCount(); progressor.update(false); //Info(strFmt("%1 %2 %3 ", privilegeName, grantType, grantAllow)); } } catch { throw Error(strFmt("Cannot insert privilegs of user: %1", userId )); } } } } catch { } buildControl = _buildControl.controlNum(i); findButtons(buildControl); } } else { if (classidget(_buildControl) == classnum(FormBuildButtonControl) || classidget(_buildControl) == classnum(FormBuildCommandButtonControl) || classidget(_buildControl) == classnum(FormBuildDropDialogButtonControl) || classidget(_buildControl) == classnum(FormBuildMenuButtonControl) || classidget(_buildControl) == classnum(FormBuildFunctionButtonControl)) { buttonsSet.add(_buildControl); } } } ; myForm = new Form(displayName); design = myForm.design(); for (cnt = 1; cnt <= design.controlCount(); cnt++) { try { _menuButton = design.controlNum(cnt).controlNum(cnt); if(_menuButton.menuItemType() == MenuItemType::Display) { info(_menuButton.menuItemName()); [privilegeName, grantType, grantAllow] = this.findPrivileges(_menuButton.menuItemName()); if(privilegeName && grantType && grantAllow) { try { ttsbegin; if(!SCA_PrivilegesOfUser::find(userId, privilegeName)) { privilegsOfUser.clear(); privilegsOfUser.UserId = userId; privilegsOfUser.Privilege = privilegeName; privilegsOfUser.PrivilegeDescription = strFmt("Privilege of user: %1", userId); privilegsOfUser.GrantType = grantType; privilegsOfUser.GrantAllow = grantAllow; privilegsOfUser.insert(); } ttscommit; if(privilegeName && grantType && grantType) Info(strFmt("%1 %2 %3 ", privilegeName, grantType, grantAllow)); } catch { throw Error(strFmt("Cannot insert privilegs of user: %1", userId )); } } } } catch { } control = design.controlNum(cnt); findButtons(control); } } //Cho nay lay dc form name = > buoc thiep theo lay dc cai menuitem name public void findMenuItem(str _menuItemName) { #AOT TreeNode root = TreeNode::findNode(#MenuItemsDisplayPath); TreeNode current; TreeNodeTraverser trav = new TreeNodeTraverser(root,false); current = trav.next(); while (current) { if ((current.AOTgetProperty('ObjectType') == "Form") && (current.AOTgetProperty('Name') == _menuItemName)) { info(strFmt("Menu Item inside display form %1",current.AOTgetProperty('Object'))); this.getDisplayInForm(current.AOTgetProperty('Object')); } current = trav.next(); } } private void getFavoriteItemOfEmployee(UserId _userId) { SysMenuNavigationFavoriteItemsTable favoriteTable; Name privilegeName, grantType, grantAllow; // Define XML Document and its nodes XmlDocument doc; Name privilegesName; XmlElement elementScript, elementName; XMLParseError xmlError; int i; while select favoriteTable where favoriteTable.UserId == _userId { progressor = SysOperationProgress::newGeneral(#AviFileMove, "Processing...", 2500); progressor.setCaption("@SYS8577"); progressor.setCaption(strFmt("Processing .. %1", favoriteTable.MenuItemName)); [privilegeName, grantType, grantAllow] = this.findPrivileges(favoriteTable.MenuItemName); if(privilegeName && grantType && grantAllow) { try { ttsbegin; if(!SCA_PrivilegesOfUser::find(_userId, privilegeName)) { privilegsOfUser.clear(); privilegsOfUser.UserId = _userId; privilegsOfUser.Privilege = privilegeName; privilegsOfUser.PrivilegeDescription = strFmt("Privilege of user: %1", _userId); privilegsOfUser.GrantType = grantType; privilegsOfUser.GrantAllow = grantAllow; privilegsOfUser.insert(); } ttscommit; if(privilegeName && grantType && grantType) { progressor.setText(strFmt("%1 %2 %3 ", privilegeName, grantType, grantAllow)); progressor.incCount(); progressor.update(false); } } catch { throw Error(strFmt("Cannot insert privilegs of user: %1", _userId )); } } this.findMenuItem(favoriteTable.MenuItemName); } } private container findPrivileges(Name _objectName) { System.IO.StreamReader reader; System.String stringLine; InteropPermission interopPermission; str file; int row = 1; int currentFileCount; str stringFile; container conResult; Name privilegesName, grantName, grantAllow; System.String[] filePaths = System.IO.Directory::GetFiles(@"C:\AOSService\PackagesLocalDirectory\", "*.xml*",System.IO.SearchOption::AllDirectories); int fileCount = filepaths.get_Length(); for(currentFileCount = 0; currentFileCount < fileCount ; ++currentFileCount) { file = filepaths.GetValue(currentFileCount).ToString(); if(strScan(file, "AxSecurityPrivilege", 0, strLen(file)) || strScan(file, "axsecurityprivilege", 0, strLen(file)) ) { reader = new System.IO.StreamReader(file); stringLine = reader.ReadLine(); stringFile = ""; while (!System.String::IsNullOrEmpty(stringLine)) { stringFile += stringLine; stringLine = reader.ReadLine(); } //Get privilegs of meuitem display conResult = this.getXML(stringFile, _objectName); //get all source in fom dc goi toi if(conPeek(conResult, 1)) { return conResult; } reader.Close(); reader.Dispose(); CodeAccessPermission::revertAssert(); } } return conResult; } ////// Find privilege from object Type and object name /// /// ///private container getXML(str strXML, str objectName) { // Define XML Document and its nodes XmlDocument doc; XmlNodeList vtvNodeList; XmlNode vtvNode; Name privilegesName; str grantAllow; //Nguyen doan script XmlElement elementScript, elementName, elementEntryPoints, elementEntryPointsRef, elementRefGrant, elementGrantDetail; XmlElement elementTemp; XMLParseError xmlError; int i ; try { doc = new XmlDocument(); doc.loadXml(strXML); elementScript = doc.getNamedElement("AxSecurityPrivilege"); elementName = elementScript.getNamedElement("Name"); elementEntryPoints = elementScript.getNamedElement("EntryPoints"); vtvNodeList = elementEntryPoints.childNodes(); for(i = 0; i < vtvNodeList.length() ; i++ ) { //Doan nay phia loop data ben trong, moi get het duoc //elementEntryPointsRef = elementEntryPoints.getNamedElement//("AxSecurityEntryPointReference"); elementEntryPointsRef = vtvNodeList.item(i); elementRefGrant = elementEntryPointsRef.getNamedElement("Grant"); //Get quyen cao nhat cua privileges if(elementRefGrant.getNamedElement("Delete") && elementRefGrant.getNamedElement("Delete").text() == "Allow") { if(elementEntryPointsRef.getNamedElement("ObjectName").text() == objectName) { return [elementName.text() , elementRefGrant.getNamedElement("Delete").name(), elementRefGrant.getNamedElement("Delete").text()]; } } //else get read else { if(elementRefGrant.getNamedElement("Read") && elementRefGrant.getNamedElement("Read").text() == "Allow") { if(elementEntryPointsRef.getNamedElement("ObjectName").text() == objectName) { return [elementName.text() , elementRefGrant.getNamedElement("Read").name(), elementRefGrant.getNamedElement("Read").text()]; } } } } } catch { return conNull(); } return conNull(); } private Name createRoleForUser(UserId _userId) { FileIoPermission permission; XMLDocument xmlDoc = XMLDocument::newBlank(); XMLNode rootNode; XMLNode NodeEmpl, NodeName, NodeDescript, NodeLabel, NodeDirectAccess, NodeDuty, NodePrivileges, NodeNamePri; XMLElement xmlElement; XMLText xmlText; HCMWorker HCMWorker; Name fileRoleName; FilePath linkFile; SCA_PrivilegesOfUser privilegesOfUser; ; fileRoleName = strFmt("SCA_%1_%2_Maintain", _userId, System.DateTime::get_UtcNow().ToString('yyyyMdHHmmss')); linkFile = @'C:\AOSService\PackagesLocalDirectory\Scancom\Scancom\AxSecurityRole\' + fileRoleName + ".xml"; try { permission= new FileIoPermission(linkFile,'w'); permission.assert(); xmlDoc = XMLDocument::newBlank(); // Create first line containing version info rootNode = xmlDoc.documentElement(); xmlElement = xmlDoc.createElement('AxSecurityRole'); rootNode = xmlDoc.appendChild(xmlElement); // Create a node for the name xmlElement = xmlDoc.createElement('Name'); NodeName = rootNode.appendChild(xmlElement); xmlText = xmlDoc.createTextNode(fileRoleName); NodeName.appendChild(xmlText); xmlElement = xmlDoc.createElement('Description'); NodeDescript = rootNode.appendChild(xmlElement); xmlText = xmlDoc.createTextNode("Description of role"); NodeDescript.appendChild(xmlText); xmlElement = xmlDoc.createElement("Label"); NodeLabel = rootNode.appendChild(xmlElement); xmlText = xmlDoc.createTextNode("Label of role"); NodeLabel.appendChild(xmlText); xmlElement = xmlDoc.createElement('Privileges'); NodeName = rootNode.appendChild(xmlElement); while select privilegesOfUser where privilegesOfUser.UserId == _userId { // Create a node for the address xmlElement = xmlDoc.createElement('AxSecurityPrivilegeReference'); NodePrivileges = NodeName.appendChild(xmlElement); xmlElement = xmlDoc.createElement('Name'); xmlText = xmlDoc.createTextNode(privilegesOfUser.Privilege); NodeNamePri = NodePrivileges.appendChild(xmlElement); NodeNamePri.appendChild(xmlText); } // Save the file xmldoc.save(linkFile); return fileRoleName; } catch { throw Error("Create role error"); } } private void addRoleToUser(UserId _userId, Name _roleName) { SecurityRole role; SecurityUserRole userRole; //Synchonice table sercurity role before insert data appl.dbSynchronize(tableNum("SecurityRole")); select role where role.AotName == _roleName; select * from userRole where userRole.SecurityRole == role.RecId && userRole.User == _userId; userRole.User = _userId; userRole.SecurityRole = role.RecId; userRole.AssignmentMode = RoleAssignmentMode::Manual; userRole.AssignmentStatus = RoleAssignmentStatus::Enabled; SecuritySegregationOfDuties::assignUserToRole(userRole, null); //Synchonice table sercurity appl.dbSynchronize(tableNum("SecurityUserRole")); } private void getFiles() { System.String[] files; System.Collections.IEnumerator enumerator; str file; try { fileSet = new Set(Types::Container); files = System.IO.Directory::GetFiles(filePath, '*.xml'); enumerator = files.GetEnumerator(); while(enumerator.MoveNext()) { file = enumerator.get_Current(); fileSet.add([file]); } } catch(Exception::Internal) { this.processCLRErrorException(); } catch(Exception::CLRError) { this.processCLRErrorException(); } } private void openFile() { FileIOPermission fileIOPermission; fileIOPermission = new FileIOPermission(filename, #io_read); fileIOPermission.assert(); commaIo = new CommaIo(filename, #io_read); if(commaIo && commaIo.status() == IO_Status::Ok) { commaIo.inRecordDelimiter(#delimiterCRLF); } else { throw error(strFmt("Error when opening file %1", filename)); } } private boolean readLine() { boolean readLine; if(commaIo && commaIo.status() == IO_Status::Ok) { lineCon = commaIo.read(); readLine = lineCon != conNull(); } else { lineCon = conNull(); readLine = false; } return readLine; } private void processCLRErrorException( boolean _throw = true ) { str strError; CLRObject exc; CLRObject innerExc; CLRObject clrExcMessage; exc = CLRInterop::getLastException(); if(exc) { clrExcMessage = exc.get_Message(); innerExc = exc.get_InnerException(); while(innerExc != null) { clrExcMessage = innerExc.get_Message(); innerExc = innerExc.get_InnerException(); } strError = CLRInterop::getAnyTypeForObject(clrExcMessage); error(strError); if (_throw) { throw error("Update has been cancelled"); } } } }